Repository: pactus-project/pactus Branch: main Commit: fa89e8025dc1 Files: 825 Total size: 14.1 MB Directory structure: gitextract_gyguei1v/ ├── .dockerignore ├── .editorconfig ├── .entire/ │ └── .gitignore ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ ├── PULL_REQUEST_TEMPLATE.md │ ├── actions/ │ │ └── windows-signing/ │ │ └── action.yml │ ├── codecov.yml │ ├── packager/ │ │ ├── js/ │ │ │ ├── grpc/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ └── jsonrpc/ │ │ │ ├── README.md │ │ │ └── package.json │ │ ├── packager.sh │ │ ├── python/ │ │ │ ├── grpc/ │ │ │ │ ├── README.md │ │ │ │ ├── pactus_grpc/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── __init__.pyi │ │ │ │ ├── pyproject.toml │ │ │ │ └── setup.py │ │ │ └── jsonrpc/ │ │ │ ├── README.md │ │ │ ├── pactus_jsonrpc/ │ │ │ │ └── __init__.py │ │ │ ├── pyproject.toml │ │ │ └── setup.py │ │ └── rust/ │ │ ├── grpc/ │ │ │ ├── Cargo.toml │ │ │ ├── README.md │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── jsonrpc/ │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── src/ │ │ └── lib.rs │ ├── releasers/ │ │ ├── linux/ │ │ │ └── pactus-gui.desktop │ │ ├── macos/ │ │ │ ├── Info.plist │ │ │ ├── gtk3-launcher.sh │ │ │ ├── gui.bundle │ │ │ ├── pactus.icns │ │ │ └── run-install-name-tool-change.sh │ │ ├── pactus_downloader.sh │ │ ├── releaser_cli.sh │ │ ├── releaser_gui_linux.sh │ │ ├── releaser_gui_macos.sh │ │ ├── releaser_gui_windows_build.sh │ │ ├── releaser_gui_windows_installer.sh │ │ └── windows/ │ │ ├── README.md │ │ ├── gtk-win-bundler.py │ │ ├── pactus-gui.manifest │ │ └── rsrc_windows_amd64.syso │ └── workflows/ │ ├── codeql.yml │ ├── coverage.yml │ ├── deadlock.yml │ ├── docker.yml │ ├── gui.yml │ ├── linting.yml │ ├── packager.yml │ ├── releaser.yml │ ├── semantic-pr.yml │ └── testing.yml ├── .gitignore ├── .golangci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── cmd/ │ ├── cmd.go │ ├── cmd_test.go │ ├── daemon/ │ │ ├── import.go │ │ ├── init.go │ │ ├── main.go │ │ ├── prune.go │ │ ├── start.go │ │ └── version.go │ ├── gtk/ │ │ ├── app/ │ │ │ └── run.go │ │ ├── assets/ │ │ │ ├── assets.go │ │ │ ├── css/ │ │ │ │ └── style.css │ │ │ ├── css.go │ │ │ ├── dialogs.go │ │ │ ├── icons.go │ │ │ ├── images.go │ │ │ ├── main_ui.go │ │ │ └── ui/ │ │ │ ├── dialog_about.ui │ │ │ ├── dialog_about_gtk.ui │ │ │ ├── dialog_address_details.ui │ │ │ ├── dialog_address_label.ui │ │ │ ├── dialog_address_private_key.ui │ │ │ ├── dialog_transaction_bond.ui │ │ │ ├── dialog_transaction_transfer.ui │ │ │ ├── dialog_transaction_unbond.ui │ │ │ ├── dialog_transaction_withdraw.ui │ │ │ ├── dialog_wallet_change_password.ui │ │ │ ├── dialog_wallet_create_address.ui │ │ │ ├── dialog_wallet_password.ui │ │ │ ├── dialog_wallet_set_default_fee.ui │ │ │ ├── dialog_wallet_show_seed.ui │ │ │ ├── main_window.ui │ │ │ ├── widget_committee.ui │ │ │ ├── widget_network.ui │ │ │ ├── widget_node.ui │ │ │ ├── widget_validator.ui │ │ │ └── widget_wallet.ui │ │ ├── controller/ │ │ │ ├── address_details_dialog_controller.go │ │ │ ├── address_label_dialog_controller.go │ │ │ ├── address_private_key_dialog_controller.go │ │ │ ├── committee_widget_controller.go │ │ │ ├── controller.go │ │ │ ├── main_window_controller.go │ │ │ ├── navigator.go │ │ │ ├── network_widget_controller.go │ │ │ ├── node_widget_controller.go │ │ │ ├── password_prompt.go │ │ │ ├── tx_bond_dialog_controller.go │ │ │ ├── tx_transfer_dialog_controller.go │ │ │ ├── tx_unbond_dialog_controller.go │ │ │ ├── tx_withdraw_dialog_controller.go │ │ │ ├── validator_widget_controller.go │ │ │ ├── wallet_change_password_dialog_controller.go │ │ │ ├── wallet_create_address_dialog_controller.go │ │ │ ├── wallet_default_fee_dialog_controller.go │ │ │ ├── wallet_password_dialog_controller.go │ │ │ ├── wallet_seed_dialog_controller.go │ │ │ └── wallet_widget_controller.go │ │ ├── gtkutil/ │ │ │ ├── format.go │ │ │ ├── format_test.go │ │ │ ├── gtkutil.go │ │ │ └── gtkutil_test.go │ │ ├── main.go │ │ ├── model/ │ │ │ ├── committee_model.go │ │ │ ├── network_model.go │ │ │ ├── node_model.go │ │ │ ├── validator_model.go │ │ │ └── wallet_model.go │ │ ├── startup_assistant.go │ │ └── view/ │ │ ├── about_dialog_view.go │ │ ├── about_gtk_dialog_view.go │ │ ├── address_details_dialog_view.go │ │ ├── address_label_dialog_view.go │ │ ├── address_private_key_dialog_view.go │ │ ├── committee_widget_view.go │ │ ├── main_window_view.go │ │ ├── network_widget_view.go │ │ ├── node_widget_view.go │ │ ├── splash_window_view.go │ │ ├── tx_bond_dialog_view.go │ │ ├── tx_transfer_dialog_view.go │ │ ├── tx_unbond_dialog_view.go │ │ ├── tx_withdraw_dialog_view.go │ │ ├── validator_widget_view.go │ │ ├── view_builder.go │ │ ├── wallet_change_password_dialog_view.go │ │ ├── wallet_create_address_dialog_view.go │ │ ├── wallet_default_fee_dialog_view.go │ │ ├── wallet_password_dialog_view.go │ │ ├── wallet_seed_dialog_view.go │ │ └── wallet_widget_view.go │ ├── helper.go │ ├── importer.go │ ├── shell/ │ │ ├── main.go │ │ └── main_test.go │ └── wallet/ │ ├── address.go │ ├── create.go │ ├── fee.go │ ├── info.go │ ├── main.go │ ├── neuter.go │ ├── password.go │ ├── recover.go │ ├── send.go │ └── transaction.go ├── committee/ │ ├── committee.go │ ├── committee_test.go │ └── interface.go ├── config/ │ ├── banned_addrs.json │ ├── bootstrap.json │ ├── config.go │ ├── config_test.go │ ├── errors.go │ └── example_config.toml ├── consensus/ │ ├── commit.go │ ├── config.go │ ├── config_test.go │ ├── consensus.go │ ├── consensus_test.go │ ├── cp.go │ ├── cp_decide.go │ ├── cp_mainvote.go │ ├── cp_prevote.go │ ├── cp_test.go │ ├── errors.go │ ├── height.go │ ├── height_test.go │ ├── interface.go │ ├── log/ │ │ ├── log.go │ │ ├── log_test.go │ │ └── messages.go │ ├── manager/ │ │ ├── interface.go │ │ ├── manager.go │ │ ├── manager_test.go │ │ └── mock.go │ ├── mediator.go │ ├── mock.go │ ├── precommit.go │ ├── precommit_test.go │ ├── prepare.go │ ├── prepare_test.go │ ├── propose.go │ ├── propose_test.go │ ├── spec/ │ │ ├── .gitignore │ │ ├── Pactus.cfg │ │ ├── Pactus.tla │ │ └── README.md │ ├── state.go │ ├── ticker.go │ └── voteset/ │ ├── binary_voteset.go │ ├── block_voteset.go │ ├── errors.go │ ├── vote_box.go │ ├── vote_box_test.go │ ├── voteset.go │ └── voteset_test.go ├── consensusv2/ │ ├── commit.go │ ├── config.go │ ├── config_test.go │ ├── consensus.go │ ├── consensus_test.go │ ├── cp.go │ ├── cp_decide.go │ ├── cp_mainvote.go │ ├── cp_prevote.go │ ├── cp_test.go │ ├── errors.go │ ├── height.go │ ├── height_test.go │ ├── log/ │ │ ├── log.go │ │ ├── log_test.go │ │ └── messages.go │ ├── mediator.go │ ├── precommit.go │ ├── precommit_test.go │ ├── propose.go │ ├── propose_test.go │ ├── spec/ │ │ ├── .gitignore │ │ ├── Pactus.cfg │ │ ├── Pactus.tla │ │ └── README.md │ ├── state.go │ ├── ticker.go │ └── voteset/ │ ├── binary_voteset.go │ ├── block_voteset.go │ ├── errors.go │ ├── vote_box.go │ ├── vote_box_test.go │ ├── voteset.go │ └── voteset_test.go ├── crypto/ │ ├── address.go │ ├── address_test.go │ ├── address_type.go │ ├── bls/ │ │ ├── bls.go │ │ ├── bls_bench_test.go │ │ ├── bls_test.go │ │ ├── errors.go │ │ ├── hdkeychain/ │ │ │ ├── errors.go │ │ │ ├── extendedkey.go │ │ │ └── extendedkey_test.go │ │ ├── private_key.go │ │ ├── private_key_test.go │ │ ├── public_key.go │ │ ├── public_key_test.go │ │ ├── signature.go │ │ ├── signature_test.go │ │ ├── validator_key.go │ │ └── validator_key_test.go │ ├── crypto.go │ ├── ed25519/ │ │ ├── ed25519.go │ │ ├── ed25519_test.go │ │ ├── errors.go │ │ ├── hdkeychain/ │ │ │ ├── errors.go │ │ │ ├── extendedkey.go │ │ │ └── extendedkey_test.go │ │ ├── private_key.go │ │ ├── private_key_test.go │ │ ├── public_key.go │ │ ├── public_key_test.go │ │ ├── signature.go │ │ └── signature_test.go │ ├── errors.go │ ├── hash/ │ │ ├── errors.go │ │ ├── hash.go │ │ └── hash_test.go │ ├── private_key.go │ ├── public_key.go │ └── signature.go ├── docs/ │ ├── bootstrap.md │ ├── gtk-gui-development.md │ ├── install.md │ ├── metrics.md │ ├── patching.md │ ├── release-candidate.md │ ├── releasing.md │ └── update-dependencies.md ├── execution/ │ ├── errors.go │ ├── execution.go │ ├── execution_test.go │ └── executor/ │ ├── batch_transfer.go │ ├── batch_transfer_test.go │ ├── bond.go │ ├── bond_test.go │ ├── errors.go │ ├── executor.go │ ├── executor_test.go │ ├── sortition.go │ ├── sortition_test.go │ ├── transfer.go │ ├── transfer_test.go │ ├── unbond.go │ ├── unbond_test.go │ ├── withdraw.go │ └── withdraw_test.go ├── genesis/ │ ├── genesis.go │ ├── genesis_params.go │ ├── genesis_test.go │ ├── mainnet.go │ ├── mainnet.json │ ├── testnet.go │ └── testnet.json ├── go.mod ├── go.sum ├── network/ │ ├── config.go │ ├── config_test.go │ ├── dht.go │ ├── errors.go │ ├── gater.go │ ├── gater_test.go │ ├── gossip.go │ ├── gossip_test.go │ ├── interface.go │ ├── mdns.go │ ├── mdns_test.go │ ├── mock.go │ ├── network.go │ ├── network_test.go │ ├── notifee.go │ ├── peermgr.go │ ├── peermgr_test.go │ ├── stream.go │ ├── stream_test.go │ ├── utils.go │ └── utils_test.go ├── node/ │ ├── node.go │ └── node_test.go ├── sandbox/ │ ├── interface.go │ ├── mock.go │ ├── sandbox.go │ └── sandbox_test.go ├── scripts/ │ └── snapshot.py ├── sortition/ │ ├── proof.go │ ├── proof_test.go │ ├── seed.go │ ├── seed_test.go │ ├── sortition.go │ ├── sortition_test.go │ ├── vrf.go │ └── vrf_test.go ├── state/ │ ├── errors.go │ ├── execution.go │ ├── execution_test.go │ ├── facade.go │ ├── lastinfo/ │ │ ├── last_info.go │ │ └── last_info_test.go │ ├── mock.go │ ├── param/ │ │ ├── foundation_mainnet.json │ │ ├── foundation_testnet.json │ │ └── param.go │ ├── score/ │ │ ├── score.go │ │ └── score_test.go │ ├── state.go │ ├── state_test.go │ ├── validation.go │ └── validation_test.go ├── store/ │ ├── account.go │ ├── account_test.go │ ├── block.go │ ├── block_test.go │ ├── config.go │ ├── config_test.go │ ├── errors.go │ ├── interface.go │ ├── mock.go │ ├── store.go │ ├── store_test.go │ ├── tx.go │ ├── validator.go │ └── validator_test.go ├── sync/ │ ├── bundle/ │ │ ├── bundle.go │ │ ├── bundle_test.go │ │ └── message/ │ │ ├── block_announce.go │ │ ├── block_announce_test.go │ │ ├── blocks_request.go │ │ ├── blocks_request_test.go │ │ ├── blocks_response.go │ │ ├── blocks_response_test.go │ │ ├── errors.go │ │ ├── hello.go │ │ ├── hello_ack.go │ │ ├── hello_ack_test.go │ │ ├── hello_test.go │ │ ├── message.go │ │ ├── message_test.go │ │ ├── proposal.go │ │ ├── proposal_test.go │ │ ├── query_proposal.go │ │ ├── query_proposal_test.go │ │ ├── query_votes.go │ │ ├── query_votes_test.go │ │ ├── transactions.go │ │ ├── transactions_test.go │ │ ├── vote.go │ │ └── vote_test.go │ ├── cache/ │ │ ├── cache.go │ │ └── cache_test.go │ ├── config.go │ ├── config_test.go │ ├── firewall/ │ │ ├── config.go │ │ ├── errors.go │ │ ├── firewall.go │ │ └── firewall_test.go │ ├── handler.go │ ├── handler_block_announce.go │ ├── handler_block_announce_test.go │ ├── handler_blocks_request.go │ ├── handler_blocks_request_test.go │ ├── handler_blocks_response.go │ ├── handler_blocks_response_test.go │ ├── handler_hello.go │ ├── handler_hello_ack.go │ ├── handler_hello_ack_test.go │ ├── handler_hello_test.go │ ├── handler_proposal.go │ ├── handler_proposal_test.go │ ├── handler_query_proposal.go │ ├── handler_query_proposal_test.go │ ├── handler_query_votes.go │ ├── handler_query_votes_test.go │ ├── handler_transactions.go │ ├── handler_transactions_test.go │ ├── handler_vote.go │ ├── handler_vote_test.go │ ├── interface.go │ ├── mock.go │ ├── peerset/ │ │ ├── peer/ │ │ │ ├── metric/ │ │ │ │ ├── metric.go │ │ │ │ └── metric_test.go │ │ │ ├── peer.go │ │ │ ├── peer_test.go │ │ │ ├── service/ │ │ │ │ ├── services.go │ │ │ │ └── services_test.go │ │ │ └── status/ │ │ │ └── status.go │ │ ├── peer_set.go │ │ ├── peer_set_test.go │ │ └── session/ │ │ ├── manager.go │ │ ├── session.go │ │ └── stats.go │ ├── sync.go │ └── sync_test.go ├── tests/ │ ├── account_test.go │ ├── block_test.go │ ├── main_test.go │ ├── transaction_test.go │ └── validator_test.go ├── txpool/ │ ├── config.go │ ├── config_test.go │ ├── errors.go │ ├── interface.go │ ├── pool.go │ ├── txpool.go │ ├── txpool_mock.go │ └── txpool_test.go ├── types/ │ ├── account/ │ │ ├── account.go │ │ └── account_test.go │ ├── amount/ │ │ ├── amount.go │ │ ├── amount_test.go │ │ └── errors.go │ ├── block/ │ │ ├── block.go │ │ ├── block_test.go │ │ ├── errors.go │ │ ├── header.go │ │ ├── txs.go │ │ └── txs_test.go │ ├── certificate/ │ │ ├── certificate.go │ │ ├── certificate_test.go │ │ ├── errors.go │ │ ├── power.go │ │ └── power_test.go │ ├── height.go │ ├── height_test.go │ ├── proposal/ │ │ ├── errors.go │ │ ├── proposal.go │ │ └── proposal_test.go │ ├── protocol/ │ │ ├── protocol.go │ │ └── protocol_test.go │ ├── round.go │ ├── round_test.go │ ├── tx/ │ │ ├── errors.go │ │ ├── factory.go │ │ ├── payload/ │ │ │ ├── batch_transfer.go │ │ │ ├── batch_transfer_test.go │ │ │ ├── bond.go │ │ │ ├── bond_test.go │ │ │ ├── errors.go │ │ │ ├── payload.go │ │ │ ├── sortition.go │ │ │ ├── sortition_test.go │ │ │ ├── transfer.go │ │ │ ├── transfer_test.go │ │ │ ├── unbond.go │ │ │ ├── unbond_test.go │ │ │ ├── withdraw.go │ │ │ └── withdraw_test.go │ │ ├── tx.go │ │ └── tx_test.go │ ├── validator/ │ │ ├── validator.go │ │ └── validator_test.go │ └── vote/ │ ├── cp_just.go │ ├── cp_vote.go │ ├── errors.go │ ├── vote.go │ ├── vote_test.go │ └── vote_type.go ├── util/ │ ├── bech32m/ │ │ ├── bech32m.go │ │ ├── bech32m_test.go │ │ └── error.go │ ├── bip39/ │ │ ├── README.md │ │ ├── bip39.go │ │ ├── bip39_test.go │ │ ├── example_test.go │ │ └── wordlists/ │ │ ├── chinese_simplified.go │ │ ├── chinese_traditional.go │ │ ├── czech.go │ │ ├── english.go │ │ ├── french.go │ │ ├── italian.go │ │ ├── japanese.go │ │ ├── korean.go │ │ └── spanish.go │ ├── downloader/ │ │ ├── chunk.go │ │ ├── chunk_test.go │ │ ├── downloader.go │ │ ├── downloader_test.go │ │ ├── errors.go │ │ └── options.go │ ├── encoding/ │ │ ├── encoding.go │ │ └── encoding_test.go │ ├── htpasswd/ │ │ ├── htpasswd.go │ │ └── htpasswd_test.go │ ├── io.go │ ├── io_test.go │ ├── ipblocker/ │ │ ├── ipblocker.go │ │ └── ipblocker_test.go │ ├── linkedlist/ │ │ ├── linkedlist.go │ │ └── linkedlist_test.go │ ├── linkedmap/ │ │ ├── linkedmap.go │ │ └── linkedmap_test.go │ ├── logger/ │ │ ├── config.go │ │ ├── logger.go │ │ └── logger_test.go │ ├── net.go │ ├── ntp/ │ │ ├── ntp.go │ │ ├── ntp_test.go │ │ └── query.go │ ├── number.go │ ├── number_test.go │ ├── pairslice/ │ │ ├── pairslice.go │ │ └── pairslice_test.go │ ├── persistentmerkle/ │ │ ├── merkle.go │ │ └── merkle_test.go │ ├── prompt/ │ │ └── prompt.go │ ├── ratelimit/ │ │ ├── ratelimit.go │ │ └── ratelimit_test.go │ ├── shell/ │ │ ├── shell.go │ │ └── shell_test.go │ ├── simplemerkle/ │ │ ├── merkle.go │ │ ├── merkle_test.go │ │ └── printing.go │ ├── slice.go │ ├── slice_test.go │ ├── terminal/ │ │ ├── terminal.go │ │ └── terminal_test.go │ ├── testsuite/ │ │ ├── logger.go │ │ └── testsuite.go │ ├── time.go │ ├── time_test.go │ ├── utils.go │ └── utils_test.go ├── version/ │ ├── agent.go │ ├── agent_test.go │ ├── version.go │ ├── version.json │ └── version_test.go ├── wallet/ │ ├── addresses.go │ ├── addresses_test.go │ ├── addresspath/ │ │ ├── errors.go │ │ ├── path.go │ │ └── path_test.go │ ├── encrypter/ │ │ ├── encrypter.go │ │ ├── encrypter_test.go │ │ ├── error.go │ │ ├── params.go │ │ └── params_test.go │ ├── errors.go │ ├── manager/ │ │ ├── config.go │ │ ├── config_test.go │ │ ├── errors.go │ │ ├── interface.go │ │ ├── manager.go │ │ ├── manager_mock.go │ │ └── manager_test.go │ ├── provider/ │ │ ├── interface.go │ │ ├── local/ │ │ │ └── local.go │ │ ├── offline/ │ │ │ └── offline.go │ │ ├── provider_mock.go │ │ └── remote/ │ │ ├── errors.go │ │ ├── remote.go │ │ ├── servers.go │ │ └── servers.json │ ├── storage/ │ │ ├── errors.go │ │ ├── interface.go │ │ ├── jsonstorage/ │ │ │ ├── errors.go │ │ │ ├── storage.go │ │ │ ├── storage_test.go │ │ │ ├── store.go │ │ │ ├── testdata/ │ │ │ │ ├── neuter_wallet │ │ │ │ ├── testnet_wallet │ │ │ │ ├── unsupported_wallet │ │ │ │ ├── wallet_version_1 │ │ │ │ ├── wallet_version_2 │ │ │ │ ├── wallet_version_3 │ │ │ │ ├── wallet_version_4 │ │ │ │ └── wallet_version_5 │ │ │ ├── upgrader.go │ │ │ ├── upgrader_test.go │ │ │ └── version.go │ │ ├── sqlitestorage/ │ │ │ ├── options.go │ │ │ ├── sql.go │ │ │ ├── storage.go │ │ │ ├── storage_test.go │ │ │ └── version.go │ │ └── storage_mock.go │ ├── transactions.go │ ├── transactions_test.go │ ├── tx_builder.go │ ├── types/ │ │ └── types.go │ ├── vault/ │ │ ├── errors.go │ │ ├── utils.go │ │ ├── utils_test.go │ │ ├── vault.go │ │ └── vault_test.go │ ├── wallet.go │ └── wallet_test.go └── www/ ├── grpc/ │ ├── README.md │ ├── basicauth/ │ │ ├── basicauth.go │ │ └── basicauth_test.go │ ├── blockchain.go │ ├── blockchain_test.go │ ├── buf/ │ │ ├── buf.gen.yaml │ │ ├── buf.yaml │ │ ├── grpc-gateway.config.yaml │ │ ├── openapi.config.yaml │ │ └── templates/ │ │ ├── components.tmpl │ │ ├── grpc.md.tmpl │ │ ├── json-rpc.md.tmpl │ │ └── openrpc.tmpl │ ├── config.go │ ├── gen/ │ │ ├── dart/ │ │ │ ├── blockchain.pb.dart │ │ │ ├── blockchain.pbenum.dart │ │ │ ├── blockchain.pbjson.dart │ │ │ ├── blockchain.pbserver.dart │ │ │ ├── network.pb.dart │ │ │ ├── network.pbenum.dart │ │ │ ├── network.pbjson.dart │ │ │ ├── network.pbserver.dart │ │ │ ├── transaction.pb.dart │ │ │ ├── transaction.pbenum.dart │ │ │ ├── transaction.pbjson.dart │ │ │ ├── transaction.pbserver.dart │ │ │ ├── utils.pb.dart │ │ │ ├── utils.pbenum.dart │ │ │ ├── utils.pbjson.dart │ │ │ ├── utils.pbserver.dart │ │ │ ├── wallet.pb.dart │ │ │ ├── wallet.pbenum.dart │ │ │ ├── wallet.pbjson.dart │ │ │ └── wallet.pbserver.dart │ │ ├── docs/ │ │ │ ├── grpc.md │ │ │ └── json-rpc.md │ │ ├── go/ │ │ │ ├── blockchain.cobra.pb.go │ │ │ ├── blockchain.pb.go │ │ │ ├── blockchain.pb.gw.go │ │ │ ├── blockchain_grpc.pb.go │ │ │ ├── blockchain_jgw.pb.go │ │ │ ├── network.cobra.pb.go │ │ │ ├── network.pb.go │ │ │ ├── network.pb.gw.go │ │ │ ├── network_grpc.pb.go │ │ │ ├── network_jgw.pb.go │ │ │ ├── transaction.cobra.pb.go │ │ │ ├── transaction.pb.go │ │ │ ├── transaction.pb.gw.go │ │ │ ├── transaction_grpc.pb.go │ │ │ ├── transaction_jgw.pb.go │ │ │ ├── utils.cobra.pb.go │ │ │ ├── utils.pb.go │ │ │ ├── utils.pb.gw.go │ │ │ ├── utils_grpc.pb.go │ │ │ ├── utils_jgw.pb.go │ │ │ ├── wallet.cobra.pb.go │ │ │ ├── wallet.pb.go │ │ │ ├── wallet.pb.gw.go │ │ │ ├── wallet_grpc.pb.go │ │ │ └── wallet_jgw.pb.go │ │ ├── java/ │ │ │ └── pactus/ │ │ │ ├── BlockchainGrpc.java │ │ │ ├── BlockchainOuterClass.java │ │ │ ├── NetworkGrpc.java │ │ │ ├── NetworkOuterClass.java │ │ │ ├── TransactionGrpc.java │ │ │ ├── TransactionOuterClass.java │ │ │ ├── UtilsGrpc.java │ │ │ ├── UtilsOuterClass.java │ │ │ ├── WalletGrpc.java │ │ │ └── WalletOuterClass.java │ │ ├── js/ │ │ │ ├── blockchain_grpc_pb.js │ │ │ ├── blockchain_grpc_web_pb.js │ │ │ ├── blockchain_pb.js │ │ │ ├── network_grpc_pb.js │ │ │ ├── network_grpc_web_pb.js │ │ │ ├── network_pb.js │ │ │ ├── transaction_grpc_pb.js │ │ │ ├── transaction_grpc_web_pb.js │ │ │ ├── transaction_pb.js │ │ │ ├── utils_grpc_pb.js │ │ │ ├── utils_grpc_web_pb.js │ │ │ ├── utils_pb.js │ │ │ ├── wallet_grpc_pb.js │ │ │ ├── wallet_grpc_web_pb.js │ │ │ └── wallet_pb.js │ │ ├── open-rpc/ │ │ │ └── pactus-openrpc.json │ │ ├── python/ │ │ │ ├── blockchain_pb2.py │ │ │ ├── blockchain_pb2.pyi │ │ │ ├── blockchain_pb2_grpc.py │ │ │ ├── network_pb2.py │ │ │ ├── network_pb2.pyi │ │ │ ├── network_pb2_grpc.py │ │ │ ├── transaction_pb2.py │ │ │ ├── transaction_pb2.pyi │ │ │ ├── transaction_pb2_grpc.py │ │ │ ├── utils_pb2.py │ │ │ ├── utils_pb2.pyi │ │ │ ├── utils_pb2_grpc.py │ │ │ ├── wallet_pb2.py │ │ │ ├── wallet_pb2.pyi │ │ │ └── wallet_pb2_grpc.py │ │ └── rust/ │ │ ├── pactus.rs │ │ ├── pactus.serde.rs │ │ └── pactus.tonic.rs │ ├── middleware.go │ ├── middleware_test.go │ ├── network.go │ ├── network_test.go │ ├── proto/ │ │ ├── .clang-format │ │ ├── blockchain.proto │ │ ├── network.proto │ │ ├── transaction.proto │ │ ├── utils.proto │ │ └── wallet.proto │ ├── server.go │ ├── server_test.go │ ├── transaction.go │ ├── transaction_test.go │ ├── utils.go │ ├── utils_test.go │ ├── wallet.go │ └── wallet_test.go ├── html/ │ ├── README.md │ ├── blockchain.go │ ├── blockchain_test.go │ ├── config.go │ ├── html_test.go │ ├── middleware.go │ ├── middleware_test.go │ ├── network.go │ ├── network_test.go │ ├── server.go │ ├── transaction.go │ └── transaction_test.go ├── http/ │ ├── config.go │ ├── config_test.go │ ├── server.go │ ├── server_test.go │ └── swagger-ui/ │ ├── LICENSE │ ├── README.md │ ├── index.css │ ├── index.html │ ├── oauth2-redirect.html │ ├── pactus.swagger.json │ ├── swagger-initializer.js │ ├── swagger-ui-bundle.js │ ├── swagger-ui-es-bundle-core.js │ ├── swagger-ui-es-bundle.js │ ├── swagger-ui-standalone-preset.js │ ├── swagger-ui.css │ └── swagger-ui.js ├── jsonrpc/ │ ├── config.go │ └── server.go └── zmq/ ├── config.go ├── config_test.go ├── mock.go ├── publisher.go ├── publisher_block_info.go ├── publisher_block_info_test.go ├── publisher_raw_block.go ├── publisher_raw_block_test.go ├── publisher_raw_tx.go ├── publisher_raw_tx_test.go ├── publisher_test.go ├── publisher_tx_info.go ├── publisher_tx_info_test.go ├── server.go ├── server_test.go ├── topic.go └── topic_test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ .github build ================================================ FILE: .editorconfig ================================================ root = true [*] end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.go] indent_size = 4 indent_style = tab [Makefile] indent_style = tab ================================================ FILE: .entire/.gitignore ================================================ tmp/ settings.local.json metadata/ logs/ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: If you find an issue, please let us know. title: '[BUG]: ' labels: '["bug"]' type: 'Bug' assignees: '' --- ## Description > Provide a clear and concise description of the issue, including what you expected to happen. ### How To Reproduce > Detail the steps taken to reproduce this error, and > whether this issue can be reproduced consistently or if it is intermittent. 1. Step 1 2. Step 2 3. Step 3 ### What Happened > What actually happened including any error log or so ### Expected Behavior > What were you expecting ### Extra > Any extra information you think is relevant to issue ### Environment - **Operation System:** - **Pactus Version:** - **Go Version:** ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Any new functionality for Pactus. title: '[FEATURE]: ' labels: '["enhancement"]' type: "Feature" assignees: '' --- ## Describe the problem you'd like to have solved > A clear and concise description of what the problem is. ### Describe the ideal solution > A clear and concise description of what you want to happen. ### Alternatives and current work-around > A clear and concise description of any alternatives you've considered or any work-around that are currently in place. ### Additional context > Add any other context or screenshots about the feature request here. ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ ## Description > A clear description of what the pull request does. ## Related Issue Fixes # (issue) ================================================ FILE: .github/actions/windows-signing/action.yml ================================================ name: "Signing Windows Artifacts" description: "Signing Windows Artifacts" inputs: signpath-api-token: description: "SignPath API Token" required: true signpath-signing-policy-slug: description: "SignPath Signing Policy Slug" required: true artifact-name: description: "The name of artifact (.zip) file" required: true runs: using: "composite" steps: - name: upload-unsigned-artifact id: upload-unsigned-artifact uses: actions/upload-artifact@v6 with: name: ${{ inputs.artifact-name }} # Based on current SignPath configuration, we can only sign one file per request. path: ./build/unsigned/${{ inputs.artifact-name }}.exe - name: sign-artifact id: sign-artifact uses: signpath/github-action-submit-signing-request@v2 with: api-token: "${{ inputs.signpath-api-token }}" organization-id: "208fe1b4-fd9d-41c8-be2e-8ebd037cd0db" project-slug: "pactus" signing-policy-slug: "${{ inputs.signpath-signing-policy-slug }}" github-artifact-id: "${{ steps.upload-unsigned-artifact.outputs.artifact-id }}" wait-for-completion: true wait-for-completion-timeout-in-seconds: 3600 output-artifact-directory: ./build/signed/ ================================================ FILE: .github/codecov.yml ================================================ comment: layout: header, changes, diff, sunburst coverage: status: patch: default: threshold: "10%" only_pulls: true project: default: target: auto threshold: "10%" ignore: - "*/mock.go" - "www/grpc/gen" ================================================ FILE: .github/packager/js/grpc/README.md ================================================ # pactus-grpc JavaScript client for interacting with the [Pactus](https://pactus.org) blockchain via gRPC. ## Installation ```bash npm install pactus-grpc ``` ## Usage ```javascript import grpc from '@grpc/grpc-js'; import blockchain_pb from "pactus-grpc/blockchain_pb.js"; import blockchain_grpc_pb from "pactus-grpc/blockchain_grpc_pb.js"; const client = new blockchain_grpc_pb.BlockchainClient( "127.0.0.1:50051", grpc.credentials.createInsecure() ); const request = new blockchain_pb.GetBlockchainInfoRequest(); client.getBlockchainInfo(request, (err, response) => { if (err) { console.log(err); } else { console.log(response.toObject()); } }); ``` ================================================ FILE: .github/packager/js/grpc/package.json ================================================ { "name": "pactus-grpc", "version": "{{ VERSION }}", "description": "JavaScript client for interacting with the Pactus blockchain via gRPC", "author": "Pactus Development Team", "license": "MIT", "homepage": "https://pactus.org", "repository": { "type": "git", "url": "git+https://github.com/pactus-project/pactus.git" }, "bugs": { "url": "https://github.com/pactus-project/pactus/issues" }, "keywords": [ "pactus", "blockchain", "grpc" ], "dependencies": { "@grpc/grpc-js": "^1.14.1", "grpc-web": "^2.0.2", "google-protobuf": "^4.0.1" } } ================================================ FILE: .github/packager/js/jsonrpc/README.md ================================================ # pactus-jsonrpc JavaScript client for interacting with the [Pactus](https://pactus.org) blockchain via JSON-RPC. ## Installation ```bash npm install pactus-jsonrpc ``` ## Usage ```javascript import PactusOpenRPC from "pactus-jsonrpc"; const jsonrpcClient = new PactusOpenRPC({ transport: { type: "http", host: "127.0.0.1", port: 8545 }, }); const blockchainInfo = await jsonrpcClient.pactusBlockchainGetBlockchainInfo(); console.log(JSON.stringify(blockchainInfo, null, 2)); ``` ================================================ FILE: .github/packager/js/jsonrpc/package.json ================================================ { "name": "pactus-jsonrpc", "version": "{{ VERSION }}", "description": "JavaScript client for interacting with the Pactus blockchain via JSON-RPC", "author": "Pactus Development Team", "license": "MIT", "homepage": "https://pactus.org", "main": "./index.js", "repository": { "type": "git", "url": "git+https://github.com/pactus-project/pactus.git" }, "bugs": { "url": "https://github.com/pactus-project/pactus/issues" }, "keywords": [ "pactus", "blockchain", "json-rpc" ], "dependencies": { "@open-rpc/client-js": "1.8.1", "@open-rpc/meta-schema": "1.14.9", "@open-rpc/schema-utils-js": "2.1.2", "lodash": "^4.17.15" } } ================================================ FILE: .github/packager/packager.sh ================================================ #!/bin/bash # The 'set -e' command causes the script to immediately exit # if any command returns a non-zero exit status (i.e., an error). set -e replace_in_place() { if [[ "$OSTYPE" == "darwin"* ]]; then sed -i '' "$1" "$2" else sed -i "$1" "$2" fi } ROOT_DIR="$(pwd)" PACKAGE_DIR="${ROOT_DIR}/packages" PROTO_GEN_DIR="${ROOT_DIR}/www/grpc/gen" if [[ -z "$VERSION" ]]; then echo "❌ Error: Version tag not found." exit 1 fi # Remove 'v' prefix from version if present VERSION=${VERSION#v} echo "Packing Version:" ${VERSION} rm -rf ${PACKAGE_DIR} mkdir -p ${PACKAGE_DIR} mkdir -p ${PACKAGE_DIR}/js/{pactus-grpc,pactus-jsonrpc} mkdir -p ${PACKAGE_DIR}/python/{pactus-grpc,pactus-jsonrpc} mkdir -p ${PACKAGE_DIR}/rust/{pactus-grpc,pactus-jsonrpc} echo "== Building pactus-grpc package for JavaScript" cp -R ${ROOT_DIR}/.github/packager/js/grpc/* ${PACKAGE_DIR}/js/pactus-grpc cp -R ${PROTO_GEN_DIR}/js/* ${PACKAGE_DIR}/js/pactus-grpc cp ${ROOT_DIR}/LICENSE ${PACKAGE_DIR}/js/pactus-grpc replace_in_place "s/{{ VERSION }}/$VERSION/g" "${PACKAGE_DIR}/js/pactus-grpc/package.json" echo "== Building pactus-jsonrpc package for JavaScript" GENERATOR_DIR="${PACKAGE_DIR}/generator" git clone https://github.com/pactus-project/generator.git "$GENERATOR_DIR" && cd "$GENERATOR_DIR" npm install && npm run build cd "$ROOT_DIR" && $GENERATOR_DIR/build/cli.js generate \ -t client \ -l typescript \ -n pactus-jsonrpc \ -d "${ROOT_DIR}/www/grpc/gen/open-rpc/pactus-openrpc.json" \ -o "$GENERATOR_DIR/js" cd "$GENERATOR_DIR/js/client/typescript" npm install && npx tsc cp $GENERATOR_DIR/js/client/typescript/build/index.d.ts ${PACKAGE_DIR}/js/pactus-jsonrpc cp $GENERATOR_DIR/js/client/typescript/build/index.js ${PACKAGE_DIR}/js/pactus-jsonrpc cp $GENERATOR_DIR/js/client/typescript/build/index.js.map ${PACKAGE_DIR}/js/pactus-jsonrpc cp -R ${ROOT_DIR}/.github/packager/js/jsonrpc/* ${PACKAGE_DIR}/js/pactus-jsonrpc cp ${ROOT_DIR}/LICENSE ${PACKAGE_DIR}/js/pactus-jsonrpc replace_in_place "s/{{ VERSION }}/$VERSION/g" "${PACKAGE_DIR}/js/pactus-jsonrpc/package.json" echo "== Building pactus-grpc package for Python" cp -R ${ROOT_DIR}/.github/packager/python/grpc/* ${PACKAGE_DIR}/python/pactus-grpc cp ${PROTO_GEN_DIR}/python/* ${PACKAGE_DIR}/python/pactus-grpc/pactus_grpc cp ${ROOT_DIR}/LICENSE ${PACKAGE_DIR}/python/pactus-grpc replace_in_place "s/{{ VERSION }}/$VERSION/g" ${PACKAGE_DIR}/python/pactus-grpc/setup.py echo "== Building pactus-jsonrpc package for Python" pip install openrpcclientgenerator ORPC_DIR="${PACKAGE_DIR}/orpc" mkdir -p ${ORPC_DIR} cp "${ROOT_DIR}/www/grpc/gen/open-rpc/pactus-openrpc.json" ${ORPC_DIR}/openrpc.json cd ${ORPC_DIR} orpc python example.com ./out cp -R ${ROOT_DIR}/.github/packager/python/jsonrpc/* ${PACKAGE_DIR}/python/pactus-jsonrpc cp ${ORPC_DIR}/out/python/pactus-open-rpc-http-client/pactus_open_rpc_http_client/client.py ${PACKAGE_DIR}/python/pactus-jsonrpc/pactus_jsonrpc/client.py cp ${ORPC_DIR}/out/python/pactus-open-rpc-http-client/pactus_open_rpc_http_client/models.py ${PACKAGE_DIR}/python/pactus-jsonrpc/pactus_jsonrpc/models.py cp ${ROOT_DIR}/LICENSE ${PACKAGE_DIR}/python/pactus-jsonrpc replace_in_place "s/{{ VERSION }}/$VERSION/g" ${PACKAGE_DIR}/python/pactus-jsonrpc/setup.py echo "== Building pactus-grpc package for Rust" cp -R ${ROOT_DIR}/.github/packager/rust/grpc/* ${PACKAGE_DIR}/rust/pactus-grpc cp -R ${PROTO_GEN_DIR}/rust/* ${PACKAGE_DIR}/rust/pactus-grpc/src cp ${ROOT_DIR}/LICENSE ${PACKAGE_DIR}/rust/pactus-grpc replace_in_place "s/{{ VERSION }}/$VERSION/g" ${PACKAGE_DIR}/rust/pactus-grpc/Cargo.toml echo "== Building pactus-jsonrpc package for Rust" cd "$ROOT_DIR" && $GENERATOR_DIR/build/cli.js generate \ -t client \ -l rust \ -n pactus-jsonrpc \ -d "${ROOT_DIR}/www/grpc/gen/open-rpc/pactus-openrpc.json" \ -o "$GENERATOR_DIR/rust" cp -R ${ROOT_DIR}/.github/packager/rust/jsonrpc/* ${PACKAGE_DIR}/rust/pactus-jsonrpc cp $GENERATOR_DIR/rust/client/rust/src/index.rs ${PACKAGE_DIR}/rust/pactus-jsonrpc/src/pactus.rs cp ${ROOT_DIR}/LICENSE ${PACKAGE_DIR}/rust/pactus-jsonrpc replace_in_place "s/{{ VERSION }}/$VERSION/g" "${PACKAGE_DIR}/rust/pactus-jsonrpc/Cargo.toml" ================================================ FILE: .github/packager/python/grpc/README.md ================================================ # pactus-grpc Python client for interacting with the [Pactus](https://pactus.org) blockchain via gRPC. ## Installation ```bash pip install pactus-grpc ``` ## Usage ```python import asyncio import grpc from pactus_grpc import blockchain_pb2_grpc, blockchain_pb2, network_pb2_grpc, network_pb2 async def main(): channel = grpc.aio.insecure_channel("127.0.0.1:50051") blockchain_stub = blockchain_pb2_grpc.BlockchainStub(channel) blockchain_request = blockchain_pb2.GetBlockchainInfoRequest() blockchain_response = await blockchain_stub.GetBlockchainInfo(blockchain_request) print(blockchain_response) await channel.close() if __name__ == "__main__": asyncio.run(main()) ``` ================================================ FILE: .github/packager/python/grpc/pactus_grpc/__init__.py ================================================ import os import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) ================================================ FILE: .github/packager/python/grpc/pactus_grpc/__init__.pyi ================================================ import os import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) ================================================ FILE: .github/packager/python/grpc/pyproject.toml ================================================ [build-system] requires = ["setuptools >= 42.0.0"] build-backend = "setuptools.build_meta" ================================================ FILE: .github/packager/python/grpc/setup.py ================================================ from pathlib import Path from setuptools import find_packages, setup setup( name="pactus-grpc", version="{{ VERSION }}", author="Pactus Development Team", author_email="info@pactus.org", url="https://pactus.org", description="Python client for interacting with the Pactus blockchain via gRPC", long_description=Path("README.md").read_text(encoding="utf-8"), long_description_content_type="text/markdown", license="MIT", packages=find_packages(), keywords=["pactus", "blockchain", "grpc"], install_requires=[ "grpcio", "protobuf", ], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Build Tools", "Operating System :: OS Independent", ], python_requires=">=3.6", ) ================================================ FILE: .github/packager/python/jsonrpc/README.md ================================================ # pactus-jsonrpc Python client for interacting with the [Pactus](https://pactus.org) blockchain via JSON-RPC. ## Installation ```bash pip install pactus-jsonrpc ``` ## Usage ```python import asyncio from pactus_jsonrpc.client import PactusOpenRPCClient async def main(): client = PactusOpenRPCClient( headers={}, client_url="http://127.0.0.1:8545" ) blockchain_info = await client.pactus.blockchain.get_blockchain_info() print(blockchain_info) if __name__ == "__main__": asyncio.run(main()) ``` ================================================ FILE: .github/packager/python/jsonrpc/pactus_jsonrpc/__init__.py ================================================ ================================================ FILE: .github/packager/python/jsonrpc/pyproject.toml ================================================ [build-system] requires = ["setuptools >= 42.0.0"] build-backend = "setuptools.build_meta" ================================================ FILE: .github/packager/python/jsonrpc/setup.py ================================================ from pathlib import Path from setuptools import find_packages, setup setup( name="pactus-jsonrpc", version="{{ VERSION }}", author="Pactus Development Team", author_email="info@pactus.org", url="https://pactus.org", description="Python client for interacting with the Pactus blockchain via JSON-RPC", long_description=Path("README.md").read_text(encoding="utf-8"), long_description_content_type="text/markdown", packages=find_packages(), license="MIT", install_requires=[ "jsonrpc2-pyclient>=5.2.0", "py-undefined>=0.1.5", "pydantic>=2.5.3" ], keywords=["pactus", "blockchain", "json-rpc"], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Build Tools", "Operating System :: OS Independent", ], python_requires=">=3.6", ) ================================================ FILE: .github/packager/rust/grpc/Cargo.toml ================================================ [package] name = "pactus-grpc" version = "{{ VERSION }}" edition = "2021" description = "Rust client for interacting with the Pactus blockchain via gRPC" authors = [ "Pactus Development Team " ] license = "MIT" homepage = "https://pactus.org" repository = "https://github.com/pactus-project/pactus" keywords = [ "pactus", "blockchain", "grpc" ] [dependencies] tonic = { version = "0.14", default-features = false, features = ["transport", "codegen"] } prost = { version = "0.14", default-features = false, features = ["derive", "std"] } tonic-prost = { version = "0.14", default-features = false, features = [] } serde = { version = "1.0", default-features = false, features = [] } async-trait = { version = "0.1", default-features = false, features = [] } pbjson = { version = "0.8", default-features = false, features = [] } ================================================ FILE: .github/packager/rust/grpc/README.md ================================================ # pactus-grpc Rust client for interacting with the [Pactus](https://pactus.org) blockchain via gRPC. ## Installation ```bash cargo add pactus-grpc ``` ## Usage ```rust use pactus_grpc::{blockchain_client::BlockchainClient, GetBlockchainInfoRequest}; use tonic::transport::Channel; #[tokio::main] async fn main() -> Result<(), Box> { let channel = Channel::from_static("http://127.0.0.1:50051") .connect() .await?; let mut client = BlockchainClient::new(channel); let request = tonic::Request::new(GetBlockchainInfoRequest {}); let response = client.get_blockchain_info(request).await?; let info = response.into_inner(); println!("get_blockchain_info Response: {:?}", info); Ok(()) } ``` ================================================ FILE: .github/packager/rust/grpc/src/lib.rs ================================================ //! # Pactus gRPC Client //! //! A Rust client library for interacting with the Pactus blockchain via gRPC. //! //! ## Example //! //! ```rust //! use pactus_grpc::{blockchain_client::BlockchainClient, GetBlockchainInfoRequest}; //! use tonic::transport::Channel; //! //! #[tokio::main] //! async fn main() -> Result<(), Box> { //! let channel = Channel::from_static("http://127.0.0.1:50051") //! .connect() //! .await?; //! //! let mut client = BlockchainClient::new(channel); //! //! let request = tonic::Request::new(GetBlockchainInfoRequest {}); //! let response = client.get_blockchain_info(request).await?; //! let info = response.into_inner(); //! //! println!("get_blockchain_info Response: {:?}", info); //! //! Ok(()) //! } //! ``` pub mod pactus; // Re-export the main message types pub use pactus::*; ================================================ FILE: .github/packager/rust/jsonrpc/Cargo.toml ================================================ [package] name = "pactus-jsonrpc" version = "{{ VERSION }}" edition = "2021" description = "Rust client for interacting with the Pactus blockchain via JSON-RPC" authors = [ "Pactus Development Team " ] license = "MIT" homepage = "https://pactus.org" repository = "https://github.com/pactus-project/pactus" keywords = [ "pactus", "blockchain", "json-rpc" ] [dependencies] jsonrpsee = { version = "0.26", default-features = false, features = ["http-client"] } serde = { version = "1.0", default-features = false, features = ["derive", "std"] } serde_json = { version = "1.0", default-features = false, features = ["std"] } derive_builder = { version = "0.20", default-features = false, features = ["std"] } ================================================ FILE: .github/packager/rust/jsonrpc/README.md ================================================ # pactus-jsonrpc Rust client for interacting with the [Pactus](https://pactus.org) blockchain via JSON-RPC. ## Installation ```bash cargo add pactus-jsonrpc ``` ## Usage ```rust use jsonrpsee::http_client::HttpClient; use pactus_jsonrpc::pactus::PactusOpenRPC; #[tokio::main] async fn main() { let client = HttpClient::builder().build("http://127.0.0.1:8545").unwrap(); let rpc: PactusOpenRPC = PactusOpenRPC::new(client); let info = rpc.pactus_blockchain_get_blockchain_info().await.unwrap(); println!("get_blockchain_info Response: {:?}", info); } ``` ================================================ FILE: .github/packager/rust/jsonrpc/src/lib.rs ================================================ //! # Pactus JSON-RPC Client //! //! A Rust client library for interacting with the Pactus blockchain via JSON-RPC. //! //! ## Example //! //! ```rust //! use jsonrpsee::http_client::HttpClient; //! use pactus_jsonrpc::pactus::PactusOpenRPC; //! //! #[tokio::main] //! async fn main() { //! let client = HttpClient::builder().build("http://127.0.0.1:8545").unwrap(); //! let rpc: PactusOpenRPC = PactusOpenRPC::new(client); //! //! let info = rpc.pactus_blockchain_get_blockchain_info().await.unwrap(); //! println!("get_blockchain_info Response: {:?}", info); //! } //! ``` pub mod pactus; ================================================ FILE: .github/releasers/linux/pactus-gui.desktop ================================================ [Desktop Entry] Name=pactus-gui Comment=Pactus blockchain node Exec=pactus-gui Icon=pactus Type=Application Categories=Network; ================================================ FILE: .github/releasers/macos/Info.plist ================================================ CFBundlePackageType APPL CFBundleIdentifier com.github.pactus-project.pactus.pactus-gui CFBundleExecutable pactus-gui CFBundleName pactus-gui CFBundleShortVersionString %SHORTVERSION% CFBundleVersion %VERSION% CFBundleIconFile pactus.icns CFBundleSignature ???? NSHumanReadableCopyright MIT License. LSMinimumSystemVersion 10.15 ================================================ FILE: .github/releasers/macos/gtk3-launcher.sh ================================================ #!/bin/sh if test "x$GTK_DEBUG_LAUNCHER" != x; then set -x fi if test "x$GTK_DEBUG_GDB" != x; then EXEC="gdb --args" else EXEC=exec fi name=`basename "$0"` tmp="$0" tmp=`dirname "$tmp"` tmp=`dirname "$tmp"` bundle=`dirname "$tmp"` bundle_contents="$bundle"/Contents bundle_res="$bundle_contents"/Resources bundle_lib="$bundle_res"/lib bundle_bin="$bundle_res"/bin bundle_data="$bundle_res"/share bundle_etc="$bundle_res"/etc export DYLD_FALLBACK_LIBRARY_PATH="$bundle_lib" export XDG_CONFIG_DIRS="$bundle_etc"/xdg export XDG_DATA_DIRS="$bundle_data" export GTK_DATA_PREFIX="$bundle_res" export GTK_EXE_PREFIX="$bundle_res" export GTK_PATH="$bundle_res" # macOS-specific settings if [ "$(uname)" = "Darwin" ]; then # Changing the PANGOCAIRO_BACKEND is necessary on MacOS to render emoji export PANGOCAIRO_BACKEND="fontconfig" fi export GDK_PIXBUF_MODULE_FILE="$bundle_lib/gdk-pixbuf-2.0/2.10.0/loaders.cache" if [ `uname -r | cut -d . -f 1` -ge 10 ]; then export GTK_IM_MODULE_FILE="$bundle_lib/gtk-3.0/3.0.0/immodules.cache" fi APP=$name # Strip out the argument added by the OS. if /bin/expr "x$1" : '^x-psn_' > /dev/null; then shift 1 fi $EXEC "$bundle_contents/MacOS/$name-bin" "$@" $EXTRA_ARGS ================================================ FILE: .github/releasers/macos/gui.bundle ================================================ ${env:LIB_HOME} ${env:GUI_BUNDLE} ${env:ROOT_DIR} ${project}/gtk3-launcher.sh gtk+-3.0 ${project}/Info.plist ${prefix:bundle}/pactus-gui ${prefix}/lib/${gtkdir}/${pkg:${gtk}:gtk_binary_version}/immodules/*.so ${prefix}/lib/gdk-pixbuf-2.0/${pkg:gdk-pixbuf-2.0:gdk_pixbuf_binary_version}/loaders/*.so ${prefix}/lib/gio/modules/libgiognutls.so ${prefix}/share/themes ${prefix}/share/icons ${prefix:bundle}/pactus.icns ================================================ FILE: .github/releasers/macos/run-install-name-tool-change.sh ================================================ #!/bin/sh if [ $# -lt 3 ]; then echo "Usage: $0 library old_prefix new_prefix action" exit 1 fi LIBRARY=$1 WRONG_PREFIX=$2 RIGHT_PREFIX="@executable_path/../$3" ACTION=$4 chmod u+w $LIBRARY if [ "x$ACTION" = "xchange" ]; then libs="`otool -L $LIBRARY 2>/dev/null | fgrep compatibility | cut -d\( -f1 | grep $WRONG_PREFIX | sort | uniq`" for lib in $libs; do if ! echo $lib | grep --silent "@executable_path" ; then if echo $lib | grep --silent "${LIB_HOME}/Cellar/"; then fixed=`echo $lib | sed -e "s|${LIB_HOME}/Cellar/\([^/]*\)/[^/]*/|@executable_path/../Resources/opt/\1/|"` else fixed=`echo $lib | sed -e s,\${WRONG_PREFIX},\${RIGHT_PREFIX},` fi echo $lib $fixed $LIBRARY install_name_tool -change $lib $fixed $LIBRARY fi done; elif [ "x$ACTION" = "xid" ]; then # echo "$LIBRARY $WRONG_PREFIX to $RIGHT_PREFIX" lib=$(otool -D "$LIBRARY" 2>/dev/null | grep ^"$WRONG_PREFIX" | sed s,"$WRONG_PREFIX",,) if [ -n "$lib" ]; then # echo "Rewrite $lib" install_name_tool -id "${RIGHT_PREFIX}/${lib}" $LIBRARY; # else # path=$(otool -D "$LIBRARY" 2>/dev/null | sed -n 2p) # echo "Empty Result $path" fi fi ================================================ FILE: .github/releasers/pactus_downloader.sh ================================================ #!/bin/sh # Function to check if a command is available command_exists() { command -v "$1" >/dev/null 2>&1 } # Download function download_file() { file_name=$1 url=$2 echo "== Downloading ${file_name}..." if ! curl --fail --proto '=https' --tlsv1.2 -# -L -o "${file_name}" "${url}" ; then echo "Failed to download ${file_name}. Check the URL or your internet connection." exit 1 fi } # Check if sha256sum is installed if ! command_exists sha256sum; then echo "sha256sum is not installed. Please install sha256sum and try again." exit 1 fi # Detect the operating system and CPU type OS=$(uname -s) ARCH=$(uname -m) EXT=".tar.gz" case $OS in ###################### Android) OS="android" case $ARCH in aarch64 | arm64) ARCH="arm64" ;; *) echo "Unrecognized CPU type: $ARCH" exit 1 ;; esac ;; ###################### Linux) OS="linux" case $ARCH in x86_64) ARCH="amd64" ;; aarch64 | arm64) ARCH="arm64" ;; *) echo "Unrecognized CPU type: $ARCH" exit 1 ;; esac ;; ###################### FreeBSD) OS="freebsd" case $ARCH in amd64) ARCH="amd64" ;; *) echo "Unrecognized CPU type: $ARCH" exit 1 ;; esac ;; ###################### Darwin) OS="darwin" case $ARCH in x86_64) ARCH="amd64" ;; arm64) ARCH="arm64" ;; *) echo "Unrecognized CPU type: $ARCH" exit 1 ;; esac ;; ###################### MINGW* | MSYS* | CYGWIN*) if ! command_exists unzip; then echo "unzip is not installed. Please install unzip and try again." exit 1 fi OS="windows" EXT=".zip" case $ARCH in i686 | i386) ARCH="386" ;; x86_64) ARCH="amd64" ;; aarch64 | arm64) ARCH="arm64" ;; *) echo "Unrecognized CPU type: $ARCH" exit 1 ;; esac ;; *) echo "Unrecognized OS type: $OS" exit 1 ;; esac # Version number VERSION="__VERSION__" # Set the server URL where the binary and checksum files are hosted SERVER_URL="https://github.com/pactus-project/pactus/releases/download/v${VERSION}" # Set the filename of the binary and checksum CHECKSUM_FILE="SHA256SUMS" # Set the filename of the binary and checksum FILE_NAME="pactus-cli_${VERSION}_${OS}_${ARCH}${EXT}" # Destination directory that is the current directory DEST_DIR="$(pwd)" EXTRACTED_DIR="${DEST_DIR}/pactus-cli_${VERSION}" # Create a temporary directory for downloads DOWN_DIR="$(mktemp -d)" # Check if extractopn folder exists and print an error if it does if [ -e "${EXTRACTED_DIR}" ]; then echo "Destination directory '${EXTRACTED_DIR}' already exists." exit 1 fi cd ${DOWN_DIR} # Download the files using the download_file function download_file "${FILE_NAME}" "${SERVER_URL}/${FILE_NAME}" download_file "${CHECKSUM_FILE}" "${SERVER_URL}/${CHECKSUM_FILE}" # Verify the checksum echo "== Verify the checksum..." sha256sum --ignore-missing -c "${CHECKSUM_FILE}" if [ $? -ne 0 ]; then echo "Checksum verification failed for ${FILE_NAME}!" exit 1 fi # Extracting echo "== Extracting ${FILE_NAME}..." if [ "${OS}" = "windows" ]; then unzip -n "${FILE_NAME}" -d "${DEST_DIR}" || { echo "Error: Extraction failed." exit 1 } else tar -xzf "${FILE_NAME}" -C "${DEST_DIR}" || { echo "Error: Extraction failed." exit 1 } fi echo "Extracted at ${EXTRACTED_DIR}" echo "" echo "Installation completed." ================================================ FILE: .github/releasers/releaser_cli.sh ================================================ #!/bin/bash # The 'set -e' command causes the script to immediately exit # if any command returns a non-zero exit status (i.e., an error). set -e ROOT_DIR="$(pwd)" VERSION="$(echo `git -C ${ROOT_DIR} describe --abbrev=0 --tags` | sed 's/^.//')" # "v1.2.3" -> "1.2.3" PACKAGE_NAME="pactus-cli_${VERSION}" # https://go.dev/doc/install/source#environment for OS_ARCH in \ "linux amd64" "linux arm64" \ "android arm64" \ "freebsd amd64" "freebsd arm64" \ "darwin amd64" "darwin arm64" \ "windows 386" "windows amd64" "windows arm64"; do PAIR=($OS_ARCH); OS=${PAIR[0]}; ARCH=${PAIR[1]}; cd ${ROOT_DIR} PACKAGE_NAME_OS=${PACKAGE_NAME}_${OS}_${ARCH} BUILD_DIR=${ROOT_DIR}/build/${PACKAGE_NAME_OS} if [ $OS = "windows" ]; then EXE=".exe" fi echo "Building Pactus for ${OS}-${ARCH}..." LD_FLAGS="-s -w" if [[ ${OS} == "android" ]]; then LD_FLAGS="${LD_FLAGS} -checklinkname=0" fi CGO_ENABLED=0 GOOS=${OS} GOARCH=${ARCH} go build -ldflags "${LD_FLAGS}" -trimpath -o ${BUILD_DIR}/${PACKAGE_NAME}/pactus-daemon${EXE} ./cmd/daemon CGO_ENABLED=0 GOOS=${OS} GOARCH=${ARCH} go build -ldflags "${LD_FLAGS}" -trimpath -o ${BUILD_DIR}/${PACKAGE_NAME}/pactus-wallet${EXE} ./cmd/wallet CGO_ENABLED=0 GOOS=${OS} GOARCH=${ARCH} go build -ldflags "${LD_FLAGS}" -trimpath -o ${BUILD_DIR}/${PACKAGE_NAME}/pactus-shell${EXE} ./cmd/shell cd ${BUILD_DIR} if [ $OS = "windows" ]; then zip -r ${PACKAGE_NAME_OS}.zip ${PACKAGE_NAME} mv ${PACKAGE_NAME_OS}.zip ${ROOT_DIR} else tar -czvf ${PACKAGE_NAME_OS}.tar.gz -p ${PACKAGE_NAME} mv ${PACKAGE_NAME_OS}.tar.gz ${ROOT_DIR} fi done ================================================ FILE: .github/releasers/releaser_gui_linux.sh ================================================ #!/bin/bash set -e ROOT_DIR="$(pwd)" VERSION="$(echo `git -C ${ROOT_DIR} describe --abbrev=0 --tags` | sed 's/^.//')" # "v1.2.3" -> "1.2.3" BUILD_DIR="${ROOT_DIR}/build" PACKAGE_NAME="pactus-gui_${VERSION}" PACKAGE_DIR="${ROOT_DIR}/${PACKAGE_NAME}" # Check the architecture ARC="$(uname -m)" if [ "${ARC}" = "x86_64" ]; then FILE_NAME="${PACKAGE_NAME}_linux_amd64" elif [ "${ARC}" = "aarch64" ]; then FILE_NAME="${PACKAGE_NAME}_linux_arm64" else echo "Unsupported architecture: ${ARC}" exit 1 fi mkdir ${PACKAGE_DIR} echo "Building the binaries for Linux ${ARC} architecture" cd ${ROOT_DIR} CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/pactus-daemon ./cmd/daemon CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/pactus-wallet ./cmd/wallet CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/pactus-shell ./cmd/shell CGO_ENABLED=1 go build -ldflags "-s -w" -trimpath -tags gtk -o ${BUILD_DIR}/pactus-gui ./cmd/gtk # Moving binaries to package directory echo "Moving binaries" mv ${BUILD_DIR}/pactus-daemon ${PACKAGE_DIR}/pactus-daemon mv ${BUILD_DIR}/pactus-wallet ${PACKAGE_DIR}/pactus-wallet mv ${BUILD_DIR}/pactus-shell ${PACKAGE_DIR}/pactus-shell mv ${BUILD_DIR}/pactus-gui ${PACKAGE_DIR}/pactus-gui echo "Creating archive" tar -czvf ${ROOT_DIR}/${FILE_NAME}.tar.gz -p ${PACKAGE_NAME} # building AppImage # https://github.com/linuxdeploy/linuxdeploy-plugin-gtk cp ${ROOT_DIR}/.github/releasers/linux/* ${PACKAGE_DIR} cd ${PACKAGE_DIR} wget -c "https://raw.githubusercontent.com/linuxdeploy/linuxdeploy-plugin-gtk/master/linuxdeploy-plugin-gtk.sh" wget -c "https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-${ARC}.AppImage" chmod +x linuxdeploy-${ARC}.AppImage linuxdeploy-plugin-gtk.sh DEPLOY_GTK_VERSION=3 ./linuxdeploy-${ARC}.AppImage \ --executable ./pactus-gui \ --appdir AppDir \ --plugin gtk \ --output appimage \ --icon-file pactus.png \ --desktop-file ./pactus-gui.desktop mv ./pactus-gui-${ARC}.AppImage ${ROOT_DIR}/${FILE_NAME}.AppImage ================================================ FILE: .github/releasers/releaser_gui_macos.sh ================================================ #!/bin/bash set -e ROOT_DIR="$(pwd)" VERSION="$(echo `git -C ${ROOT_DIR} describe --abbrev=0 --tags` | sed 's/^.//')" # "v1.2.3" -> "1.2.3" BUILD_DIR="${ROOT_DIR}/build" PACKAGE_NAME="pactus-gui_${VERSION}" PACKAGE_DIR="${ROOT_DIR}/${PACKAGE_NAME}" # Ensure GTK prefix is provided for bundling assets if [ -z "${LIB_HOME}" ]; then echo "LIB_HOME is not set. Set it to your GTK prefix (e.g. /opt/homebrew or /usr/local)." exit 1 fi # Check the architecture ARC="$(uname -m)" if [ "${ARC}" = "x86_64" ]; then FILE_NAME="${PACKAGE_NAME}_darwin_amd64" elif [ "${ARC}" = "arm64" ]; then FILE_NAME="${PACKAGE_NAME}_darwin_arm64" else echo "Unsupported architecture: ${ARC}" exit 1 fi mkdir -p ${PACKAGE_DIR} echo "Building the binaries for macOS ${ARC} architecture" cd ${ROOT_DIR} CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/pactus-daemon ./cmd/daemon CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/pactus-wallet ./cmd/wallet CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/pactus-shell ./cmd/shell CGO_ENABLED=1 go build -ldflags "-s -w -extldflags -headerpad_max_install_names" -trimpath -tags gtk -o ${BUILD_DIR}/pactus-gui ./cmd/gtk echo "Installing gtk-mac-bundler" git clone https://gitlab.gnome.org/GNOME/gtk-mac-bundler.git cd gtk-mac-bundler # A workaround to make bundle without building GTK+ using jhbuild. rm bundler/run-install-name-tool-change.sh cp ${ROOT_DIR}/.github/releasers/macos/run-install-name-tool-change.sh bundler/run-install-name-tool-change.sh chmod +x bundler/run-install-name-tool-change.sh # make sure launcher is executable chmod +x ${ROOT_DIR}/.github/releasers/macos/gtk3-launcher.sh make install export PATH=${PATH}:${HOME}/.bin:${HOME}/local/bin BUNDLER=$(which gtk-mac-bundler) echo "gtk-mac-bundler found at ${BUNDLER}" cd - echo "Bundling the GUI package" GUI_BUNDLE=${ROOT_DIR}/gui-bundle mkdir -p ${GUI_BUNDLE} cp ${BUILD_DIR}/pactus-gui ${GUI_BUNDLE} cp ${ROOT_DIR}/.github/releasers/macos/* ${GUI_BUNDLE} # https://stackoverflow.com/questions/21242932/sed-i-may-not-be-used-with-stdin-on-mac-os-x sed -i '' "s/%SHORTVERSION%/${VERSION}/" ${GUI_BUNDLE}/Info.plist sed -i '' "s/%VERSION%/Version ${VERSION}/" ${GUI_BUNDLE}/Info.plist export GUI_BUNDLE export ROOT_DIR ${BUNDLER} ${GUI_BUNDLE}/gui.bundle # Removing Cellar as workaround rm -rf ${ROOT_DIR}/pactus-gui.app/Contents/Resources/Cellar echo "Creating dmg" # https://github.com/create-dmg/create-dmg create-dmg --version create-dmg --skip-jenkins \ --volname "Pactus GUI" \ "${FILE_NAME}.dmg" \ "${ROOT_DIR}/pactus-gui.app" echo "Creating archive" cp ${BUILD_DIR}/pactus-daemon ${PACKAGE_DIR} cp ${BUILD_DIR}/pactus-wallet ${PACKAGE_DIR} cp ${BUILD_DIR}/pactus-shell ${PACKAGE_DIR} cp -R ${ROOT_DIR}/pactus-gui.app ${PACKAGE_DIR} tar -czvf ${ROOT_DIR}/${FILE_NAME}.tar.gz -p ${PACKAGE_NAME} ================================================ FILE: .github/releasers/releaser_gui_windows_build.sh ================================================ #!/bin/bash set -e ROOT_DIR="$(pwd)" BUILD_DIR="${ROOT_DIR}/build" # Copy Windows resources file for application icon cp ${ROOT_DIR}/.github/releasers/windows/rsrc_windows_amd64.syso ${ROOT_DIR}/cmd/gtk/rsrc_windows_amd64.syso # This fixes a bug in pkgconfig: invalid flag in pkg-config --libs: -Wl,-luuid sed -i -e 's/-Wl,-luuid/-luuid/g' /mingw64/lib/pkgconfig/gdk-3.0.pc CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/unsigned/pactus-daemon.exe ./cmd/daemon CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/unsigned/pactus-wallet.exe ./cmd/wallet CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ${BUILD_DIR}/unsigned/pactus-shell.exe ./cmd/shell CGO_ENABLED=1 go build -ldflags "-s -w -H windowsgui" -trimpath -tags gtk -o ${BUILD_DIR}/unsigned/pactus-gui.exe ./cmd/gtk ================================================ FILE: .github/releasers/releaser_gui_windows_installer.sh ================================================ #!/bin/bash set -e ROOT_DIR="$(pwd)" VERSION="$(echo `git -C ${ROOT_DIR} describe --abbrev=0 --tags` | sed 's/^.//')" BUILD_DIR="${ROOT_DIR}/build" PACKAGE_NAME="pactus-gui_${VERSION}" PACKAGE_DIR="${ROOT_DIR}/${PACKAGE_NAME}" FILE_NAME="${PACKAGE_NAME}_windows_amd64" echo "🚀 Starting Pactus GUI Windows packaging..." # Create package directory mkdir -p "${PACKAGE_DIR}/pactus-gui" # Bundle GTK application using Python bundler python3 "${ROOT_DIR}/.github/releasers/windows/gtk-win-bundler.py" \ "${BUILD_DIR}/signed/pactus-gui.exe" \ "${PACKAGE_DIR}/pactus-gui" # Move other binaries cp ${BUILD_DIR}/signed/pactus-daemon.exe ${PACKAGE_DIR}/pactus-daemon.exe cp ${BUILD_DIR}/signed/pactus-wallet.exe ${PACKAGE_DIR}/pactus-wallet.exe cp ${BUILD_DIR}/signed/pactus-shell.exe ${PACKAGE_DIR}/pactus-shell.exe cp ${BUILD_DIR}/signed/pactus-gui.exe ${PACKAGE_DIR}/pactus-gui/pactus-gui.exe # Create archive 7z a ${ROOT_DIR}/${FILE_NAME}.zip ${PACKAGE_DIR} # Create installer cat << EOF > ${ROOT_DIR}/inno.iss [Setup] AppId=Pactus AppName=Pactus AppVersion=${VERSION} AppPublisher=Pactus AppPublisherURL=https://pactus.org/ DefaultDirName={autopf}/Pactus DefaultGroupName=Pactus SetupIconFile=.github/releasers/windows/pactus.ico LicenseFile=LICENSE Uninstallable=yes [Files] Source:"${PACKAGE_NAME}/*"; DestDir:"{app}"; Flags: recursesubdirs [Icons] Name:"{group}\\Pactus"; Filename:"{app}\\pactus-gui\\pactus-gui.exe" Name:"{commondesktop}\\Pactus"; Filename:"{app}\\pactus-gui\\pactus-gui.exe" [Run] Filename:"{app}\\pactus-gui\\pactus-gui.exe"; Description:"Launch Pactus"; Flags: postinstall nowait EOF # Build installer INNO_PATH="/c/Program Files (x86)/Inno Setup 6" INNO_DIR=$(cygpath -w -s "${INNO_PATH}") "${INNO_DIR}/ISCC.exe" "${ROOT_DIR}/inno.iss" mv "Output/mysetup.exe" "${BUILD_DIR}/unsigned/${FILE_NAME}_installer.exe" echo "🎉 Build complete! Package: ${BUILD_DIR}/unsigned/${FILE_NAME}_installer.exe" ================================================ FILE: .github/releasers/windows/README.md ================================================ # Generating the Windows resource (.syso) 1) Install the tool (once): `go install github.com/akavel/rsrc@latest` 2) Generate the .syso in this folder: `rsrc -manifest ./pactus-gui.manifest -ico ./pactus.ico` ================================================ FILE: .github/releasers/windows/gtk-win-bundler.py ================================================ #!/usr/bin/env python3 """ GTK Bundle Helper for Windows Automatically detects and bundles all GTK dependencies for Windows distribution. """ import os import sys import shutil import subprocess import json from pathlib import Path from typing import List, Set, Dict, Optional class GTKBundler: def __init__(self, mingw_prefix: str, target_dir: str): self.mingw_prefix = Path(mingw_prefix) self.target_dir = Path(target_dir) def run_command(self, cmd: List[str]) -> str: """Run a command and return its output.""" try: result = subprocess.run(cmd, capture_output=True, text=True, check=True) return result.stdout.strip() except subprocess.CalledProcessError as e: print(f"Error running command {' '.join(cmd)}: {e}") sys.exit(1) def get_dependencies(self, exe_path: Path, dependencies: List[Path]) -> None: """Get all DLL dependencies for an executable using ldd.""" # Use ldd to get dependencies ldd_output = self.run_command(['ldd', str(exe_path)]) for line in ldd_output.split('\n'): if '/mingw64' in line and '.dll' in line: # Extract the DLL path parts = line.split() if len(parts) >= 3: dll_path = parts[2].replace('/mingw64', str(self.mingw_prefix)) dll_path = Path(dll_path) if dll_path not in dependencies: dependencies.append(dll_path) def copy_file(self, src: Path, dst: Path) -> None: """Copy a file if it hasn't been copied already.""" if dst.exists(): print(f" Already copied: {src.name}") return if not src.exists(): print(f"ERROR: Required file not found: {src}") sys.exit(1) try: # Create parent directories if needed dst.parent.mkdir(parents=True, exist_ok=True) # Copy the file shutil.copy2(src, dst) print(f" Copied: {src.name}") except Exception as e: print(f"ERROR: Failed to copy file {src} to {dst}: {e}") sys.exit(1) def copy_dir(self, src_path: str, dst_path: str) -> None: """Copy a directory if it exists.""" if not Path(src_path).exists(): print(f"ERROR: Required directory not found: {src_path}") sys.exit(1) try: Path(dst_path).parent.mkdir(parents=True, exist_ok=True) shutil.copytree(src_path, dst_path, dirs_exist_ok=True) print(f" Copied directory: {Path(src_path).name}") except Exception as e: print(f"ERROR: Failed to copy directory {src_path} to {dst_path}: {e}") sys.exit(1) def copy_gtk_dependencies(self, exe_path: Path, target_exe_dir: Path) -> None: """Copy all dependencies for the GTK executable.""" print(f"Analyzing dependencies for: {exe_path.name}") # Get direct dependencies dependencies = [] self.get_dependencies(exe_path, dependencies) for dep in dependencies: self.get_dependencies(dep, dependencies) # Add dependencies for all pixbuf loader DLLs pixbuf_dir = Path(f"{self.mingw_prefix}/lib/gdk-pixbuf-2.0/2.10.0/loaders") for loader_file in pixbuf_dir.glob("*.dll"): print(f" Scanning pixbuf loader: {loader_file.name}") self.get_dependencies(loader_file, dependencies) for dep in dependencies: self.copy_file(dep, target_exe_dir / dep.name) # Copy GTK resources # Based on this tutorial: https://www.gtk.org/docs/installations/windows#building-and-distributing-your-application def copy_gtk_resources(self) -> None: """Copy GTK resources (themes, icons, schemas, etc.).""" print("Copying GTK resources...") # Copy GdkPixbuf loaders print(" Copying GdkPixbuf loaders...") self.copy_dir( f"{self.mingw_prefix}/lib/gdk-pixbuf-2.0", f"{self.target_dir}/lib/gdk-pixbuf-2.0" ) # Copy icon themes print(" Copying icon themes...") self.copy_dir( f"{self.mingw_prefix}/share/icons/Adwaita", f"{self.target_dir}/share/icons/Adwaita" ) self.copy_dir( f"{self.mingw_prefix}/share/icons/hicolor", f"{self.target_dir}/share/icons/hicolor" ) # Copy GTK themes print(" Copying GTK themes...") self.copy_dir( f"{self.mingw_prefix}/share/gtk-3.0", f"{self.target_dir}/share/themes/Windows10/gtk-3.0" ) # Copy GSettings schemas print(" Copying GSettings schemas...") self.copy_dir( f"{self.mingw_prefix}/share/glib-2.0/schemas", f"{self.target_dir}/share/glib-2.0/schemas" ) # Create settings.ini settings_file = f"{self.target_dir}/share/gtk-3.0/settings.ini" Path(settings_file).parent.mkdir(parents=True, exist_ok=True) with open(settings_file, 'w') as f: f.write("[Settings]\n") f.write("gtk-theme-name=Adwaita\n") f.write("gtk-icon-theme-name=Adwaita\n") f.write("gtk-font-name=Segoe UI 9\n") f.write("gtk-application-prefer-dark-theme=true\n") print(" Created settings.ini") def copy_gtk_executables(self, target_exe_dir: Path) -> None: """Copy helper executables that might be needed.""" print("Copying helper executables...") helper_exes = [ "gdbus.exe", "gspawn-win64-helper.exe", "gspawn-win64-helper-console.exe" ] for exe in helper_exes: exe_src = self.mingw_prefix / "bin" / exe if exe_src.exists(): self.copy_file(exe_src, target_exe_dir / exe) def bundle_application(self, exe_path: Path) -> None: """Main method to bundle the entire application.""" print(f"Bundling GTK application: {exe_path}") # Create target directory structure target_exe_dir = self.target_dir target_exe_dir.mkdir(parents=True, exist_ok=True) # Copy all dependencies self.copy_gtk_dependencies(exe_path, target_exe_dir) # Copy helper executables self.copy_gtk_executables(target_exe_dir) # Copy GTK resources self.copy_gtk_resources() def main(): if len(sys.argv) != 3: print("Usage: python3 gtk-win-bundler.py ") sys.exit(1) # Check for MINGW_PREFIX environment variable mingw_prefix = os.environ.get('MINGW_PREFIX') if not mingw_prefix: print("Error: MINGW_PREFIX environment variable is not set") sys.exit(1) exe_path = Path(sys.argv[1]) target_dir = Path(sys.argv[2]) bundler = GTKBundler(mingw_prefix, target_dir) bundler.bundle_application(exe_path) if __name__ == "__main__": main() ================================================ FILE: .github/releasers/windows/pactus-gui.manifest ================================================ Pactus GUI ================================================ FILE: .github/workflows/codeql.yml ================================================ name: "CodeQL Advanced" on: push: branches: ["main"] pull_request: branches: ["main"] schedule: - cron: "23 3 * * 0" jobs: analyze: name: Analyze (${{ matrix.language }}) runs-on: "ubuntu-latest" permissions: # required for all workflows security-events: write # required to fetch internal or private CodeQL packs packages: read strategy: fail-fast: false matrix: # https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning#changing-the-languages-that-are-analyzed include: - language: actions build-mode: none - language: go build-mode: manual steps: - name: Checkout repository uses: actions/checkout@v6 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs queries: security-extended, security-and-quality - if: matrix.build-mode == 'manual' shell: bash run: make build - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" ================================================ FILE: .github/workflows/coverage.yml ================================================ name: Reporting Test Coverage permissions: contents: read on: push: branches: ["main"] pull_request: branches: ["main"] jobs: coverage: runs-on: ubuntu-latest steps: - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Checkout code uses: actions/checkout@v6 - name: Test with coverage run: go test -gcflags=-l -coverprofile=coverage.txt -covermode=atomic ./... - name: Upload coverage report uses: codecov/codecov-action@v5 env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} ================================================ FILE: .github/workflows/deadlock.yml ================================================ name: Deadlock and Data Race Detection permissions: contents: read on: pull_request: branches: ["main"] jobs: data-race: runs-on: ubuntu-latest steps: - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Checkout code uses: actions/checkout@v6 - name: Test with data race detection run: make test_race - name: Replace sync.RWMutex with deadlock.RWMutex run: find . -type f -name "*.go" -not -path '*/\.*' -exec sed -i -- 's/\t"sync"/\tsync "github.com\/sasha-s\/go-deadlock"/g' {} + - name: Adding go-deadlock package run: go get github.com/sasha-s/go-deadlock - name: Test with deadlock detection run: make test ================================================ FILE: .github/workflows/docker.yml ================================================ name: Building Docker and Push to DockerHub permissions: contents: read on: push: tags: ["v[0-9]+.[0-9]+.[0-9]+"] # Trigger on version tags (e.g., v1.0.0) branches: ["main"] env: REGISTRY_IMAGE: pactus/pactus jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: platform: - linux/amd64 - linux/arm/v6 - linux/arm/v7 - linux/arm64 - linux/386 - linux/ppc64le steps: - name: Prepare run: | platform=${{ matrix.platform }} echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV - name: Checkout code uses: actions/checkout@v6 - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Extract metadata (tags, labels) for Docker id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY_IMAGE }} - name: Build and push platform-specific image id: build uses: docker/build-push-action@v6 with: context: . platforms: ${{ matrix.platform }} push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} - name: Export digest run: | mkdir -p /tmp/digests digest="${{ steps.build.outputs.digest }}" touch "/tmp/digests/${digest#sha256:}" - name: Upload digest uses: actions/upload-artifact@v6 with: name: digests-${{ env.PLATFORM_PAIR }} path: /tmp/digests/* if-no-files-found: error retention-days: 1 merge: runs-on: ubuntu-latest needs: - build steps: - name: Download digests uses: actions/download-artifact@v6 with: path: /tmp/digests pattern: digests-* merge-multiple: true - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Docker meta id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY_IMAGE }} - name: Login to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Create manifest list and push working-directory: /tmp/digests run: | docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ $(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *) - name: Inspect image run: | docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.meta.outputs.version }} ================================================ FILE: .github/workflows/gui.yml ================================================ name: Build and Test GUI permissions: contents: read on: push: branches: ["main"] pull_request: branches: ["main"] jobs: build-gui: runs-on: ${{ matrix.name }} defaults: run: shell: ${{ matrix.shell }} strategy: matrix: # Default values for `defaults.run.shell` # https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#defaultsrunshell include: - name: ubuntu-latest shell: "bash -e {0}" - name: macos-latest shell: "bash -e {0}" - name: windows-latest shell: "msys2 {0}" steps: - uses: actions/checkout@v6 - name: Setup Go for macOS and Linux if: runner.os != 'Windows' uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Install Dependencies (Linux) if: runner.os == 'Linux' run: | sudo apt update sudo apt install -y libgtk-3-dev libcairo2-dev libglib2.0-dev - name: Install Dependencies (macOS) if: runner.os == 'macOS' run: brew install gtk+3 - name: Setup MSYS2 and Dependencies (Windows) if: runner.os == 'Windows' uses: msys2/setup-msys2@v2 with: msystem: MINGW64 install: >- git make glib2-devel mingw-w64-x86_64-go mingw-w64-x86_64-gtk3 mingw-w64-x86_64-glib2 mingw-w64-x86_64-gcc mingw-w64-x86_64-pkg-config - name: Patch pkgconfig (Windows) if: runner.os == 'Windows' run: | sed -i -e 's/-Wl,-luuid/-luuid/g' /mingw64/lib/pkgconfig/gdk-3.0.pc ####################################################### ## Caching Go modules and GTK dependencies - name: Get Go environment id: go-env run: | echo "cache=$(go env GOCACHE)" >> $GITHUB_ENV echo "modcache=$(go env GOMODCACHE)" >> $GITHUB_ENV echo "lintcache=$HOME/.cache/golangci-lint" >> $GITHUB_ENV # Example for caching Go dependencies: # https://github.com/actions/cache/blob/main/examples.md#go---modules - uses: actions/cache@v5 id: cache with: path: | ${{ env.cache }} ${{ env.modcache }} ${{ env.lintcache }} key: ${{ matrix.name }}-go-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ matrix.name }}-go- ####################################################### - name: Install GTK if: steps.cache.outputs.cache-hit != 'true' run: go install github.com/gotk3/gotk3/gtk - name: Build the GUI binary run: make build_gui - name: Test the GUI binary run: go test -tags gtk ./cmd/gtk/... - name: Lint check (Linux only) if: runner.os == 'Linux' uses: golangci/golangci-lint-action@v9 with: version: v2.11.4 args: --build-tags gtk ================================================ FILE: .github/workflows/linting.yml ================================================ name: Lint and Format Check permissions: contents: read on: push: branches: ["main"] pull_request: branches: ["main"] jobs: linting: runs-on: ubuntu-latest steps: - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Checkout code uses: actions/checkout@v6 - name: Check linting and formatting uses: golangci/golangci-lint-action@v9 with: version: v2.11.4 - name: Check proto files run: | go install github.com/bufbuild/buf/cmd/buf@v1.67.0 make proto-check ================================================ FILE: .github/workflows/packager.yml ================================================ ## Important Notes: ## 1. The Releaser workflow is triggered when a new tag is pushed to the repository. ## 2. The Packager workflow is triggered when the Releaser workflow completes successfully. ## 3. GitHub always executes this workflow using the version from the main branch ## 4. To package the correct release, it checks out the latest tag. ## name: Packager permissions: contents: read id-token: write on: workflow_run: workflows: ["Releaser"] types: ["completed"] jobs: packager: runs-on: ubuntu-latest if: github.event.workflow_run.conclusion == 'success' outputs: dry_run: ${{ steps.release-type.outputs.dry_run }} steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - name: Determine Release Type id: release-type run: | LATEST_TAG=$(git describe --tags `git rev-list --tags --max-count=1`) echo "Latest tag: $LATEST_TAG" if [[ "$LATEST_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "🚀 Final release detected." DRY_RUN=false elif [[ "$LATEST_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-rc[0-9]+$ ]]; then echo "🧪 Pre-release detected, using dry-run." DRY_RUN=true else echo "Tag $LATEST_TAG is invalid." exit 1 fi echo "dry_run=$DRY_RUN" >> "$GITHUB_OUTPUT" echo "LATEST_TAG=$LATEST_TAG" >> $GITHUB_ENV git checkout $LATEST_TAG - name: Setup Node.js uses: actions/setup-node@v6 with: node-version: "20" registry-url: "https://registry.npmjs.org" - name: Create Packages run: bash ./.github/packager/packager.sh env: VERSION: ${{ env.LATEST_TAG }} - name: Upload `package-js-grpc` package uses: actions/upload-artifact@v6 with: name: package-js-grpc path: packages/js/pactus-grpc - name: Upload `package-js-jsonrpc` package uses: actions/upload-artifact@v6 with: name: package-js-jsonrpc path: packages/js/pactus-jsonrpc - name: Upload `package-python-grpc` package uses: actions/upload-artifact@v6 with: name: package-python-grpc path: packages/python/pactus-grpc - name: Upload `package-python-jsonrpc` package uses: actions/upload-artifact@v6 with: name: package-python-jsonrpc path: packages/python/pactus-jsonrpc - name: Upload `package-rust-grpc` package uses: actions/upload-artifact@v6 with: name: package-rust-grpc path: packages/rust/pactus-grpc - name: Upload `package-rust-jsonrpc` package uses: actions/upload-artifact@v6 with: name: package-rust-jsonrpc path: packages/rust/pactus-jsonrpc publish-npm-grpc: name: Publish pactus-grpc package to npm needs: packager runs-on: ubuntu-latest environment: name: npmjs.com url: https://npmjs.com/package/pactus-grpc steps: - name: Download JavaScript Package uses: actions/download-artifact@v6 with: name: package-js-grpc - name: Setup Node.js uses: actions/setup-node@v6 with: node-version: "20" registry-url: "https://registry.npmjs.org" - name: Publish to npm run: | if [[ "${{ needs.packager.outputs.dry_run }}" == "true" ]]; then npm publish --access public --dry-run else npm publish --access public fi publish-npm-jsonrpc: name: Publish pactus-jsonrpc package to npm needs: packager runs-on: ubuntu-latest environment: name: npmjs.com url: https://npmjs.com/package/pactus-jsonrpc steps: - name: Download JavaScript Package uses: actions/download-artifact@v6 with: name: package-js-jsonrpc - name: Setup Node.js uses: actions/setup-node@v6 with: node-version: "20" registry-url: "https://registry.npmjs.org" - name: Publish to npm run: | if [[ "${{ needs.packager.outputs.dry_run }}" == "true" ]]; then npm publish --access public --dry-run else npm publish --access public fi publish-pypi-grpc: name: Publish pactus-grpc package to PyPI needs: packager runs-on: ubuntu-latest environment: name: pypi.org url: https://pypi.org/p/pactus-grpc steps: - name: Download Python Package uses: actions/download-artifact@v6 with: name: package-python-grpc - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.13" - name: Install build tools and build Python wheel run: | python3 -m pip install build --user python3 -m build - name: Publish distribution to PyPI if: needs.packager.outputs.dry_run == 'false' uses: pypa/gh-action-pypi-publish@release/v1 publish-pypi-jsonrpc: name: Publish pactus-jsonrpc package to PyPI needs: packager runs-on: ubuntu-latest environment: name: pypi.org url: https://pypi.org/p/pactus-jsonrpc steps: - name: Download Python Package uses: actions/download-artifact@v6 with: name: package-python-jsonrpc - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.13" - name: Install build tools and build Python wheel run: | python3 -m pip install build --user python3 -m build - name: Publish distribution to PyPI if: needs.packager.outputs.dry_run == 'false' uses: pypa/gh-action-pypi-publish@release/v1 publish-crates-grpc: name: Publish pactus-grpc package to crates.io needs: packager runs-on: ubuntu-latest environment: name: crates.io url: https://crates.io/crates/pactus-grpc steps: - name: Download Rust Package uses: actions/download-artifact@v6 with: name: package-rust-grpc - uses: dtolnay/rust-toolchain@stable with: toolchain: 1.90.0 - name: Publish to crates.io run: | if [[ "${{ needs.packager.outputs.dry_run }}" == "true" ]]; then cargo publish --dry-run else cargo publish fi env: CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} publish-crates-jsonrpc: name: Publish pactus-jsonrpc package to crates.io needs: packager runs-on: ubuntu-latest environment: name: crates.io url: https://crates.io/crates/pactus-jsonrpc steps: - name: Download Rust Package uses: actions/download-artifact@v6 with: name: package-rust-jsonrpc - uses: dtolnay/rust-toolchain@stable with: toolchain: 1.90.0 - name: Publish to crates.io run: | if [[ "${{ needs.packager.outputs.dry_run }}" == "true" ]]; then cargo publish --dry-run else cargo publish fi env: CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} ================================================ FILE: .github/workflows/releaser.yml ================================================ name: Releaser permissions: # https://github.com/softprops/action-gh-release?tab=readme-ov-file#permissions contents: write on: push: tags: ["v*"] jobs: ######################################## build-cli: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - name: Install Dependencies run: | sudo apt update sudo apt install zip - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Create release files run: bash ./.github/releasers/releaser_cli.sh - name: Calculate sha256sum run: sha256sum pactus-*.zip pactus-*tar.gz > checksum-cli.txt - name: Upload checksum artifact uses: actions/upload-artifact@v6 with: name: checksum-cli path: checksum-cli.txt - name: Publish uses: softprops/action-gh-release@v2 with: files: | pactus-*.zip pactus-*.tar.gz env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ######################################## build-gui-linux: runs-on: ${{ matrix.runner }} strategy: matrix: name: [linux-amd64, linux-arm64] include: - name: linux-amd64 runner: ubuntu-24.04 - name: linux-arm64 runner: ubuntu-24.04-arm steps: - uses: actions/checkout@v6 - name: Install Dependencies run: | sudo apt update sudo apt install libgtk-3-dev libcairo2-dev libglib2.0-dev libfuse2 pkg-config dpkg dpkg-dev - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Create release files run: bash ./.github/releasers/releaser_gui_linux.sh - name: Calculate sha256sum run: sha256sum pactus-gui*.tar.gz pactus-gui*.AppImage > checksum-${{ matrix.name }}.txt - name: Upload checksum artifact uses: actions/upload-artifact@v6 with: name: checksum-${{ matrix.name }} path: checksum-${{ matrix.name }}.txt - name: Publish uses: softprops/action-gh-release@v2 with: files: | pactus-gui*.tar.gz pactus-gui*.AppImage env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ######################################## build-gui-macos: runs-on: ${{ matrix.runner }} strategy: matrix: name: [macos-amd64, macos-arm64] include: - name: macos-amd64 runner: macos-15-intel lib_home: /usr/local - name: macos-arm64 runner: macos-26 lib_home: /opt/homebrew env: LIB_HOME: ${{ matrix.lib_home }} steps: - uses: actions/checkout@v6 - name: Install Dependencies run: brew install gtk+3 librsvg create-dmg coreutils gdk-pixbuf glib-networking pkg-config - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Create release files run: bash ./.github/releasers/releaser_gui_macos.sh - name: Calculate sha256sum run: sha256sum pactus-*.dmg pactus-*.tar.gz > checksum-${{ matrix.name }}.txt - name: Upload checksum artifact uses: actions/upload-artifact@v6 with: name: checksum-${{ matrix.name }} path: checksum-${{ matrix.name }}.txt - name: Publish uses: softprops/action-gh-release@v2 with: files: | pactus-*.dmg pactus-*.tar.gz env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ######################################## build-gui-windows: runs-on: ${{ matrix.runner }} strategy: matrix: name: [windows_amd64] include: - name: windows_amd64 runner: windows-2025 defaults: run: shell: msys2 {0} steps: - uses: actions/checkout@v6 - uses: msys2/setup-msys2@v2 with: msystem: MINGW64 update: true install: git make p7zip glib2-devel mingw-w64-x86_64-go mingw-w64-x86_64-gtk3 mingw-w64-x86_64-glib2 mingw-w64-x86_64-gcc mingw-w64-x86_64-pkg-config mingw-w64-x86_64-adwaita-icon-theme mingw-w64-x86_64-hicolor-icon-theme - name: Get Version id: get_version run: | VERSION="$(echo `git -C . describe --abbrev=0 --tags` | sed 's/^.//')" echo "VERSION=$VERSION" >> $GITHUB_OUTPUT - name: Build Binaries run: bash ./.github/releasers/releaser_gui_windows_build.sh - name: Sign Pactus Daemon uses: ./.github/actions/windows-signing with: signpath-api-token: ${{ secrets.SIGNPATH_API_TOKEN }} signpath-signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }} artifact-name: pactus-daemon - name: Sign Pactus Wallet uses: ./.github/actions/windows-signing with: signpath-api-token: ${{ secrets.SIGNPATH_API_TOKEN }} signpath-signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }} artifact-name: pactus-wallet - name: Sign Pactus Shell uses: ./.github/actions/windows-signing with: signpath-api-token: ${{ secrets.SIGNPATH_API_TOKEN }} signpath-signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }} artifact-name: pactus-shell - name: Sign Pactus GUI uses: ./.github/actions/windows-signing with: signpath-api-token: ${{ secrets.SIGNPATH_API_TOKEN }} signpath-signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }} artifact-name: pactus-gui - name: Build Installer run: bash ./.github/releasers/releaser_gui_windows_installer.sh - name: Sign Installer uses: ./.github/actions/windows-signing with: signpath-api-token: ${{ secrets.SIGNPATH_API_TOKEN }} signpath-signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }} artifact-name: pactus-gui_${{ steps.get_version.outputs.VERSION }}_${{ matrix.name }}_installer - name: Move Installer to Root run: mv ./build/signed/pactus-gui_*_installer.exe . - name: Calculate sha256sum run: sha256sum pactus-gui_*.zip pactus-gui_*_installer.exe > checksum-${{ matrix.name }}.txt - name: Upload checksum artifact uses: actions/upload-artifact@v6 with: name: checksum-${{ matrix.name }} path: checksum-${{ matrix.name }}.txt - name: Publish uses: softprops/action-gh-release@v2 with: files: | pactus-gui_*.zip pactus-gui_*_installer.exe env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ######################################## checksums: needs: [ build-cli, build-gui-linux, build-gui-macos, build-gui-windows, ] runs-on: ubuntu-latest steps: - name: Download checksum artifacts uses: actions/download-artifact@v6 with: path: checksums - name: Combine checksums run: | cat checksums/*/*.txt > SHA256SUMS cat SHA256SUMS - name: Upload SHA256SUMS as an artifact uses: actions/upload-artifact@v6 with: name: sha256sums path: SHA256SUMS - name: Publish uses: softprops/action-gh-release@v2 with: files: SHA256SUMS env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ######################################## cosign: needs: [checksums] runs-on: ubuntu-latest steps: - name: Download SHA256SUMS artifact uses: actions/download-artifact@v6 with: name: sha256sums - uses: sigstore/cosign-installer@v3 - name: Sign Checksum run: cosign sign-blob --yes --key env://COSIGN_PRIVATE_KEY SHA256SUMS > SHA256SUMS.sig env: COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }} COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }} - name: Publish uses: softprops/action-gh-release@v2 with: files: SHA256SUMS.sig ######################################## downloader: needs: [cosign] runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - name: Create Downloader file run: | VERSION="$(echo `git -C . describe --abbrev=0 --tags` | sed 's/^.//')" # "v1.2.3" -> "1.2.3" echo ${VERSION} sed -i "s/__VERSION__/${VERSION}/g" .github/releasers/pactus_downloader.sh - name: Publish uses: softprops/action-gh-release@v2 with: files: .github/releasers/pactus_downloader.sh env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/semantic-pr.yml ================================================ name: Semantic PR permissions: pull-requests: read on: pull_request_target: types: - opened - edited - synchronize - reopened jobs: main: name: Validate PR title runs-on: ubuntu-latest steps: - uses: amannn/action-semantic-pull-request@v6 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: # Configure which scopes are allowed (newline-delimited). scopes: | github linter deps makefile release releaser packager other daemon cbor cmd firewall gtk shell wallet-cmd committee config consensus crypto docs docker encoding execution genesis network node sandbox scripts sortition state store sync main txpool types util version wallet www grpc proto jsonrpc http html zeromq windows linux macos # Configure that a scope must always be provided. requireScope: true # The subject should not start with an uppercase character and should not end with a period. subjectPattern: ^(?![A-Z]).+[^.]$ subjectPatternError: | The subject "{subject}" cannot start with an uppercase character or end with a period. ================================================ FILE: .github/workflows/testing.yml ================================================ name: Unit Testing permissions: contents: read on: push: branches: ["main"] pull_request: branches: ["main"] jobs: test: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v6 - name: Install Go uses: actions/setup-go@v6 with: go-version: "1.26.2" - name: Unit tests run: make unit_test ================================================ FILE: .gitignore ================================================ build/ .DS_Store # IDEs .idea .vscode # TODO tasks todo # Releasers output /pactus-* # VIM artifacts .swp .*.sw* packages/ ================================================ FILE: .golangci.yml ================================================ version: "2" linters: enable: - asasalint - asciicheck - bidichk - bodyclose - contextcheck - copyloopvar - decorder - dogsled - dupword - durationcheck - errchkjson - errname - errorlint - exhaustive - forbidigo - gocheckcompilerdirectives - gocognit - gocritic - gocyclo - godot - goheader - gomoddirectives - gomodguard - goprintffuncname - gosec - gosmopolitan - grouper - importas - lll - loggercheck - maintidx - makezero - mirror - misspell - musttag - nakedret - nestif - nilerr - nilnil - nlreturn - noctx - nolintlint - nosprintfhostport - prealloc - predeclared - promlinter - reassign - revive - rowserrcheck - sqlclosecheck - staticcheck - tagalign - tagliatelle - testableexamples - testifylint - thelper - tparallel - unconvert - unparam - usestdlibvars - usetesting - varnamelen - wastedassign - whitespace - zerologlint settings: gocritic: disabled-checks: - ifElseChain - unnamedResult - importShadow enabled-tags: - diagnostic - style - performance gosec: excludes: - G304 - G204 - G115 - G704 # SSRF via taint analysis - ignore (URLs are validated/trusted) - G705 # XSS via taint analysis - ignore (internal HTML, values escaped) govet: disable: - fieldalignment enable-all: true settings: shadow: strict: true nestif: min-complexity: 6 predeclared: ignore: - len - ' min' - ' max' qualified-name: true revive: enable-all-rules: true rules: - name: exported disabled: true - name: package-comments disabled: true - name: add-constant disabled: true - name: line-length-limit disabled: true - name: cognitive-complexity disabled: true - name: function-length disabled: true - name: cyclomatic disabled: true - name: unchecked-type-assertion disabled: true - name: max-public-structs disabled: true - name: flag-parameter disabled: true - name: deep-exit disabled: true - name: get-return disabled: true - name: confusing-naming disabled: true - name: function-result-limit disabled: true - name: import-shadowing disabled: true - name: redefines-builtin-id disabled: true - name: enforce-switch-style disabled: true - name: identical-switch-branches disabled: true - name: package-naming disabled: true # - name: use-slices-sort # disabled: true - name: var-naming arguments: - [] # AllowList - [] # DenyList - - skip-package-name-checks: true - name: unhandled-error arguments: - fmt.Printf - fmt.Println - fmt.Fprintf - strings.Builder.WriteString - strings.Builder.WriteRune - strings.Builder.WriteByte - bytes.Buffer.Write - bytes.Buffer.WriteString staticcheck: checks: - all - -ST1000 - -QF1008 testifylint: enable-all: true usetesting: os-temp-dir: true context-background: true context-todo: true tagliatelle: case: rules: json: snake yaml: snake use-field-name: false varnamelen: ignore-names: - ok - ip - db - "no" - tt - n - i - j - l - h - il - r - w ignore-decls: - wg sync.WaitGroup - ts *testsuite.TestSuite - td *testData - ma multiaddr.Multiaddr - db *leveldb.DB exclusions: generated: lax rules: - linters: - forbidigo - gocognit - maintidx - nestif - gosec path: _test.go - path: (.+)\.go$ text: 'shadow: declaration of "err" shadows' - path: (.+)\.go$ text: 'builtinShadow: shadowing of predeclared identifier: min' - path: (.+)\.go$ text: 'builtinShadow: shadowing of predeclared identifier: max' - path: (.+)\.go$ text: 'builtinShadow: shadowing of predeclared identifier: len' paths: - third_party$ - builtin$ - examples$ - util/bip39/wordlists/ formatters: enable: - gci - gofmt - gofumpt - goimports ================================================ FILE: CHANGELOG.md ================================================ # Changelog ## [1.13.0](https://github.com/pactus-project/pactus/compare/v1.12.0...v1.13.0) (2026-04-03) ### Feat - **grpc**: update validator object to support delegation ([#2117](https://github.com/pactus-project/pactus/pull/2117)) - **cmd**: add delegation flags for bond and unbond transactions ([#2106](https://github.com/pactus-project/pactus/pull/2106)) - **other**: implement PIP-49 ([#2101](https://github.com/pactus-project/pactus/pull/2101)) - **gtk**: add network info tab ([#2098](https://github.com/pactus-project/pactus/pull/2098)) - **gtk**: add committee info tab ([#2096](https://github.com/pactus-project/pactus/pull/2096)) ### Fix - **sync**: update the latest support version ([#2125](https://github.com/pactus-project/pactus/pull/2125)) - **state**: fix delegate reward on boundaries ([#2120](https://github.com/pactus-project/pactus/pull/2120)) - **state**: check subsidy transaction for delegated reward ([#2119](https://github.com/pactus-project/pactus/pull/2119)) - **types**: check decode size for validator ([#2116](https://github.com/pactus-project/pactus/pull/2116)) - **cmd**: set protocol version for localnet ([#2114](https://github.com/pactus-project/pactus/pull/2114)) - **gtk**: set percentage of protocol versions ([#2113](https://github.com/pactus-project/pactus/pull/2113)) - **gtk**: set public key for known validators ([#2112](https://github.com/pactus-project/pactus/pull/2112)) - **wallet**: ignore delegation on normal bond tx ([#2111](https://github.com/pactus-project/pactus/pull/2111)) - **state**: set subsidy for delegated reward ([#2109](https://github.com/pactus-project/pactus/pull/2109)) - **execution**: check delegation for withdraw execution ([#2108](https://github.com/pactus-project/pactus/pull/2108)) - **execution**: check delegation for unbond execution ([#2107](https://github.com/pactus-project/pactus/pull/2107)) - **types**: set delegation-owner for unbond transaction ([#2105](https://github.com/pactus-project/pactus/pull/2105)) - **types**: fix bond encoding issue ([#2104](https://github.com/pactus-project/pactus/pull/2104)) - **wallet**: set remote provider if not specified ([#2097](https://github.com/pactus-project/pactus/pull/2097)) ## [1.12.0](https://github.com/pactus-project/pactus/compare/v1.11.0...v1.12.0) (2026-02-21) ### Feat - **grpc**: add committee_size to blockchain_info ([#2091](https://github.com/pactus-project/pactus/pull/2091)) - **gtk**: add node-agent field ([#2090](https://github.com/pactus-project/pactus/pull/2090)) - **gtk**: connect to remote node ([#2079](https://github.com/pactus-project/pactus/pull/2079)) - **grpc**: decouple peer list API ([#2078](https://github.com/pactus-project/pactus/pull/2078)) - **gtk**: add validator page ([#2068](https://github.com/pactus-project/pactus/pull/2068)) ### Fix - **grpc**: add in_committee field to blockchain info ([#2089](https://github.com/pactus-project/pactus/pull/2089)) - **util**: prevent panic on sha256 mismatch error ([#2088](https://github.com/pactus-project/pactus/pull/2088)) - **gtk**: set connection label ([#2085](https://github.com/pactus-project/pactus/pull/2085)) - **gtk**: update view asynchronously ([#2082](https://github.com/pactus-project/pactus/pull/2082)) - **gtk**: ensure GTK UIs run on main thread ([#2081](https://github.com/pactus-project/pactus/pull/2081)) - **gtk**: define validator model ([#2075](https://github.com/pactus-project/pactus/pull/2075)) - **gtk**: close wallet on node startup ([#2057](https://github.com/pactus-project/pactus/pull/2057)) ### Refactor - **gtk**: refactor controllers ([#2080](https://github.com/pactus-project/pactus/pull/2080)) - **gtk**: use gRPC connection for node model ([#2077](https://github.com/pactus-project/pactus/pull/2077)) - **node**: set global context ([#2076](https://github.com/pactus-project/pactus/pull/2076)) - **grpc**: update blockchain info API ([#2073](https://github.com/pactus-project/pactus/pull/2073)) - **gtk**: use gRPC for wallet model ([#2070](https://github.com/pactus-project/pactus/pull/2070)) - **grpc**: define wallet transaction info ([#2071](https://github.com/pactus-project/pactus/pull/2071)) ## [1.11.0](https://github.com/pactus-project/pactus/compare/v1.10.0...v1.11.0) (2026-01-25) ### Feat - **gtk**: use timeout to refresh wallet page ([#2039](https://github.com/pactus-project/pactus/pull/2039)) - **gtk**: add transactions page ([#2035](https://github.com/pactus-project/pactus/pull/2035)) - **types**: define ShortString for Address and Hash ([#2031](https://github.com/pactus-project/pactus/pull/2031)) - **gtk**: add splash screen for starting the node ([#2019](https://github.com/pactus-project/pactus/pull/2019)) - **wallet**: define query parameters for list of transactions ([#2014](https://github.com/pactus-project/pactus/pull/2014)) - **wallet**: define Blockchain Provider interface ([#2013](https://github.com/pactus-project/pactus/pull/2013)) - **wallet**: process blocks for wallet transactions ([#2011](https://github.com/pactus-project/pactus/pull/2011)) - **cmd**: add transaction command ([#2006](https://github.com/pactus-project/pactus/pull/2006)) - **grpc**: add List Transaction API for wallets ([#2005](https://github.com/pactus-project/pactus/pull/2005)) - **grpc**: add Update Password API for wallets ([#2004](https://github.com/pactus-project/pactus/pull/2004)) - **wallet**: add SQLite3 storage ([#2001](https://github.com/pactus-project/pactus/pull/2001)) - **util**: add LogString for compact log formatting ([#2000](https://github.com/pactus-project/pactus/pull/2000)) - **types**: decode transaction from hex string ([#1998](https://github.com/pactus-project/pactus/pull/1998)) - **types**: decode block from hex string ([#1999](https://github.com/pactus-project/pactus/pull/1999)) - **types**: format amount with thousand separators ([#1977](https://github.com/pactus-project/pactus/pull/1977)) ### Fix - **txpool**: perform basic check on appending transactions ([#2050](https://github.com/pactus-project/pactus/pull/2050)) - **gtk**: refresh wallet info ([#2049](https://github.com/pactus-project/pactus/pull/2049)) - **wallet**: close wallet before starting the node ([#2047](https://github.com/pactus-project/pactus/pull/2047)) - **gtk**: refresh wallet view on changing address ([#2041](https://github.com/pactus-project/pactus/pull/2041)) - **wallet**: total balance for non-existing accounts ([#2040](https://github.com/pactus-project/pactus/pull/2040)) - **wallet**: add no column for transaction table ([#2034](https://github.com/pactus-project/pactus/pull/2034)) - **wallet**: configure Pragmas and create indices ([#2030](https://github.com/pactus-project/pactus/pull/2030)) - **wallet**: deprecate load wallet API ([#2029](https://github.com/pactus-project/pactus/pull/2029)) - **cmd**: ensure provider is set when recovering wallet ([#2027](https://github.com/pactus-project/pactus/pull/2027)) - **grpc**: correct wallet verbs and add validator addresses route ([#2023](https://github.com/pactus-project/pactus/pull/2023)) - **wallet**: set default values for address and direction ([#2022](https://github.com/pactus-project/pactus/pull/2022)) - **cmd**: show transaction list in a table ([#2015](https://github.com/pactus-project/pactus/pull/2015)) - **grpc**: include driver and path in GetWalletInfo response ([#2010](https://github.com/pactus-project/pactus/pull/2010)) - **wallet**: load default_wallet on startup ([#2008](https://github.com/pactus-project/pactus/pull/2008)) - **util**: list only top-level files and directories without recursion ([#2009](https://github.com/pactus-project/pactus/pull/2009)) - **wallet**: list SQLite wallets in wallet manager ([#2003](https://github.com/pactus-project/pactus/pull/2003)) - **wallet**: add Close method for wallet ([#2002](https://github.com/pactus-project/pactus/pull/2002)) - **network**: remove leading and trailing spaces from network key ([#1992](https://github.com/pactus-project/pactus/pull/1992)) - **gtk**: fix dark theme issue in Windows ([#1973](https://github.com/pactus-project/pactus/pull/1973)) - **wallet**: panic on disconnect of wallet client connection ([#1971](https://github.com/pactus-project/pactus/pull/1971)) ### Refactor - **other**: use pipeline package ([#2033](https://github.com/pactus-project/pactus/pull/2033)) - **consensus, network, util**: use scheduler package to manage … ([#2032](https://github.com/pactus-project/pactus/pull/2032)) - **wallet**: define storage interface ([#1995](https://github.com/pactus-project/pactus/pull/1995)) - **gtk**: refactor Pactus GUI ([#1994](https://github.com/pactus-project/pactus/pull/1994)) - **wallet**: refactor wallet manager ([#1993](https://github.com/pactus-project/pactus/pull/1993)) - **version**: replace Split in loops with more efficient SplitSeq ([#1982](https://github.com/pactus-project/pactus/pull/1982)) - **crypto**: use b.Loop() to simplify the code and improve performance ([#1970](https://github.com/pactus-project/pactus/pull/1970)) ## [1.10.0](https://github.com/pactus-project/pactus/compare/v1.9.0...v1.10.0) (2025-10-27) ### Feat - **gtk**: prefer dark theme ([#1965](https://github.com/pactus-project/pactus/pull/1965)) - **wallet**: export the bootstrap and gRPC server list ([#1961](https://github.com/pactus-project/pactus/pull/1961)) - **util**: operating system signal handling package ([#1959](https://github.com/pactus-project/pactus/pull/1959)) - **util**: rename Extend to PadToLeft; add PadToRight ([#1953](https://github.com/pactus-project/pactus/pull/1953)) - **gtk**: set default fee dialog ([#1946](https://github.com/pactus-project/pactus/pull/1946)) - **gtk**: add address recovery page for restore wallet ([#1940](https://github.com/pactus-project/pactus/pull/1940)) - **cmd**: update daemon init for recovery addresses ([#1939](https://github.com/pactus-project/pactus/pull/1939)) - **grpc**: impl gRPC ping api for latency measurement ([#1936](https://github.com/pactus-project/pactus/pull/1936)) - **wallet**: implement check activity on wallet ([#1938](https://github.com/pactus-project/pactus/pull/1938)) - **wallet**: introduce address recovery ([#1934](https://github.com/pactus-project/pactus/pull/1934)) - **state**: calculate the number of active validators ([#1927](https://github.com/pactus-project/pactus/pull/1927)) - **packager**: add rust-jsonrpc package ([#1911](https://github.com/pactus-project/pactus/pull/1911)) - **packager**: add rust-grpc package ([#1909](https://github.com/pactus-project/pactus/pull/1909)) - **consensus**: the Cheetah implementation ([#1858](https://github.com/pactus-project/pactus/pull/1858)) ### Fix - **sync**: set supporting version to 1.9.0 ([#1949](https://github.com/pactus-project/pactus/pull/1949)) - **network**: set deadline for streams ([#1947](https://github.com/pactus-project/pactus/pull/1947)) - **grpc**: set default fee for WalletInfo API ([#1944](https://github.com/pactus-project/pactus/pull/1944)) - **wallet**: use GetAccount API to check active account ([#1945](https://github.com/pactus-project/pactus/pull/1945)) - **grpc**: set required fields in OpenRPC spec ([#1920](https://github.com/pactus-project/pactus/pull/1920)) - **grpc**: define map as object in OpenRPC sepc ([#1910](https://github.com/pactus-project/pactus/pull/1910)) - **network**: set limit for network message size ([#1904](https://github.com/pactus-project/pactus/pull/1904)) - **cbor**: set limit for Map and Array in CBOR decoder ([#1905](https://github.com/pactus-project/pactus/pull/1905)) - **encoding**: prevent data-length attack ([#1907](https://github.com/pactus-project/pactus/pull/1907)) - **gtk**: ensure GTK starts on main thread ([#1885](https://github.com/pactus-project/pactus/pull/1885)) - **gtk**: change fontmap backend for macOS ([#1884](https://github.com/pactus-project/pactus/pull/1884)) - **gtk**: resolve crash issue on MacOs ([#1882](https://github.com/pactus-project/pactus/pull/1882)) ### Refactor - **cmd, gtk**: separate address recovery from node creation flow ([#1964](https://github.com/pactus-project/pactus/pull/1964)) - **util**: use b.Loop() to simplify the code and improve performance ([#1957](https://github.com/pactus-project/pactus/pull/1957)) - **wallet**: re-structure the server list ([#1962](https://github.com/pactus-project/pactus/pull/1962)) - **util**: define terminal package ([#1960](https://github.com/pactus-project/pactus/pull/1960)) - **cmd**: move prompt to util package ([#1958](https://github.com/pactus-project/pactus/pull/1958)) - **crypto**: check BLS aggregate primitive error ([#1956](https://github.com/pactus-project/pactus/pull/1956)) - **network**: use WaitGroup.Go to simplify code ([#1935](https://github.com/pactus-project/pactus/pull/1935)) - **state**: refactor reward transaction ([#1901](https://github.com/pactus-project/pactus/pull/1901)) - **state**: check genesis state using certificate presence ([#1899](https://github.com/pactus-project/pactus/pull/1899)) - **other**: use maps.Copy for cleaner map handling ([#1900](https://github.com/pactus-project/pactus/pull/1900)) ## [1.9.0](https://github.com/pactus-project/pactus/compare/v1.8.0...v1.9.0) (2025-09-10) ### Feat - **grpc**: report current time in node API ([#1864](https://github.com/pactus-project/pactus/pull/1864)) - **state**: update block version on forks ([#1863](https://github.com/pactus-project/pactus/pull/1863)) - **state**: set foundation addresses for split reward ([#1859](https://github.com/pactus-project/pactus/pull/1859)) - **wallet**: set default transaction fee ([#1849](https://github.com/pactus-project/pactus/pull/1849)) - **committee**: check if committee support a protocol version ([#1855](https://github.com/pactus-project/pactus/pull/1855)) - **sync**: set protocol version for proposal message ([#1854](https://github.com/pactus-project/pactus/pull/1854)) - **committee**: calculate committee protocol version percentages ([#1853](https://github.com/pactus-project/pactus/pull/1853)) - **state**: set protocol version for validators ([#1851](https://github.com/pactus-project/pactus/pull/1851)) - **types**: define protocol version ([#1850](https://github.com/pactus-project/pactus/pull/1850)) - **state**: implement PIP-43 ([#1840](https://github.com/pactus-project/pactus/pull/1840)) - **cmd**: add label option for new address command ([#1842](https://github.com/pactus-project/pactus/pull/1842)) ### Fix - **util**: ignore filtered levels ([#1874](https://github.com/pactus-project/pactus/pull/1874)) - **sync**: ignore hello message from outdated nodes ([#1873](https://github.com/pactus-project/pactus/pull/1873)) - **state**: update protocol version for own validators ([#1871](https://github.com/pactus-project/pactus/pull/1871)) - **sync**: banned peer recovery ([#1869](https://github.com/pactus-project/pactus/pull/1869)) - **state**: update block version on enabling fork ([#1866](https://github.com/pactus-project/pactus/pull/1866)) - **sandbox**: remove check height for banned address ([#1868](https://github.com/pactus-project/pactus/pull/1868)) - **state**: check protocol version to enable split-reward fork ([#1857](https://github.com/pactus-project/pactus/pull/1857)) - **cmd**: prevent panic on redownloading chunk ([#1847](https://github.com/pactus-project/pactus/pull/1847)) - **state**: enable soft fork for split reward ([#1846](https://github.com/pactus-project/pactus/pull/1846)) - **cmd**: prompt for label if it is empty ([#1845](https://github.com/pactus-project/pactus/pull/1845)) - **state**: check foundation address in subsidy transaction ([#1844](https://github.com/pactus-project/pactus/pull/1844)) - **wallet**: set Testnet network on upgrading wallet ([#1841](https://github.com/pactus-project/pactus/pull/1841)) - **execution**: remove Ed25519 check ([#1835](https://github.com/pactus-project/pactus/pull/1835)) ### Refactor - **sync**: refactor handshaking protocol ([#1872](https://github.com/pactus-project/pactus/pull/1872)) - **util**: use slices.Equal to simplify code ([#1837](https://github.com/pactus-project/pactus/pull/1837)) - **shell**: rename shell command to interactive ([#1734](https://github.com/pactus-project/pactus/pull/1734)) - **docker**: update go version for Dockerfile ([#1834](https://github.com/pactus-project/pactus/pull/1834)) - **other**: update dependencies ([#1833](https://github.com/pactus-project/pactus/pull/1833)) ## [1.8.0](https://github.com/pactus-project/pactus/compare/v1.7.0...v1.8.0) (2025-07-01) ### Feat - **cmd**: add transport switch in flag start daemon ([#1681](https://github.com/pactus-project/pactus/pull/1681)) - **grpc**: add get raw batch transfer transaction ([#1799](https://github.com/pactus-project/pactus/pull/1799)) - **types**: implement batch transfer payload ([#1793](https://github.com/pactus-project/pactus/pull/1793)) - **packager**: publish jsonrpc packages on release ([#1776](https://github.com/pactus-project/pactus/pull/1776)) - **rest**: define base path for REST APIs ([#1770](https://github.com/pactus-project/pactus/pull/1770)) - **grpc**: define Rest-API server ([#1765](https://github.com/pactus-project/pactus/pull/1765)) - **docs**: add openrpc template and schema ([#1767](https://github.com/pactus-project/pactus/pull/1767)) - **grpc**: support gRPC Web library ([#1762](https://github.com/pactus-project/pactus/pull/1762)) - **jsonrpc**: add CORS support ([#1755](https://github.com/pactus-project/pactus/pull/1755)) - **grpc**: publish `pactus_grpc` package for Python ([#1732](https://github.com/pactus-project/pactus/pull/1732)) - **grpc**: publish `pactus_grpc` package for JS ([#1736](https://github.com/pactus-project/pactus/pull/1736)) - **wallet**: support of AES-256-CBC for the encryption ([#1706](https://github.com/pactus-project/pactus/pull/1706)) - **wallet-cmd**: add Neuter command for wallet ([#1683](https://github.com/pactus-project/pactus/pull/1683)) - **grpc**: add decode raw transaction method ([#1671](https://github.com/pactus-project/pactus/pull/1671)) ### Fix - **execution**: check network type for batch transfer ([#1812](https://github.com/pactus-project/pactus/pull/1812)) - **execution**: set batch transfer height ([#1811](https://github.com/pactus-project/pactus/pull/1811)) - **util**: panic on importing snapshot ([#1807](https://github.com/pactus-project/pactus/pull/1807)) - **sync**: drop messages with mismatched consensus height ([#1810](https://github.com/pactus-project/pactus/pull/1810)) - **firewall**: remove decoding bundle for expired message ([#1682](https://github.com/pactus-project/pactus/pull/1682)) - **util**: replace go-bip39 ([#1795](https://github.com/pactus-project/pactus/pull/1795)) - **wallet**: set Argon2 derived bytes for AES IV ([#1703](https://github.com/pactus-project/pactus/pull/1703)) - **consensus**: schedule timeout to retry querying for the proposal or votes ([#1698](https://github.com/pactus-project/pactus/pull/1698)) - **util**: add manually copy to prevent invalid cross-device link ([#1684](https://github.com/pactus-project/pactus/pull/1684)) ### Refactor - **util**: use the built-in max/min to simplify the code ([#1819](https://github.com/pactus-project/pactus/pull/1819)) - **other**: use slices.Contains to simplify code ([#1802](https://github.com/pactus-project/pactus/pull/1802)) - **www**: rename Rest to HTTP-API ([#1774](https://github.com/pactus-project/pactus/pull/1774)) - **grpc**: update buf.build ([#1716](https://github.com/pactus-project/pactus/pull/1716)) ## [1.7.0](https://github.com/pactus-project/pactus/compare/v1.6.0...v1.7.0) (2025-01-23) ### Feat - **zeromq**: add ZMQ Publishers to NodeInfo API ([#1674](https://github.com/pactus-project/pactus/pull/1674)) - **zeromq**: add publisher raw tx ([#1672](https://github.com/pactus-project/pactus/pull/1672)) - **zeromq**: add publisher raw block ([#1670](https://github.com/pactus-project/pactus/pull/1670)) - **zeromq**: add publisher transaction info ([#1669](https://github.com/pactus-project/pactus/pull/1669)) - **zeromq**: add block info publisher ([#1666](https://github.com/pactus-project/pactus/pull/1666)) - **grpc**: support Ed25519 message signing and verification ([#1667](https://github.com/pactus-project/pactus/pull/1667)) - **other**: add zeromq server with configuration ([#1660](https://github.com/pactus-project/pactus/pull/1660)) - **cmd**: read password from file ([#1653](https://github.com/pactus-project/pactus/pull/1653)) - **network**: evaluate propagate policy for gossip messages ([#1647](https://github.com/pactus-project/pactus/pull/1647)) - **config**: add firewall module to logger config ([#1637](https://github.com/pactus-project/pactus/pull/1637)) ### Fix - **gtk**: panic on windows 11 and mac ([#1650](https://github.com/pactus-project/pactus/pull/1650)) - **consensus**: refactor strong termination for change-proposer phase ([#1643](https://github.com/pactus-project/pactus/pull/1643)) - **network**: restore default message queue size in PubSub module ([#1642](https://github.com/pactus-project/pactus/pull/1642)) - **consensus**: refactor strong termination for change-proposer phase ([#1641](https://github.com/pactus-project/pactus/pull/1641)) - **grpc**: define address for the aggregated public key ([#1608](https://github.com/pactus-project/pactus/pull/1608)) - **gtk**: last block height icon ([#1611](https://github.com/pactus-project/pactus/pull/1611)) - **crypto, state**: resolve panic on 32-bit OSes ([#1604](https://github.com/pactus-project/pactus/pull/1604)) - **cmd**: parse withdraw fee using transaction options ([#1602](https://github.com/pactus-project/pactus/pull/1602)) ## [1.6.0](https://github.com/pactus-project/pactus/compare/v1.5.0...v1.6.0) (2024-11-14) ### Feat - **grpc**: add bls public key and signature aggregate methods ([#1587](https://github.com/pactus-project/pactus/pull/1587)) - **wallet**: create single ed25519 reward address for all validators ([#1570](https://github.com/pactus-project/pactus/pull/1570)) - **gtk**: add fee entry for transfer, bond and withdraw ([#1575](https://github.com/pactus-project/pactus/pull/1575)) - **txpool**: add consumptional fee model ([#1572](https://github.com/pactus-project/pactus/pull/1572)) - **txpool**: calculate consumption when committing a new block ([#1554](https://github.com/pactus-project/pactus/pull/1554)) - **sync**: add metric to track the network activity ([#1552](https://github.com/pactus-project/pactus/pull/1552)) - **wallet**: add wallet service API ([#1548](https://github.com/pactus-project/pactus/pull/1548)) - **config**: add consumption fee configs ([#1547](https://github.com/pactus-project/pactus/pull/1547)) ### Fix - **config**: update TOML parser ([#1592](https://github.com/pactus-project/pactus/pull/1592)) - **gtk**: prevent duplicate address on enter signal in create modal ([#1590](https://github.com/pactus-project/pactus/pull/1590)) - **txpool, cmd, gtk**: broadcast transactions with zero fee ([#1589](https://github.com/pactus-project/pactus/pull/1589)) - **consensus**: send decided vote for previous round on query vote ([#1567](https://github.com/pactus-project/pactus/pull/1567)) - **grpc**: get tx pool content filter by payload type ([#1581](https://github.com/pactus-project/pactus/pull/1581)) - **wallet, cmd**: add support for importing Ed25519 private keys ([#1584](https://github.com/pactus-project/pactus/pull/1584)) - **gtk**: change transactions to transaction in tx link ([#1580](https://github.com/pactus-project/pactus/pull/1580)) - **grpc**: set Bond public key for decoded transaction ([#1577](https://github.com/pactus-project/pactus/pull/1577)) - **other**: add varnamelen linter to improve name convention ([#1568](https://github.com/pactus-project/pactus/pull/1568)) - **grpc**: encode data and signature properly ([#1538](https://github.com/pactus-project/pactus/pull/1538)) - **gtk**: change some text in GUI and pruned position ([#1536](https://github.com/pactus-project/pactus/pull/1536)) ### Refactor - **cmd**: get first account address from wallet as reward address ([#1594](https://github.com/pactus-project/pactus/pull/1594)) - **grpc**: revert GetRawTransfer method and undo deprecation ([#1560](https://github.com/pactus-project/pactus/pull/1560)) - **crypto**: define SerializeSize for PublicKey and Signature ([#1534](https://github.com/pactus-project/pactus/pull/1534)) ## [1.5.0](https://github.com/pactus-project/pactus/compare/v1.4.0...v1.5.0) (2024-10-08) ### Feat - **cmd**: pactus-wallet add info commands ([#1496](https://github.com/pactus-project/pactus/pull/1496)) - **state**: enable Ed25519 for the Testnet ([#1497](https://github.com/pactus-project/pactus/pull/1497)) - **gtk**: support create Ed25519 in gtk ([#1489](https://github.com/pactus-project/pactus/pull/1489)) - **grpc**: add Ed25519 to AddressType proto ([#1492](https://github.com/pactus-project/pactus/pull/1492)) - **wallet**: upgrade wallet ([#1491](https://github.com/pactus-project/pactus/pull/1491)) - **wallet**: supporting Ed25519 curve in wallet ([#1484](https://github.com/pactus-project/pactus/pull/1484)) - **grpc**: add `Proposal` to `ConsensusInfo` API ([#1469](https://github.com/pactus-project/pactus/pull/1469)) - **crypto**: supporting ed25519 ([#1481](https://github.com/pactus-project/pactus/pull/1481)) - **gtk**: adding IsPrune to node widget ([#1470](https://github.com/pactus-project/pactus/pull/1470)) - **daemon**: warn at pruning a prune node attempt ([#1471](https://github.com/pactus-project/pactus/pull/1471)) - **genesis**: separating chain param from genesis param ([#1463](https://github.com/pactus-project/pactus/pull/1463)) - **cmd**: pactus-shell support interactive shell ([#1460](https://github.com/pactus-project/pactus/pull/1460)) ### Fix - **gtk**: increase window width to show availability score ([#1529](https://github.com/pactus-project/pactus/pull/1529)) - **state**: set hard-fork height for the mainnet ([#1528](https://github.com/pactus-project/pactus/pull/1528)) - **wallet**: change to prompt password for masking ([#1527](https://github.com/pactus-project/pactus/pull/1527)) - **deps**: go version docker image to build go v1.23.2 ([#1522](https://github.com/pactus-project/pactus/pull/1522)) - **network**: close stream on timeout ([#1520](https://github.com/pactus-project/pactus/pull/1520)) - **http**: add pprof link in http web interface ([#1518](https://github.com/pactus-project/pactus/pull/1518)) - **sync**: close stream on read error ([#1519](https://github.com/pactus-project/pactus/pull/1519)) - **sync**: set last support version to 1.5.0 ([#1517](https://github.com/pactus-project/pactus/pull/1517)) - **http**: pprof in http server ([#1515](https://github.com/pactus-project/pactus/pull/1515)) - **cmd**: add flag debug to enable pprof ([#1512](https://github.com/pactus-project/pactus/pull/1512)) - **cmd**: add pprof as default in http server ([#1511](https://github.com/pactus-project/pactus/pull/1511)) - **grpc**: merge raw transaction methods to one rpc method ([#1500](https://github.com/pactus-project/pactus/pull/1500)) - **wallet, cmd**: adding ed25519_account in help and set as default ([#1485](https://github.com/pactus-project/pactus/pull/1485)) - **wallet**: add memo in confirmation wallet CLI ([#1499](https://github.com/pactus-project/pactus/pull/1499)) - **store**: cache Ed25519 Public Keys ([#1495](https://github.com/pactus-project/pactus/pull/1495)) - **grpc**: adding pyi files for python generated files ([#1479](https://github.com/pactus-project/pactus/pull/1479)) - **grpc**: change enum type to numeric for documentation ([#1474](https://github.com/pactus-project/pactus/pull/1474)) - **shell**: stop showing usage on error ([#1467](https://github.com/pactus-project/pactus/pull/1467)) - **util**: chunked download to improve download speed ([#1459](https://github.com/pactus-project/pactus/pull/1459)) - **gtk**: width size of listbox and download button ([#1434](https://github.com/pactus-project/pactus/pull/1434)) - **grpc**: add example json-rpc in generated doc ([#1461](https://github.com/pactus-project/pactus/pull/1461)) - **grpc**: add basic check for grpc configuration to check basic auth ([#1455](https://github.com/pactus-project/pactus/pull/1455)) - **util**: remove util.Now helper function ([#1442](https://github.com/pactus-project/pactus/pull/1442)) ### Refactor - **crypto**: replace bls12-381 kilic with gnark ([#1510](https://github.com/pactus-project/pactus/pull/1510)) - **crypto**: define errors for crypto package ([#1507](https://github.com/pactus-project/pactus/pull/1507)) - **sync**: define errors for sync package ([#1504](https://github.com/pactus-project/pactus/pull/1504)) - **types**: define errors for vote package ([#1503](https://github.com/pactus-project/pactus/pull/1503)) - **state**: define errors for state package ([#1457](https://github.com/pactus-project/pactus/pull/1457)) - **util**: remove GenericError code ([#1454](https://github.com/pactus-project/pactus/pull/1454)) - **types**: using options pattern for memo parameter on new tx functions ([#1443](https://github.com/pactus-project/pactus/pull/1443)) ## [1.4.0](https://github.com/pactus-project/pactus/compare/v1.3.0...v1.4.0) (2024-08-01) ### Feat - **cmd**: add node type page to the startup assistant ([#1431](https://github.com/pactus-project/pactus/pull/1431)) - **grpc**: adding is-pruned and pruning-height to blockchain info API ([#1420](https://github.com/pactus-project/pactus/pull/1420)) - **daemon**: add import command to download pruned snapshots ([#1424](https://github.com/pactus-project/pactus/pull/1424)) - **util**: file downloader with verify sha256 hash ([#1422](https://github.com/pactus-project/pactus/pull/1422)) - **sync**: define full and prune service ([#1412](https://github.com/pactus-project/pactus/pull/1412)) - **pip**: implement PIP-23 ([#1397](https://github.com/pactus-project/pactus/pull/1397)) - **firewall**: check valid gossip and stream messages ([#1402](https://github.com/pactus-project/pactus/pull/1402)) - **state**: prune block on commit ([#1404](https://github.com/pactus-project/pactus/pull/1404)) - **core**: pruning client by prune command ([#1400](https://github.com/pactus-project/pactus/pull/1400)) - **store**: prune block function ([#1399](https://github.com/pactus-project/pactus/pull/1399)) - **wallet**: add timeout client connection ([#1396](https://github.com/pactus-project/pactus/pull/1396)) - add backup tool script ([#1373](https://github.com/pactus-project/pactus/pull/1373)) ### Fix - **consensus**: handle query for decided proposal ([#1438](https://github.com/pactus-project/pactus/pull/1438)) - **gtk**: solve dynamic library dependencies and import path on macOS ([#1435](https://github.com/pactus-project/pactus/pull/1435)) - **cmd**: prevent sudden crash on download error ([#1432](https://github.com/pactus-project/pactus/pull/1432)) - **store**: pruning height returns zero when store is not in prune mode ([#1430](https://github.com/pactus-project/pactus/pull/1430)) - **grpc**: add last-block-time to blockchain-info API ([#1428](https://github.com/pactus-project/pactus/pull/1428)) - **grpc**: show negative pruning height when is pruned false ([#1429](https://github.com/pactus-project/pactus/pull/1429)) - **sync**: fix syncing issue on prune mode ([#1415](https://github.com/pactus-project/pactus/pull/1415)) - **grpc**: return error on invalid arguments for VerifyMessage ([#1411](https://github.com/pactus-project/pactus/pull/1411)) - **network**: accept messages originating from self ([#1408](https://github.com/pactus-project/pactus/pull/1408)) - change wallet rpc ip to dns address ([#1398](https://github.com/pactus-project/pactus/pull/1398)) - **pactus-shell**: pactus shell support basic auth ([#1384](https://github.com/pactus-project/pactus/pull/1384)) - **gui**: support ctrl+c for interrupt gui ([#1385](https://github.com/pactus-project/pactus/pull/1385)) - **grpc**: add basic auth in swagger header ([#1383](https://github.com/pactus-project/pactus/pull/1383)) ### Refactor - **execution**: simplify executors and tests ([#1425](https://github.com/pactus-project/pactus/pull/1425)) ## [1.3.0](https://github.com/pactus-project/pactus/compare/v1.2.0...v1.3.0) (2024-06-27) ### Feat - **grpc**: get txpool content API ([#1364](https://github.com/pactus-project/pactus/pull/1364)) - **network**: permanent peer store ([#1354](https://github.com/pactus-project/pactus/pull/1354)) ### Fix - **grpc**: change bytes type to hex string ([#1371](https://github.com/pactus-project/pactus/pull/1371)) - **http**: add basic auth middleware for http server ([#1372](https://github.com/pactus-project/pactus/pull/1372)) - **network**: use goroutines for sending streams ([#1365](https://github.com/pactus-project/pactus/pull/1365)) ## [1.2.0](https://github.com/pactus-project/pactus/compare/v1.1.0...v1.2.0) (2024-06-20) ### Feat - **config**: make minimum fee configurable ([#1349](https://github.com/pactus-project/pactus/pull/1349)) - apply rate limit for the network topics ([#1332](https://github.com/pactus-project/pactus/pull/1332)) - add ipblocker package ([#1323](https://github.com/pactus-project/pactus/pull/1323)) - **consensus**: fast consensus path implementation ([#1253](https://github.com/pactus-project/pactus/pull/1253)) - **version**: add alias to node version ([#1281](https://github.com/pactus-project/pactus/pull/1281)) - **ntp**: add ntp util ([#1274](https://github.com/pactus-project/pactus/pull/1274)) - **gRPC**: add connection info to node info ([#1273](https://github.com/pactus-project/pactus/pull/1273)) - **gRPC**: add only_connected parameter to getNetworkInfo API ([#1264](https://github.com/pactus-project/pactus/pull/1264)) - **grpc**: refactor CreateWallet and add RestoreWallet API endpoint ([#1256](https://github.com/pactus-project/pactus/pull/1256)) - add wallet service ([#1241](https://github.com/pactus-project/pactus/pull/1241)) - ban attacker validators ([#1235](https://github.com/pactus-project/pactus/pull/1235)) - **txpool**: prevent spamming transactions by defining a minimum value ([#1233](https://github.com/pactus-project/pactus/pull/1233)) - reject direct message from non-supporting agents ([#1225](https://github.com/pactus-project/pactus/pull/1225)) ### Fix - **wallet**: add public key on get new address ([#1350](https://github.com/pactus-project/pactus/pull/1350)) - **sync**: add IsBannedAddress check in processing connect event ([#1347](https://github.com/pactus-project/pactus/pull/1347)) - **sync**: update latest supporting version ([#1336](https://github.com/pactus-project/pactus/pull/1336)) - **state**: improve node startup by optimizing availability score calculation ([#1338](https://github.com/pactus-project/pactus/pull/1338)) - **HTTP**: add clock offset and connection info to node-info API ([#1334](https://github.com/pactus-project/pactus/pull/1334)) - **grpc**: add stacktrace to locate panic ([#1333](https://github.com/pactus-project/pactus/pull/1333)) - **consensus**: implement PIP-26 ([#1331](https://github.com/pactus-project/pactus/pull/1331)) - **grpc**: improve grpc server and client ([#1330](https://github.com/pactus-project/pactus/pull/1330)) - **util**: add more ntp pool ([#1328](https://github.com/pactus-project/pactus/pull/1328)) - **jsonrpc**: update JSON-RPC Gateway to support headers and improve client registry ([#1327](https://github.com/pactus-project/pactus/pull/1327)) - **consensus**: improve consensus alghorithm ([#1329](https://github.com/pactus-project/pactus/pull/1329)) - **txpool**: set fix fee of 0.1 PAC for transactions ([#1320](https://github.com/pactus-project/pactus/pull/1320)) - **network**: add block and transaction topics ([#1319](https://github.com/pactus-project/pactus/pull/1319)) - **gRPC**: prevent concurrent map iteration and map write ([#1279](https://github.com/pactus-project/pactus/pull/1279)) - **api**: add swagger schemes ([#1270](https://github.com/pactus-project/pactus/pull/1270)) - **network**: set infinite limit for resource manager ([#1261](https://github.com/pactus-project/pactus/pull/1261)) - **sync**: introduce session manager ([#1257](https://github.com/pactus-project/pactus/pull/1257)) - **HTTP**: using amount type for fee in transaction details ([#1255](https://github.com/pactus-project/pactus/pull/1255)) - **network**: disconnect from peers that has no protocol ([#1243](https://github.com/pactus-project/pactus/pull/1243)) - **wallet**: saving wallet file after generating new address in gRPC ([#1236](https://github.com/pactus-project/pactus/pull/1236)) - prevent zero stake for bond transactions ([#1227](https://github.com/pactus-project/pactus/pull/1227)) - set bounding interval for first boudning tx only ([#1224](https://github.com/pactus-project/pactus/pull/1224)) ### Refactor - **wallet**: set server address on loading wallet ([#1348](https://github.com/pactus-project/pactus/pull/1348)) - removed deprecated LockWallet and UnLockWallet from WalletService ([#1343](https://github.com/pactus-project/pactus/pull/1343)) - **crypto**: decode data to point on verification ([#1339](https://github.com/pactus-project/pactus/pull/1339)) - **network**: define connection info in network proto ([#1297](https://github.com/pactus-project/pactus/pull/1297)) - **sync**: define peer package ([#1271](https://github.com/pactus-project/pactus/pull/1271)) - **network**: refactor peer manager and redefine the min cons ([#1259](https://github.com/pactus-project/pactus/pull/1259)) ## [1.1.0](https://github.com/pactus-project/pactus/compare/v1.0.0...v1.1.0) (2024-04-14) ### Feat - **gRPC**: add get address history method ([#1206](https://github.com/pactus-project/pactus/pull/1206)) - **grpc**: Add GetNewAddress/GetTotalBalance endpoint to gateway ([#1197](https://github.com/pactus-project/pactus/pull/1197)) - **GUI**: adding total balance to wallet widget ([#1194](https://github.com/pactus-project/pactus/pull/1194)) - Add GetNewAddress gRPC API ([#1193](https://github.com/pactus-project/pactus/pull/1193)) - **gRPC**: add new API to get the total balance of wallet ([#1190](https://github.com/pactus-project/pactus/pull/1190)) - **GUI**: showing transaction hash after broadcasting transaction ([#1187](https://github.com/pactus-project/pactus/pull/1187)) - add jsonrpc gateway support ([#1183](https://github.com/pactus-project/pactus/pull/1183)) - **config**: one reward address in config for all validators ([#1178](https://github.com/pactus-project/pactus/pull/1178)) - **GUI**: memo field for transactions on GUI wallet ([#1182](https://github.com/pactus-project/pactus/pull/1182)) - implement basic auth for pactus shell ([#1177](https://github.com/pactus-project/pactus/pull/1177)) - **grpc**: add rust code gen for proto ([#1151](https://github.com/pactus-project/pactus/pull/1151)) - **testnet**: define permanent Testent genesis ([#1173](https://github.com/pactus-project/pactus/pull/1173)) - add basic auth authentication for securing grpc ([#1162](https://github.com/pactus-project/pactus/pull/1162)) - **grpc**: calculate fee for create-raw-transaction APIs ([#1159](https://github.com/pactus-project/pactus/pull/1159)) - **grpc**: add fixed-amount to calc-fee API ([#1146](https://github.com/pactus-project/pactus/pull/1146)) - **wallet**: adding all account address functions ([#1128](https://github.com/pactus-project/pactus/pull/1128)) - **grpc**: update swagger API to version 1.1 ([#1106](https://github.com/pactus-project/pactus/pull/1106)) - **GUI**: adding availability score in wallet ([#1118](https://github.com/pactus-project/pactus/pull/1118)) - **logger**: adding log target ([#1122](https://github.com/pactus-project/pactus/pull/1122)) - **logger**: adding file_only option ([#1117](https://github.com/pactus-project/pactus/pull/1117)) - **gui**: add connections and moniker fields to main windows ([#1090](https://github.com/pactus-project/pactus/pull/1090)) - implementation for PIP-22 ([#1067](https://github.com/pactus-project/pactus/pull/1067)) - generate documentation for proto files ([#1064](https://github.com/pactus-project/pactus/pull/1064)) - pactus-ctl ([#946](https://github.com/pactus-project/pactus/pull/946)) ### Fix - **cmd**: ignore error on balance query ([#1220](https://github.com/pactus-project/pactus/pull/1220)) - **gRPC**: add basic auth option in header ([#1217](https://github.com/pactus-project/pactus/pull/1217)) - **gRPC**: not return block data on information verbosity ([#1212](https://github.com/pactus-project/pactus/pull/1212)) - **wallet**: fix wallet conn issue ([#1211](https://github.com/pactus-project/pactus/pull/1211)) - **GUI**: update total balance on wallet timeout ([#1204](https://github.com/pactus-project/pactus/pull/1204)) - accept small bond to existing validator ([#1152](https://github.com/pactus-project/pactus/pull/1152)) - **GUI**: make transaction hash selactable ([#1196](https://github.com/pactus-project/pactus/pull/1196)) - close connections with peers that have no supported protocol ([#1181](https://github.com/pactus-project/pactus/pull/1181)) - **sync**: check the start block request height ([#1176](https://github.com/pactus-project/pactus/pull/1176)) - **config**: load logger levels in Mainnet config ([#1168](https://github.com/pactus-project/pactus/pull/1168)) - **gRPC**: pactus swagger not found ([#1163](https://github.com/pactus-project/pactus/pull/1163)) - add error type for invalid configs ([#1153](https://github.com/pactus-project/pactus/pull/1153)) - save Mainnet config with inline comments ([#1143](https://github.com/pactus-project/pactus/pull/1143)) - **network**: set deadline for streams ([#1149](https://github.com/pactus-project/pactus/pull/1149)) - **grpc**: fix error 404 on grpc gateway ([#1144](https://github.com/pactus-project/pactus/pull/1144)) - **wallet**: checking args in history add ([#1141](https://github.com/pactus-project/pactus/pull/1141)) - **gRPC**: adding sign raw transaction API to gateway ([#1116](https://github.com/pactus-project/pactus/pull/1116)) - **sync**: fix concurrent map read-write crash ([#1112](https://github.com/pactus-project/pactus/pull/1112)) - **network**: remove disconnected peers from peerMgr ([#1110](https://github.com/pactus-project/pactus/pull/1110)) - **network**: set dial and accept limit in connection gater ([#1089](https://github.com/pactus-project/pactus/pull/1089)) - stderr logger in windows os ([#1081](https://github.com/pactus-project/pactus/pull/1081)) - **sync**: improve syncing process ([#1087](https://github.com/pactus-project/pactus/pull/1087)) - **network**: redefine resource limits ([#1086](https://github.com/pactus-project/pactus/pull/1086)) ### Refactor - **sync**: improve syncing process ([#1207](https://github.com/pactus-project/pactus/pull/1207)) - move fee calculation logic to execution package ([#1195](https://github.com/pactus-project/pactus/pull/1195)) - introduce Amount data type for converting PAC units ([#1174](https://github.com/pactus-project/pactus/pull/1174)) - using PAC instead of atomic units for external input/outputs ([#1161](https://github.com/pactus-project/pactus/pull/1161)) - change func() to cancel func type ([#1142](https://github.com/pactus-project/pactus/pull/1142)) ## [1.0.0](https://github.com/pactus-project/pactus/compare/v0.20.0...v1.0.0) (2024-01-31) ### Feat - implement get validator address for grpc ([#975](https://github.com/pactus-project/pactus/pull/975)) - add bootstrap.json and load in config on build ([#964](https://github.com/pactus-project/pactus/pull/964)) - add mainnet config and genesis files ([#951](https://github.com/pactus-project/pactus/pull/951)) - add Consensus-address to network info ([#952](https://github.com/pactus-project/pactus/pull/952)) - **grpc**: sign transaction using wallet client ([#945](https://github.com/pactus-project/pactus/pull/945)) - pactus gui lock support ([#947](https://github.com/pactus-project/pactus/pull/947)) - **consensus**: turning consensus to a zero-config module ([#942](https://github.com/pactus-project/pactus/pull/942)) ### Fix - localnet wallet issue ([#970](https://github.com/pactus-project/pactus/pull/970)) - **sync**: remove ReachabilityStatus from agent info ([#956](https://github.com/pactus-project/pactus/pull/956)) - **daemon**: keeping previous behavior for password flag, linting CLI messages ([#950](https://github.com/pactus-project/pactus/pull/950)) - **consensus**: detect if the system time is behind the network ([#939](https://github.com/pactus-project/pactus/pull/939)) ## [0.20.0](https://github.com/pactus-project/pactus/compare/v0.19.0...v0.20.0) (2024-01-11) ### Feat - implement relay service ([#931](https://github.com/pactus-project/pactus/pull/931)) - **HTTP**: Integrate AddRowDouble and update tests ([#926](https://github.com/pactus-project/pactus/pull/926)) - **network**: making listen address private in config ([#921](https://github.com/pactus-project/pactus/pull/921)) - **http**: adding AvailabilityScore to http module ([#917](https://github.com/pactus-project/pactus/pull/917)) - **network**: adding 'enable_udp' config ([#918](https://github.com/pactus-project/pactus/pull/918)) - **network**: removing gossip node service ([#916](https://github.com/pactus-project/pactus/pull/916)) - **gRPC**: adding AvailabilityScore to gRPC ([#910](https://github.com/pactus-project/pactus/pull/910)) - **GUI**: unbond and withdraw transaction dialogs ([#908](https://github.com/pactus-project/pactus/pull/908)) ### Fix - **gRPC**: adding missing get raw transaction APIs to gRPC gateway ([#925](https://github.com/pactus-project/pactus/pull/925)) - **network**: preventing self dial ([#924](https://github.com/pactus-project/pactus/pull/924)) - fixing time lag on starting node ([#923](https://github.com/pactus-project/pactus/pull/923)) - **network**: fixing network deadlock on linux arm64 ([#922](https://github.com/pactus-project/pactus/pull/922)) - **GUI**: updating unbond and withdraw dialogs ([#911](https://github.com/pactus-project/pactus/pull/911)) - fixing gRPC node info issue ([#906](https://github.com/pactus-project/pactus/pull/906)) ## [0.19.0](https://github.com/pactus-project/pactus/compare/v0.18.0...v0.19.0) (2024-01-04) ### Feat - **gRPC**: defining network and peers info response's properly ([#898](https://github.com/pactus-project/pactus/pull/898)) - implementing pip-19 ([#899](https://github.com/pactus-project/pactus/pull/899)) - **network**: disabling GosipSub, only FloodSub ([#895](https://github.com/pactus-project/pactus/pull/895)) - **www**: adding change proposer round and value to consensus info votes ([#892](https://github.com/pactus-project/pactus/pull/892)) - **network**: adding relay service to dial relay nodes ([#887](https://github.com/pactus-project/pactus/pull/887)) - implementing pip-15 ([#843](https://github.com/pactus-project/pactus/pull/843)) - check already running by lock file ([#871](https://github.com/pactus-project/pactus/pull/871)) ### Fix - **store**: use cache to check if public key exists ([#902](https://github.com/pactus-project/pactus/pull/902)) - **executor**: not rejecting bond transaction for bootstrap validator ([#901](https://github.com/pactus-project/pactus/pull/901)) - **GUI**: removing unnecessary tags in transaction confirm dialog ([#893](https://github.com/pactus-project/pactus/pull/893)) - **network**: close relay connection for public node ([#891](https://github.com/pactus-project/pactus/pull/891)) - **network**: refining GossipSubParams for Gossiper node ([#882](https://github.com/pactus-project/pactus/pull/882)) - **sync**: adding sequence number to the bundle ([#881](https://github.com/pactus-project/pactus/pull/881)) - **network**: turn off mesh for gossiper node ([#880](https://github.com/pactus-project/pactus/pull/880)) - **consensus**: check voteset for CP strong termination ([#879](https://github.com/pactus-project/pactus/pull/879)) - adding querier to query messages ([#878](https://github.com/pactus-project/pactus/pull/878)) - **execution**: fixing issue #869 ([#870](https://github.com/pactus-project/pactus/pull/870)) - fixing logger issue on rotating log file ([#859](https://github.com/pactus-project/pactus/pull/859)) ## [0.18.0](https://github.com/pactus-project/pactus/compare/v0.17.0...v0.18.0) (2023-12-11) ### Feat - implement pip-14 ([#841](https://github.com/pactus-project/pactus/pull/841)) - sort wallet addresses ([#836](https://github.com/pactus-project/pactus/pull/836)) - **grpc**: endpoints for creating raw transaction ([#838](https://github.com/pactus-project/pactus/pull/838)) - network reachability API ([#834](https://github.com/pactus-project/pactus/pull/834)) - implement pip-13 ([#835](https://github.com/pactus-project/pactus/pull/835)) - subscribing to libp2p eventbus ([#831](https://github.com/pactus-project/pactus/pull/831)) - implement helper methods for wallet address path ([#830](https://github.com/pactus-project/pactus/pull/830)) - **logger**: adding rotate log file after days, compress and max backups for logger config ([#822](https://github.com/pactus-project/pactus/pull/822)) - enable bandwidth router metric ([#819](https://github.com/pactus-project/pactus/pull/819)) ### Fix - **network**: refining the connection limit ([#849](https://github.com/pactus-project/pactus/pull/849)) - corrected mistake when retrieving the reward address ([#848](https://github.com/pactus-project/pactus/pull/848)) - **config**: restore default config when it is deleted ([#847](https://github.com/pactus-project/pactus/pull/847)) - **cmd**: changing home directory for root users ([#846](https://github.com/pactus-project/pactus/pull/846)) - removing BasicCheck for hash ([#845](https://github.com/pactus-project/pactus/pull/845)) - disabling libp2p ping protocol ([#844](https://github.com/pactus-project/pactus/pull/844)) - build docker file ([#839](https://github.com/pactus-project/pactus/pull/839)) - **sync**: ignore publishing a block if it is received before ([#829](https://github.com/pactus-project/pactus/pull/829)) - **network**: subscribing to the Libp2p event bus ([#828](https://github.com/pactus-project/pactus/pull/828)) - **sync**: ignore block request if blocks are already inside the cache ([#817](https://github.com/pactus-project/pactus/pull/817)) ## [0.17.0](https://github.com/pactus-project/pactus/compare/v0.16.0...v0.17.0) (2023-11-12) ### Feat - **network**: default configs for bootstrap and relay peers ([#812](https://github.com/pactus-project/pactus/pull/812)) - introducing node gossip type ([#811](https://github.com/pactus-project/pactus/pull/811)) - **sync**: adding remote address to the peer info ([#804](https://github.com/pactus-project/pactus/pull/804)) - **network**: adding public address to factory ([#795](https://github.com/pactus-project/pactus/pull/795)) - **network**: filter private ips ([#793](https://github.com/pactus-project/pactus/pull/793)) ### Fix - upgrading Testnet ([#814](https://github.com/pactus-project/pactus/pull/814)) - **sync**: prevent opening sessions indefinitely ([#813](https://github.com/pactus-project/pactus/pull/813)) - **execution**: fixing mistake on calculating unbonded power ([#806](https://github.com/pactus-project/pactus/pull/806)) - **network**: check connection threshold on gater ([#803](https://github.com/pactus-project/pactus/pull/803)) - **network**: no transient connection ([#799](https://github.com/pactus-project/pactus/pull/799)) - not close connection for bootstrap nodes ([#792](https://github.com/pactus-project/pactus/pull/792)) ### Refactor - **sync**: refactoring sync process ([#807](https://github.com/pactus-project/pactus/pull/807)) ## [0.16.0](https://github.com/pactus-project/pactus/compare/v0.15.0...v0.16.0) (2023-10-29) ### Feat - **gui**: display network ID ([#780](https://github.com/pactus-project/pactus/pull/780)) - create new validator address (CLI and GUI) ([#757](https://github.com/pactus-project/pactus/pull/757)) - add community bootstrap nodes to testnet config ([#764](https://github.com/pactus-project/pactus/pull/764)) - **network**: implementing connection manager ([#773](https://github.com/pactus-project/pactus/pull/773)) - **network**: adding bootstrapper mode to the network config ([#760](https://github.com/pactus-project/pactus/pull/760)) ### Fix - **network**: redefine the network limits ([#788](https://github.com/pactus-project/pactus/pull/788)) - **consensus**: not increase the vote-box power on duplicated votes ([#785](https://github.com/pactus-project/pactus/pull/785)) - **network**: close connection when unbale to get supported protocols ([#781](https://github.com/pactus-project/pactus/pull/781)) - **network**: enabling peer exchange for bootstrappers ([#779](https://github.com/pactus-project/pactus/pull/779)) - **network**: set connection limit for the resource manager ([#775](https://github.com/pactus-project/pactus/pull/775)) - **sync**: peer status set to known on sucessfull handshaking ([#774](https://github.com/pactus-project/pactus/pull/774)) - **consensus**: strong termination for the binary agreement ([#765](https://github.com/pactus-project/pactus/pull/765)) - **consensus**: not increase the voting power on duplicated binary votes ([#762](https://github.com/pactus-project/pactus/pull/762)) ### Refactor - **network**: refactoring peer manager ([#787](https://github.com/pactus-project/pactus/pull/787)) ## [0.15.0](https://github.com/pactus-project/pactus/compare/v0.13.0...v0.15.0) (2023-10-15) ### Feat - **gui**: adding the splash screen ([#743](https://github.com/pactus-project/pactus/pull/743)) - add absentees votes to the certificate ([#746](https://github.com/pactus-project/pactus/pull/746)) - **logger**: short stringer for loggers ([#732](https://github.com/pactus-project/pactus/pull/732)) - implementing pip-7 ([#731](https://github.com/pactus-project/pactus/pull/731)) - implementing pip-11 ([#712](https://github.com/pactus-project/pactus/pull/712)) - implementing pip-8 ([#711](https://github.com/pactus-project/pactus/pull/711)) - implementing pip-9 ([#706](https://github.com/pactus-project/pactus/pull/706)) - new API to get Public key by address ([#704](https://github.com/pactus-project/pactus/pull/704)) - Adding address field for AccountInfo ([#703](https://github.com/pactus-project/pactus/pull/703)) - CreateValidatorEvent and CreateAccountEvent for nanomsg ([#702](https://github.com/pactus-project/pactus/pull/702)) - implementing PIP-2 and PIP-3 ([#699](https://github.com/pactus-project/pactus/pull/699)) - Adding Hole Punching to network ([#697](https://github.com/pactus-project/pactus/pull/697)) - write logs into file ([#673](https://github.com/pactus-project/pactus/pull/673)) - check protocol support before sending connect/disconnect event ([#683](https://github.com/pactus-project/pactus/pull/683)) - updating genesis for pre-testnet-2 ([#679](https://github.com/pactus-project/pactus/pull/679)) - adding udp protocol for network ([#672](https://github.com/pactus-project/pactus/pull/672)) - implementing pip-4 ([#671](https://github.com/pactus-project/pactus/pull/671)) - Notifee service events ([#628](https://github.com/pactus-project/pactus/pull/628)) - adding MinimumStake parameter ([#574](https://github.com/pactus-project/pactus/pull/574)) - adding Sent and Received bytes per message metrics for peers ([#618](https://github.com/pactus-project/pactus/pull/618)) - add reason to BlockResponse messages ([#607](https://github.com/pactus-project/pactus/pull/607)) - Add CalcualteFee in GRPC ([#601](https://github.com/pactus-project/pactus/pull/601)) - add sent bytes and received bytes metrics to peerset plus update grpc ([#606](https://github.com/pactus-project/pactus/pull/606)) - added metrics of libp2p with supporting prometheus ([#588](https://github.com/pactus-project/pactus/pull/588)) - Check node address is valid ([#565](https://github.com/pactus-project/pactus/pull/565)) - add LastSent and LastReceived properties to peer ([#569](https://github.com/pactus-project/pactus/pull/569)) ### Fix - data race issue on updating certificate ([#747](https://github.com/pactus-project/pactus/pull/747)) - **network**: async connection ([#744](https://github.com/pactus-project/pactus/pull/744)) - adding query vote timer for CP phase ([#738](https://github.com/pactus-project/pactus/pull/738)) - trim transactions in proposed block ([#737](https://github.com/pactus-project/pactus/pull/737)) - fixing query votes and proposal issue ([#736](https://github.com/pactus-project/pactus/pull/736)) - fixing issue when a block has max transactions ([#735](https://github.com/pactus-project/pactus/pull/735)) - **consensus**: anti-entroy mechanism for the consensus ([#734](https://github.com/pactus-project/pactus/pull/734)) - **logger**: invalid level parsing error ([#733](https://github.com/pactus-project/pactus/pull/733)) - cache certificate by height ([#730](https://github.com/pactus-project/pactus/pull/730)) - fixing a crash on consensus ([#729](https://github.com/pactus-project/pactus/pull/729)) - **consensus**: prevent double entry in new height ([#728](https://github.com/pactus-project/pactus/pull/728)) - resolve consensus halt caused by time discrepancy in network. ([#727](https://github.com/pactus-project/pactus/pull/727)) - unsorted addresses in wallet listing ([#721](https://github.com/pactus-project/pactus/pull/721)) - send query votes message, if there is no proposal yet ([#723](https://github.com/pactus-project/pactus/pull/723)) - fixing logger level issue ([#722](https://github.com/pactus-project/pactus/pull/722)) - fixing syncing stuck issue ([#720](https://github.com/pactus-project/pactus/pull/720)) - fixing some minor issues on pre-testnet ([#719](https://github.com/pactus-project/pactus/pull/719)) - supporting go version 1.21 and higher ([#692](https://github.com/pactus-project/pactus/pull/692)) - ensure log rotation using tests ([#693](https://github.com/pactus-project/pactus/pull/693)) - restoring at the first block ([#691](https://github.com/pactus-project/pactus/pull/691)) - swagger doesn't work with multiple proto files ([#687](https://github.com/pactus-project/pactus/pull/687)) - fixing wallet-cli issues ([#686](https://github.com/pactus-project/pactus/pull/686)) - prevent stripping public key for subsidy transactions ([#678](https://github.com/pactus-project/pactus/pull/678)) - updating the consensus protocol ([#668](https://github.com/pactus-project/pactus/pull/668)) - aggregating signature for hello message ([#640](https://github.com/pactus-project/pactus/pull/640)) - error case for logger ([#634](https://github.com/pactus-project/pactus/pull/634)) - adding committers to the certificate ([#623](https://github.com/pactus-project/pactus/pull/623)) - updating sortition executor ([#608](https://github.com/pactus-project/pactus/pull/608)) - update buf and fixing proto generation issue ([#600](https://github.com/pactus-project/pactus/pull/600)) - adding block hash to peer ([#584](https://github.com/pactus-project/pactus/pull/584)) - copy to clipboard option for address and pubkey ([#583](https://github.com/pactus-project/pactus/pull/583)) - public key aggregate ([#576](https://github.com/pactus-project/pactus/pull/576)) - remove GetValidators rpc method ([#573](https://github.com/pactus-project/pactus/pull/573)) - missing swagger ui for grpc get account by number ([#564](https://github.com/pactus-project/pactus/pull/564)) - incorrect handler for validator by number ([#563](https://github.com/pactus-project/pactus/pull/563)) ### Refactor - **sync**: refactoring syncing process ([#676](https://github.com/pactus-project/pactus/pull/676)) - remove payload prefix from payload transaction type ([#669](https://github.com/pactus-project/pactus/pull/669)) - change Hello message from broadcasting to direct messaging ([#665](https://github.com/pactus-project/pactus/pull/665)) - **committee**: using generic list for validators ([#667](https://github.com/pactus-project/pactus/pull/667)) - rename SanityCheck to BasicCheck ([#643](https://github.com/pactus-project/pactus/pull/643)) - **cli**: Migrating from mow.cli to cobra for wallet ([#629](https://github.com/pactus-project/pactus/pull/629)) - **cli**: replacing mow.cli with cobra for daemon ([#621](https://github.com/pactus-project/pactus/pull/621)) - **logger**: using fast JSON logger (zerolog) ([#613](https://github.com/pactus-project/pactus/pull/613)) - Using Generics for calculating Min and Max for numeric type #604 ([#609](https://github.com/pactus-project/pactus/pull/609)) - Updating LRU cache to version 2 #514 ([#602](https://github.com/pactus-project/pactus/pull/602)) ## [0.13.0](https://github.com/pactus-project/pactus/compare/v0.12.0...v0.13.0) (2023-06-30) ### Fix - implemented restore wallet base on input seed ([#553](https://github.com/pactus-project/pactus/pull/553)) - measuring total sent and received bytes ([#552](https://github.com/pactus-project/pactus/pull/552)) - add validate seed and restore wallet ([#533](https://github.com/pactus-project/pactus/pull/533)) - **HTTP**: Missing handlers ([#549](https://github.com/pactus-project/pactus/pull/549)) - **gui**: update about dialog and menu items in help ([#532](https://github.com/pactus-project/pactus/pull/532)) ### Refactor - implementing TestSuite ([#535](https://github.com/pactus-project/pactus/pull/535)) ## [0.12.0](https://github.com/pactus-project/pactus/compare/v0.11.0...v0.12.0) (2023-06-19) ### Feat - add GetAccountByNumber API to get account by number ([#511](https://github.com/pactus-project/pactus/pull/511)) ### Fix - caching account and validator in store ([#513](https://github.com/pactus-project/pactus/pull/513)) - get recent blocks by stamp ([#509](https://github.com/pactus-project/pactus/pull/509)) - closing the mDNS connection upon stopping the network ([#508](https://github.com/pactus-project/pactus/pull/508)) - updating linkedmap to use generic ([#507](https://github.com/pactus-project/pactus/pull/507)) - removing state from cache ([#506](https://github.com/pactus-project/pactus/pull/506)) - Typo in GUI ([#499](https://github.com/pactus-project/pactus/pull/499)) - supporting localnet ([#492](https://github.com/pactus-project/pactus/pull/492)) ### Refactor - update total power calculation based on power change(deltas) ([#518](https://github.com/pactus-project/pactus/pull/518)) - GetValidators return all validators in state validators map ([#512](https://github.com/pactus-project/pactus/pull/512)) ## [0.11.0](https://github.com/pactus-project/pactus/compare/v0.10.0...v0.11.0) (2023-05-29) ### Fix - **gui**: showing the total number of validators ([#474](https://github.com/pactus-project/pactus/pull/474)) - **network**: fixing relay connection issue ([#475](https://github.com/pactus-project/pactus/pull/475)) - **consensus**: rejecting vote with round numbers exceeding the limit ([#466](https://github.com/pactus-project/pactus/pull/466)) - increase failed counter when stream got error ([#489](https://github.com/pactus-project/pactus/pull/489)) - boosting syncing process ([#482](https://github.com/pactus-project/pactus/pull/482)) - waiting for proposal in pre-commit phase ([#486](https://github.com/pactus-project/pactus/pull/486)) - retrieving public key from wallet for bond transactions ([#485](https://github.com/pactus-project/pactus/pull/485)) - restoring config file to the default ([#484](https://github.com/pactus-project/pactus/pull/484)) - defining ChainType in genesis to detect the type of network ([#483](https://github.com/pactus-project/pactus/pull/483)) - reducing the default Argon2d to consume less memory ([#480](https://github.com/pactus-project/pactus/pull/480)) - adding password option to the start commands ([#473](https://github.com/pactus-project/pactus/pull/473)) ### Refactor - rename send to transfer. ([#469](https://github.com/pactus-project/pactus/pull/469)) ## [0.10.0](https://github.com/pactus-project/pactus/compare/v0.9.0...v0.10.0) (2023-05-09) ### Feat - removing address from account ([#454](https://github.com/pactus-project/pactus/pull/454)) - supporting multiple consensus instances ([#450](https://github.com/pactus-project/pactus/pull/450)) - adding sortition interval to the parameters ([#442](https://github.com/pactus-project/pactus/pull/442)) ### Fix - `GetBlockchainInfo` API in gRPC now returns the total number of validators and accounts - **gui**: check if the node has an active consensus instance ([#458](https://github.com/pactus-project/pactus/pull/458)) - wallet path as argument ([#455](https://github.com/pactus-project/pactus/pull/455)) - adding reward addresses to config ([#453](https://github.com/pactus-project/pactus/pull/453)) - removing committers from the certificate hash ([#444](https://github.com/pactus-project/pactus/pull/444)) - prevent data race conditions in committee ([#452](https://github.com/pactus-project/pactus/pull/452)) - using 2^256 for the vrf denominator ([#445](https://github.com/pactus-project/pactus/pull/445)) - updating tla+ readme ([#443](https://github.com/pactus-project/pactus/pull/443)) ## 0.9.0 (2022-09-05) No changelog ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Thank you for considering contributing to the Pactus blockchain! Please read these guidelines before submitting a pull request or opening an issue. ## Code Guidelines We strive to maintain clean, readable, and maintainable code in the Pactus blockchain. Please follow these guidelines when contributing to the project: - Follow the [Effective Go](https://golang.org/doc/effective_go.html) guidelines. - Follow the [Go Doc Comments](https://go.dev/doc/comment) guidelines. - Follow the principles of clean code as outlined in Robert C. Martin's "[Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)" book. - Write tests for new code or changes to existing code, and make sure all tests pass before submitting a pull request. ### Makefile Targets You can use these commands in the Makefile: - `make build` compiles the code into executable binaries. - `make build_gui` compiles the gtk GUI code into executable binary. - `make devtools` installs required development tools. - `make fmt` formats the code according to the Go standards. - `make check` runs checks on the code, including formatting and linting. - `make test` runs all the tests, including unit tests and system tests. - `make unit_test` runs only unit tests. - `make proto` generates gRPC code from [Protobuf](https://protobuf.dev/) files. - `make proto-check` validates Protobuf files against best practices. - `make proto-format` formats Protobuf files. ### GUI Development Development of the Pactus Core GUI have some requirements on your machine which you can find a [quick guide about it here](./docs/gtk-gui-development.md). ### Error and Log Messages Error and log messages should not start with a capital letter (unless it's a proper noun or acronym) and should not end with punctuation. All changes on core must contain proper and well-defined unit-tests, also previous tests must be passed as well. This codebase used `testify` for unit tests, make sure you follow these guide for tests: - For panic cases make sure you use `assert.Panics` - For checking err using `assert.ErrorIs` make sure you pass expected error as second argument. - For checking equality using `assert.Equal` make sure you pass expected value as the first argument. > This code guideline must be followed for both contributors and maintainers to review the PRs. #### Examples - Correct ✅: "unable to connect to server" - Incorrect ❌: "Unable to connect to server" - Incorrect ❌: "unable to connect to server." ### Help Messages Follow these rules for help messages for CLI commands and flags: - Help string should not start with a capital letter. - Help string should not end with punctuation. - Don't include default value in the help string. - Include the acceptable range for the flags that accept a range of values. ## Commit Guidelines Please follow these rules when committing changes to the Pactus blockchain: - Each commit should represent a single, atomic change to the codebase. Avoid making multiple unrelated changes in a single commit. - Use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format for commit messages and Pull Request titles. ### Commit type List of conventional commit [types](https://github.com/commitizen/conventional-commit-types/blob/master/index.json): | Types | Description | | -------- | --------------------------------------------------------------------------------- | | fix | A big fix | | feat | A new feature | | docs | Documentation only changes | | test | Adding missing tests or correcting existing tests | | build | Changes that affect the build system or external dependencies | | ci | Changes to our CI configuration files and scripts | | perf | A code change that improves performance | | refactor | A code change that neither fixes a bug nor adds a feature | | style | Changes that do not affect the meaning of the code (white-space, formatting, etc) | | chore | Other changes that don't modify src or test files | ### Commit Scope The scope helps specify which part of the code is affected by your commit. It must be included in the commit message to provide clarity. Multiple scopes can be used if the changes impact several areas. Here’s a list of available scopes: [available scopes](./.github/workflows/semantic-pr.yml). ### Commit Description - Keep the commit message under 50 characters. - Start the commit message with a lowercase letter and do not end with punctuation. - Write commit messages in the imperative: "fix bug" not "fixed bug" or "fixes bug". ### Examples - Correct ✅: "feat(grpc): sign transaction using wallet client" - Correct ✅: "feat(grpc, wallet): sign transaction using wallet client" - Incorrect ❌: "feat(gRPC): Sign transaction using wallet client." - Incorrect ❌: "feat(grpc): Sign transaction using wallet client." - Incorrect ❌: "feat(grpc): signed transaction using wallet client" - Incorrect ❌: "sign transaction using wallet client" ## Code of Conduct This project has adapted the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) to ensure that our community is welcoming and inclusive for all. Please read it before contributing to the project. --- Thank you for your contributions to the Pactus blockchain! ================================================ FILE: Dockerfile ================================================ FROM golang:1.26.2-alpine3.23 AS builder RUN apk add --no-cache git gmp-dev build-base g++ openssl-dev ADD . /pactus # Building pactus-daemon RUN cd /pactus && \ CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ./build/pactus-daemon ./cmd/daemon && \ CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ./build/pactus-wallet ./cmd/wallet && \ CGO_ENABLED=0 go build -ldflags "-s -w" -trimpath -o ./build/pactus-shell ./cmd/shell ## Copy binary files from builder into second container FROM alpine:3.23 COPY --from=builder /pactus/build/pactus-daemon /usr/bin COPY --from=builder /pactus/build/pactus-wallet /usr/bin COPY --from=builder /pactus/build/pactus-shell /usr/bin ENV WORKING_DIR="/pactus" VOLUME $WORKING_DIR WORKDIR $WORKING_DIR ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2020 Pactus blockchain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ PACKAGES=$(shell go list ./... | grep -v 'tests' | grep -v 'grpc/gen') ifneq (,$(filter $(OS),Windows_NT MINGW64)) EXE = .exe endif # Handle sed differences between macOS and Linux ifeq ($(shell uname),Darwin) SED_CMD = sed -i '' else SED_CMD = sed -i endif all: build test ######################################## ### Tools needed for development devtools: @echo "Installing devtools" go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.4 go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@v2.28.0 go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@v2.28.0 go install github.com/NathanBaulch/protoc-gen-cobra@v1.2.1 go install github.com/pactus-project/protoc-gen-doc/cmd/protoc-gen-doc@v0.0.0-20260124125944-b6e7c1776266 go install github.com/bufbuild/buf/cmd/buf@v1.67.0 go install mvdan.cc/gofumpt@latest go install github.com/pacviewer/jrpc-gateway/protoc-gen-jrpc-gateway@v0.6 go install go.uber.org/mock/mockgen@latest ######################################## ### Building build: go build -o ./build/pactus-daemon$(EXE) ./cmd/daemon go build -o ./build/pactus-wallet$(EXE) ./cmd/wallet go build -o ./build/pactus-shell$(EXE) ./cmd/shell build_race: go build -race -o ./build/pactus-daemon$(EXE) ./cmd/daemon go build -race -o ./build/pactus-wallet$(EXE) ./cmd/wallet build_gui: go build -tags gtk -o ./build/pactus-gui$(EXE) ./cmd/gtk ######################################## ### Testing mocks: @echo "Generating mocks..." mockgen -source=txpool/interface.go -destination=txpool/txpool_mock.go -package=txpool mockgen -source=wallet/manager/interface.go -destination=wallet/manager/manager_mock.go -package=manager mockgen -source=wallet/provider/interface.go -destination=wallet/provider/provider_mock.go -package=provider mockgen -source=wallet/storage/interface.go -destination=wallet/storage/storage_mock.go -package=storage unit_test: @go test $(PACKAGES) test: @go test ./... -covermode=atomic test_race: @go test ./... --race ######################################## ### Docker docker: docker build --tag pactus . ######################################## ### proto # This target works only on Unix-like terminals. proto: rm -rf www/grpc/gen cd www/grpc && buf generate --template ./buf/buf.gen.yaml --config ./buf/buf.yaml ./proto proto-check: cd www/grpc && buf lint --config ./buf/buf.yaml proto-format: cd www/grpc && buf format --config ./buf/buf.yaml -w ######################################## ### Formatting the code fmt: gofumpt -l -w . check: golangci-lint run --build-tags "${BUILD_TAG}" --timeout=20m0s # To avoid unintended conflicts with file names, always add to .PHONY # unless there is a reason not to. # https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html .PHONY: build build_gui .PHONY: test unit_test test_race mocks .PHONY: proto proto-format proto-check .PHONY: devtools fmt check docker ================================================ FILE: README.md ================================================ [![codecov](https://codecov.io/gh/pactus-project/pactus/branch/main/graph/badge.svg?token=8N6N60D5UI)](https://codecov.io/gh/pactus-project/pactus) [![Go Report Card](https://goreportcard.com/badge/github.com/pactus-project/pactus)](https://goreportcard.com/report/github.com/pactus-project/pactus) [![Twitter(X)](https://badgen.net/badge/icon/twitter?icon=twitter&label)](https://x.com/PactusChain) [![Discord](https://badgen.net/badge/icon/discord?icon=discord&label)](https://discord.gg/H5vZkNnXCu) ------ # Pactus Blockchain A full-node implementation of the Pactus blockchain in Go. ## Install Please check the [install](./docs/install.md) document to build and run the Pactus blockchain. ## Contribution Contributions to the Pactus blockchain are appreciated. Please read the [CONTRIBUTING](./CONTRIBUTING.md) guidelines before submitting a pull request or opening an issue. ## License The Pactus blockchain is under MIT [license](./LICENSE). ================================================ FILE: cmd/cmd.go ================================================ package cmd import ( "context" "errors" "fmt" "os" "os/user" "path/filepath" "runtime" "syscall" "time" "github.com/ezex-io/gopkg/signal" "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/node" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/types" ) const ( DefaultHomeDirName = "pactus" DefaultWalletsDirName = "wallets" DefaultWalletName = "default_wallet" ) func PactusDefaultHomeDir() string { home := "" usr, err := user.Current() if err != nil { terminal.PrintWarnMsgf("unable to get current user: %v", err) } else { home = filepath.Join(usr.HomeDir, home, DefaultHomeDirName) } return home } func PactusWalletDir(home string) string { return filepath.Join(home, "wallets") } func PactusGenesisPath(home string) string { return filepath.Join(home, "genesis.json") } func PactusConfigPath(home string) string { return filepath.Join(home, "config.toml") } func PactusLockFilePath(home string) string { return filepath.Join(home, ".pactus.lock") } func PactusDefaultWalletPath(home string) string { return filepath.Join(PactusWalletDir(home), DefaultWalletName) } func PactusDaemonName() string { if runtime.GOOS == "windows" { return "pactus-daemon.exe" } return "./pactus-daemon" } func CreateNode(ctx context.Context, numValidators int, chain genesis.ChainType, workingDir string, mnemonic string, walletPassword string, ) (*wallet.Wallet, string, error) { walletPath := PactusDefaultWalletPath(workingDir) wlt, err := wallet.Create(ctx, walletPath, mnemonic, walletPassword, chain) if err != nil { return nil, "", err } for i := 0; i < numValidators; i++ { _, err := wlt.NewAddress(crypto.AddressTypeValidator, fmt.Sprintf("Validator address %v", i+1)) if err != nil { return nil, "", err } } rewardAddrInfo, err := wlt.NewAddress(crypto.AddressTypeEd25519Account, "Reward address", wallet.WithPassword(walletPassword)) if err != nil { return nil, "", err } confPath := PactusConfigPath(workingDir) genPath := PactusGenesisPath(workingDir) switch chain { case genesis.Mainnet: genDoc := genesis.MainnetGenesis() if err := genDoc.SaveToFile(genPath); err != nil { return nil, "", err } err := config.SaveMainnetConfig(confPath) if err != nil { return nil, "", err } case genesis.Testnet: genDoc := genesis.TestnetGenesis() if err := genDoc.SaveToFile(genPath); err != nil { return nil, "", err } conf := config.DefaultConfigTestnet() if err := conf.Save(confPath); err != nil { return nil, "", err } case genesis.Localnet: if numValidators < 4 { return nil, "", errors.New("localnet needs at least 4 validators") } genDoc := makeLocalGenesis(wlt) if err := genDoc.SaveToFile(genPath); err != nil { return nil, "", err } conf := config.DefaultConfigLocalnet() if err := conf.Save(confPath); err != nil { return nil, "", err } } return wlt, rewardAddrInfo.Address, nil } // StartNode starts the node from the given working directory. // The passwordFetcher will be used to fetch the password for the default_wallet if it is encrypted. // It returns an error if the genesis doc or default_wallet can't be found inside the working directory. // TODO: write test for me. func StartNode(ctx context.Context, workingDir string, passwordFetcher func() (string, bool), configModifier func(cfg *config.Config) *config.Config, ) (*node.Node, error) { conf, gen, err := MakeConfig(workingDir) if err != nil { return nil, err } if configModifier != nil { conf = configModifier(conf) } defaultWalletPath := PactusDefaultWalletPath(workingDir) wlt, err := wallet.Open(ctx, defaultWalletPath) if err != nil { return nil, err } valList := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) if len(valList) == 0 { return nil, errors.New("no validator addresses found in the wallet") } if len(valList) > 32 { terminal.PrintWarnMsgf("wallet has more than 32 validator addresses, only the first 32 will be used") valList = valList[:32] } rewardAddrs, err := MakeRewardAddresses(wlt, valList, conf.Node.RewardAddresses) if err != nil { return nil, err } valKeys, err := MakeValidatorKey(wlt, valList, passwordFetcher) if err != nil { return nil, err } wlt.Close() node, err := node.NewNode(ctx, gen, conf, valKeys, rewardAddrs) if err != nil { return nil, err } err = node.Start() if err != nil { return nil, err } return node, nil } // makeLocalGenesis makes genesis file for the local network. func makeLocalGenesis(wlt *wallet.Wallet) *genesis.Genesis { // Treasury account acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) accs := map[crypto.Address]*account.Account{ crypto.TreasuryAddress: acc, } genValNum := 4 vals := make([]*validator.Validator, genValNum) addrs := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) for i := 0; i < genValNum; i++ { info, _ := wlt.AddressInfo(addrs[i].Address) pub, _ := bls.PublicKeyFromString(info.PublicKey) vals[i] = validator.NewValidator(pub, int32(i)) } // create genesis params := genesis.DefaultGenesisParams() params.BlockVersion = protocol.ProtocolVersionLatest gen := genesis.MakeGenesis(util.RoundNow(60), accs, vals, params) return gen } // MakeConfig attempts to load the configuration file and // returns an instance of the configuration along with the genesis document. // The genesis document is required to determine the chain type, which influences the configuration settings. // The function sets various private configurations, such as the "wallets directory" and chain-specific HRP values. // If the configuration file cannot be loaded, it tries to recover or restore the configuration. func MakeConfig(workingDir string) (*config.Config, *genesis.Genesis, error) { gen, err := genesis.LoadFromFile(PactusGenesisPath(workingDir)) if err != nil { return nil, nil, err } if !gen.ChainType().IsMainnet() { crypto.ToTestnetHRP() } walletsDir := PactusWalletDir(workingDir) confPath := PactusConfigPath(workingDir) var defConf *config.Config chainType := gen.ChainType() switch chainType { case genesis.Mainnet: defConf = config.DefaultConfigMainnet() case genesis.Testnet: defConf = config.DefaultConfigTestnet() case genesis.Localnet: defConf = config.DefaultConfigLocalnet() } conf, err := config.LoadFromFile(confPath, true, defConf) if err != nil { terminal.PrintWarnMsgf("Unable to load the config: %s", err) terminal.PrintInfoMsgf("Attempting to update or restore the config file...") conf, err = RecoverConfig(confPath, defConf, chainType) if err != nil { return nil, nil, err } } // Now we can update the private filed, if any genParams := gen.Params() conf.Store.TxCacheWindow = genParams.TransactionToLiveInterval conf.Store.SeedCacheWindow = genParams.SortitionInterval conf.Store.AccountCacheSize = 1024 conf.Store.PublicKeyCacheSize = 1024 conf.WalletManager.ChainType = chainType conf.WalletManager.WalletsDir = walletsDir if err := conf.BasicCheck(); err != nil { return nil, nil, err } return conf, gen, nil } func RecoverConfig(confPath string, defConf *config.Config, chainType genesis.ChainType) (*config.Config, error) { // Try to attempt to load config in non-strict mode conf, err := config.LoadFromFile(confPath, false, defConf) // Create a backup of the config if util.PathExists(confPath) { confBackupPath := fmt.Sprintf("%v_bak_%s", confPath, time.Now().Format("2006-01-02T15-04-05")) renameErr := os.Rename(confPath, confBackupPath) if renameErr != nil { return nil, renameErr } } if err == nil { err := conf.Save(confPath) if err != nil { return nil, err } terminal.PrintSuccessMsgf("Config updated.") } else { switch chainType { case genesis.Mainnet: err = config.SaveMainnetConfig(confPath) if err != nil { return nil, err } case genesis.Testnet, genesis.Localnet: err = defConf.Save(confPath) if err != nil { return nil, err } } terminal.PrintSuccessMsgf("Config restored to the default values") conf, _ = config.LoadFromFile(confPath, true, defConf) // This time it should be OK } return conf, err } // MakeRewardAddresses generates a list of reward addresses based on wallet and configuration. // If no reward addresses are provided in the config, // the function attempts to use Ed25519 or BLS addresses from the wallet. func MakeRewardAddresses(wlt *wallet.Wallet, valList []types.AddressInfo, confRewardAddrs []string, ) ([]crypto.Address, error) { rewardAddrs := make([]crypto.Address, 0, len(valList)) switch { // Case 1: No reward addresses in the config file. case len(confRewardAddrs) == 0: var addrInfo *types.AddressInfo // Try to use the first Ed25519 address from the wallet as the reward address. ed25519Addrs := wlt.ListAddresses(wallet.WithAddressType(crypto.AddressTypeEd25519Account)) if len(ed25519Addrs) == 0 { // If no Ed25519 address is found, try the first BLS address instead. blsAddrs := wlt.ListAddresses(wallet.WithAddressType(crypto.AddressTypeBLSAccount)) if len(blsAddrs) == 0 { return nil, errors.New("unable to find a reward address in the wallet") } addrInfo = &blsAddrs[0] } else { addrInfo = &ed25519Addrs[0] } addr, _ := crypto.AddressFromString(addrInfo.Address) for i := 0; i < len(valList); i++ { rewardAddrs = append(rewardAddrs, addr) } // Case 2: One reward address is specified in the config file. case len(confRewardAddrs) == 1: // Use this single address for all validators. addr, _ := crypto.AddressFromString(confRewardAddrs[0]) for i := 0; i < len(valList); i++ { rewardAddrs = append(rewardAddrs, addr) } // Case 3: Each validator has a corresponding reward address in the config file. case len(confRewardAddrs) == len(valList): for _, addrStr := range confRewardAddrs { addr, _ := crypto.AddressFromString(addrStr) rewardAddrs = append(rewardAddrs, addr) } default: return nil, fmt.Errorf("expected %v reward addresses, but got %v", len(valList), len(confRewardAddrs)) } return rewardAddrs, nil } func MakeValidatorKey(walletInstance *wallet.Wallet, valAddrsInfo []types.AddressInfo, passwordFetcher func() (string, bool), ) ([]*bls.ValidatorKey, error) { valAddrs := make([]string, len(valAddrsInfo)) for i := 0; i < len(valAddrs); i++ { valAddr, _ := crypto.AddressFromString(valAddrsInfo[i].Address) if !valAddr.IsValidatorAddress() { return nil, fmt.Errorf("invalid validator address: %s", valAddrsInfo[i].Address) } valAddrs[i] = valAddr.String() } valKeys := make([]*bls.ValidatorKey, len(valAddrsInfo)) walletPassword := "" if walletInstance.IsEncrypted() { password, ok := passwordFetcher() if !ok { return nil, errors.New("aborted") } walletPassword = password } prvKeys, err := walletInstance.PrivateKeys(walletPassword, valAddrs) if err != nil { return nil, err } for i, prv := range prvKeys { valKeys[i] = bls.NewValidatorKey(prv.(*bls.PrivateKey)) } return valKeys, nil } func RecoverWalletAddresses(wlt *wallet.Wallet, password string) { ctx, cancel := context.WithCancel(context.Background()) signal.HandleSignals(func(os.Signal) { cancel() }, syscall.SIGINT, syscall.SIGTERM) terminal.PrintInfoMsgf("🔄 Recovering wallet addresses...") terminal.PrintInfoMsgf(" Press 'Ctrl+C' to abort if needed") terminal.PrintLine() index := 0 err := wlt.RecoveryAddresses(ctx, password, func(addr string) { terminal.PrintInfoMsgf("%d. %s", index+1, addr) index++ }) if err != nil { if errors.Is(err, context.Canceled) { terminal.PrintWarnMsgf("Address recovery aborted") } else { terminal.PrintErrorMsgf("Address recovery failed: %v", err) } } } ================================================ FILE: cmd/cmd_test.go ================================================ package cmd import ( "runtime" "testing" "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/wallet" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMakeConfig(t *testing.T) { t.Run("No genesis file, Should return error", func(t *testing.T) { workingDir := util.TempDirPath() _, _, err := MakeConfig(workingDir) require.Error(t, err) }) t.Run("No Config file, Should recover it", func(t *testing.T) { workingDir := util.TempDirPath() genPath := PactusGenesisPath(workingDir) gen := genesis.MainnetGenesis() err := gen.SaveToFile(genPath) require.NoError(t, err) _, _, err = MakeConfig(workingDir) require.NoError(t, err) }) t.Run("Invalid Config file, Should recover it", func(t *testing.T) { workingDir := util.TempDirPath() genPath := PactusGenesisPath(workingDir) confPath := PactusConfigPath(workingDir) gen := genesis.MainnetGenesis() err := gen.SaveToFile(genPath) require.NoError(t, err) err = util.WriteFile(confPath, []byte("invalid-config")) require.NoError(t, err) _, _, err = MakeConfig(workingDir) require.NoError(t, err) }) t.Run("Everything is good", func(t *testing.T) { workingDir := util.TempDirPath() genPath := PactusGenesisPath(workingDir) confPath := PactusConfigPath(workingDir) gen := genesis.MainnetGenesis() err := gen.SaveToFile(genPath) require.NoError(t, err) err = config.SaveMainnetConfig(confPath) require.NoError(t, err) _, _, err = MakeConfig(workingDir) require.NoError(t, err) }) } func TestPathsUnix(t *testing.T) { if runtime.GOOS == "windows" { return } tests := []struct { home string expectedWalletDir string expectedDefaultWalletPath string expectedGenesisPath string expectedConfigPath string }{ { "/home/pactus", "/home/pactus/wallets", "/home/pactus/wallets/default_wallet", "/home/pactus/genesis.json", "/home/pactus/config.toml", }, { "/home/pactus/", "/home/pactus/wallets", "/home/pactus/wallets/default_wallet", "/home/pactus/genesis.json", "/home/pactus/config.toml", }, } for _, tt := range tests { walletDir := PactusWalletDir(tt.home) defaultWalletPath := PactusDefaultWalletPath(tt.home) genesisPath := PactusGenesisPath(tt.home) configPath := PactusConfigPath(tt.home) assert.Equal(t, tt.expectedWalletDir, walletDir) assert.Equal(t, tt.expectedDefaultWalletPath, defaultWalletPath) assert.Equal(t, tt.expectedGenesisPath, genesisPath) assert.Equal(t, tt.expectedConfigPath, configPath) } } func TestPathsWindows(t *testing.T) { if runtime.GOOS != "windows" { return } tests := []struct { home string expectedWalletDir string expectedDefaultWalletPath string expectedGenesisPath string expectedConfigPath string }{ { "c:\\pactus", "c:\\pactus\\wallets", "c:\\pactus\\wallets\\default_wallet", "c:\\pactus\\genesis.json", "c:\\pactus\\config.toml", }, { "c:\\home\\", "c:\\home\\wallets", "c:\\home\\wallets\\default_wallet", "c:\\home\\genesis.json", "c:\\home\\config.toml", }, } for _, tt := range tests { walletDir := PactusWalletDir(tt.home) defaultWalletPath := PactusDefaultWalletPath(tt.home) genesisPath := PactusGenesisPath(tt.home) configPath := PactusConfigPath(tt.home) assert.Equal(t, tt.expectedWalletDir, walletDir) assert.Equal(t, tt.expectedDefaultWalletPath, defaultWalletPath) assert.Equal(t, tt.expectedGenesisPath, genesisPath) assert.Equal(t, tt.expectedConfigPath, configPath) } } func TestMakeRewardAddresses(t *testing.T) { ts := testsuite.NewTestSuite(t) setupWallet := func() *wallet.Wallet { walletPath := util.TempFilePath() mnemonic, _ := wallet.GenerateMnemonic(128) wlt, err := wallet.Create(t.Context(), walletPath, mnemonic, "", genesis.Mainnet) require.NoError(t, err) _, _ = wlt.NewValidatorAddress("Validator 1") _, _ = wlt.NewValidatorAddress("Validator 2") _, _ = wlt.NewValidatorAddress("Validator 3") return wlt } t.Run("No reward addresses in wallet", func(t *testing.T) { wlt := setupWallet() valAddrsInfo := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) confRewardAddresses := []string{} _, err := MakeRewardAddresses(wlt, valAddrsInfo, confRewardAddresses) assert.ErrorContains(t, err, "unable to find a reward address in the wallet") }) t.Run("Wallet with one Ed25519 address", func(t *testing.T) { wlt := setupWallet() addr1Info, _ := wlt.NewEd25519AccountAddress("", "") _, _ = wlt.NewEd25519AccountAddress("", "") _, _ = wlt.NewBLSAccountAddress("") valAddrsInfo := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) confRewardAddresses := []string{} rewardAddrs, err := MakeRewardAddresses(wlt, valAddrsInfo, confRewardAddresses) require.NoError(t, err) assert.Equal(t, rewardAddrs[0].String(), addr1Info.Address) assert.Equal(t, rewardAddrs[1].String(), addr1Info.Address) assert.Equal(t, rewardAddrs[2].String(), addr1Info.Address) }) t.Run("Wallet with one BLS address", func(t *testing.T) { wlt := setupWallet() addr1Info, _ := wlt.NewBLSAccountAddress("") _, _ = wlt.NewBLSAccountAddress("") valAddrsInfo := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) confRewardAddresses := []string{} rewardAddrs, err := MakeRewardAddresses(wlt, valAddrsInfo, confRewardAddresses) require.NoError(t, err) assert.Equal(t, rewardAddrs[0].String(), addr1Info.Address) assert.Equal(t, rewardAddrs[1].String(), addr1Info.Address) assert.Equal(t, rewardAddrs[2].String(), addr1Info.Address) }) t.Run("One reward address in config", func(t *testing.T) { wlt := setupWallet() valAddrsInfo := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) confRewardAddresses := []string{ ts.RandAccAddress().String(), } rewardAddrs, err := MakeRewardAddresses(wlt, valAddrsInfo, confRewardAddresses) require.NoError(t, err) assert.Equal(t, rewardAddrs[0].String(), confRewardAddresses[0]) assert.Equal(t, rewardAddrs[1].String(), confRewardAddresses[0]) assert.Equal(t, rewardAddrs[2].String(), confRewardAddresses[0]) }) t.Run("Three reward addresses in config", func(t *testing.T) { wlt := setupWallet() valAddrsInfo := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) confRewardAddresses := []string{ ts.RandAccAddress().String(), ts.RandAccAddress().String(), ts.RandAccAddress().String(), } rewardAddrs, err := MakeRewardAddresses(wlt, valAddrsInfo, confRewardAddresses) require.NoError(t, err) assert.Equal(t, rewardAddrs[0].String(), confRewardAddresses[0]) assert.Equal(t, rewardAddrs[1].String(), confRewardAddresses[1]) assert.Equal(t, rewardAddrs[2].String(), confRewardAddresses[2]) }) t.Run("Insufficient reward addresses in config", func(t *testing.T) { wlt := setupWallet() valAddrsInfo := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) confRewardAddresses := []string{ ts.RandAccAddress().String(), ts.RandAccAddress().String(), } _, err := MakeRewardAddresses(wlt, valAddrsInfo, confRewardAddresses) assert.ErrorContains(t, err, "expected 3 reward addresses, but got 2") }) } func TestCreateNode(t *testing.T) { tests := []struct { name string numValidators int chain genesis.ChainType workingDir string mnemonic string withErr bool validatorAddrs []string rewardAddrs string }{ { name: "Create node for Mainnet", numValidators: 1, chain: genesis.Mainnet, workingDir: util.TempDirPath(), mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow", validatorAddrs: []string{"pc1pqpu5tkuctj6ecxjs85f9apm802hhc65amwhuyw"}, rewardAddrs: "pc1rkg0nhswqj85wnz9sm0g9kfkxj68lfx9lhftl8n", withErr: false, }, { name: "Create node for Testnet", numValidators: 1, chain: genesis.Testnet, workingDir: util.TempDirPath(), mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow", validatorAddrs: []string{"tpc1p54ex6jvqkz6qyld5wgm77qm7walgy664hxz2pc"}, rewardAddrs: "tpc1rps3xncfvepre5w754xtxxqmrmhwuackjvaft5y", withErr: false, }, { name: "Create node for Localnet", numValidators: 4, chain: genesis.Localnet, workingDir: util.TempDirPath(), mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow", validatorAddrs: []string{ "tpc1p54ex6jvqkz6qyld5wgm77qm7walgy664hxz2pc", "tpc1pdf5e0q4d6eaww3uq5pmw5aayqpaqplra0pj8z2", "tpc1pe5px2dddn6g4zgnu3wpwgrqpdjrufvda57a4wm", "tpc1p8yyhysp380j9q9gxa6vlhstgkd94238kunttpr", }, rewardAddrs: "tpc1rps3xncfvepre5w754xtxxqmrmhwuackjvaft5y", withErr: false, }, { name: "Localnet with one validator", numValidators: 1, chain: genesis.Localnet, workingDir: util.TempDirPath(), mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow", validatorAddrs: nil, rewardAddrs: "", withErr: true, }, { name: "Invalid mnemonic", numValidators: 4, chain: genesis.Mainnet, workingDir: util.TempDirPath(), mnemonic: "", validatorAddrs: nil, rewardAddrs: "", withErr: true, }, } for _, tt := range tests { wlt, rewardAddrs, err := CreateNode(t.Context(), tt.numValidators, tt.chain, tt.workingDir, tt.mnemonic, "") if tt.withErr { require.Error(t, err) } else { require.NoError(t, err) valInfos := wlt.ListAddresses(wallet.OnlyValidatorAddresses()) for i, addr := range tt.validatorAddrs { assert.Equal(t, valInfos[i].Address, addr) } assert.Equal(t, tt.rewardAddrs, rewardAddrs) } } } ================================================ FILE: cmd/daemon/import.go ================================================ package main import ( "fmt" "os" "path/filepath" "github.com/ezex-io/gopkg/signal" "github.com/gofrs/flock" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/downloader" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) func buildImportCmd(parentCmd *cobra.Command) { importCmd := &cobra.Command{ Use: "import", Short: "download and import pruned data", } parentCmd.AddCommand(importCmd) workingDirOpt := addWorkingDirOption(importCmd) serverAddrOpt := importCmd.Flags().String("server-addr", cmd.DefaultSnapshotURL, "import server address") importCmd.Run = func(cobra *cobra.Command, _ []string) { workingDir, err := filepath.Abs(*workingDirOpt) terminal.FatalErrorCheck(err) err = os.Chdir(workingDir) terminal.FatalErrorCheck(err) conf, gen, err := cmd.MakeConfig(workingDir) terminal.FatalErrorCheck(err) lockFilePath := filepath.Join(workingDir, ".pactus.lock") fileLock := flock.New(lockFilePath) locked, err := fileLock.TryLock() terminal.FatalErrorCheck(err) if !locked { terminal.PrintWarnMsgf("Could not lock '%s', another instance is running?", lockFilePath) return } terminal.PrintLine() snapshotURL := *serverAddrOpt importer, err := cmd.NewImporter( gen.ChainType(), snapshotURL, conf.Store.DataPath(), ) terminal.FatalErrorCheck(err) metadata, err := importer.GetMetadata(cobra.Context()) terminal.FatalErrorCheck(err) snapshots := make([]string, 0, len(metadata)) for _, md := range metadata { item := fmt.Sprintf("snapshot %s (%s)", md.CreatedAtTime().Format("2006-01-02"), util.FormatBytesToHumanReadable(md.Data.Size), ) snapshots = append(snapshots, item) } terminal.PrintLine() choice := prompt.PromptSelect("Please select a snapshot", snapshots) selected := metadata[choice] signal.HandleInterrupt(func() { _ = fileLock.Unlock() _ = importer.Cleanup() }) terminal.PrintLine() err = importer.Download(cobra.Context(), &selected, downloadProgressBar) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintLine() terminal.PrintInfoMsgf("📦 Extracting snapshot files...") err = importer.ExtractAndStoreFiles() terminal.FatalErrorCheck(err) terminal.PrintInfoMsgf("📁 Moving data to node directory...") err = importer.MoveStore() terminal.FatalErrorCheck(err) terminal.PrintInfoMsgf("🧹 Cleaning up temporary files...") err = importer.Cleanup() terminal.FatalErrorCheck(err) _ = fileLock.Unlock() terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Node successfully imported pruned data!") terminal.PrintLine() terminal.PrintInfoMsgf("🚀 To start your node, run:") terminal.PrintInfoMsgBoldf(" %s start -w %s", cmd.PactusDaemonName(), workingDir) } } func downloadProgressBar(fileName string) func(stats downloader.Stats) { return func(stats downloader.Stats) { if !stats.Completed { bar := terminal.ProgressBar(stats.TotalSize, 30) bar.Describe(fmt.Sprintf("%s (%s/%s)", fileName, util.FormatBytesToHumanReadable(uint64(stats.Downloaded)), util.FormatBytesToHumanReadable(uint64(stats.TotalSize)), )) // Ignore progress bar errors _ = bar.Add64(stats.Downloaded) } } } ================================================ FILE: cmd/daemon/init.go ================================================ package main import ( "context" "path/filepath" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/spf13/cobra" ) // buildInitCmd builds a sub-command to initialize the Pactus blockchain node. func buildInitCmd(parentCmd *cobra.Command) { initCmd := &cobra.Command{ Use: "init", Short: "initialize the Pactus blockchain node", } parentCmd.AddCommand(initCmd) workingDirOpt := addWorkingDirOption(initCmd) testnetOpt := initCmd.Flags().Bool("testnet", false, "initialize working directory for joining the testnet") localnetOpt := initCmd.Flags().Bool("localnet", false, "initialize working directory for localnet (for development)") restoreOpt := initCmd.Flags().String("restore", "", "restore the 'default_wallet' using a mnemonic or seed phrase") passwordOpt := initCmd.Flags().StringP("password", "p", "", "the wallet password") entropyOpt := initCmd.Flags().IntP("entropy", "e", 128, "entropy bits for seed generation. range: 128 to 256") valNumOpt := initCmd.Flags().IntP("val-num", "", 0, "number of validators to be created. range: 1 to 32") initCmd.Run = func(_ *cobra.Command, _ []string) { workingDir, _ := filepath.Abs(*workingDirOpt) if !util.IsDirNotExistsOrEmpty(workingDir) { terminal.PrintErrorMsgf("The working directory is not empty: %s", workingDir) return } var mnemonic string if *restoreOpt == "" { mnemonic, _ = wallet.GenerateMnemonic(*entropyOpt) terminal.PrintLine() terminal.PrintInfoMsgf("🌱 Your wallet seed phrase:") terminal.PrintInfoMsgBoldf(" %s", mnemonic) terminal.PrintLine() terminal.PrintWarnMsgf("⚠️ CRITICAL: Write down this seed phrase and store it safely!") terminal.PrintWarnMsgf(" This is the ONLY way to recover your wallet if needed.") terminal.PrintWarnMsgf(" Never share it with anyone or store it electronically.") terminal.PrintLine() confirmed := prompt.PromptConfirm("Have you written down the seed phrase? Continue with initialization") if !confirmed { return } } else { mnemonic = *restoreOpt err := wallet.CheckMnemonic(*restoreOpt) terminal.FatalErrorCheck(err) } var password string if *passwordOpt == "" { terminal.PrintLine() terminal.PrintInfoMsgf("🔐 Set a password for your wallet") terminal.PrintInfoMsgf(" This password will be required to access your wallet") password = prompt.PromptPassword("Wallet Password", true) } else { password = *passwordOpt } var valNum int if *valNumOpt == 0 { terminal.PrintLine() terminal.PrintInfoMsgBoldf("🏛️ How many validators do you want to create?") terminal.PrintInfoMsgf(" • Each node can run up to 32 validators") terminal.PrintInfoMsgf(" • Each validator can stake up to 1,000 coins") terminal.PrintInfoMsgf(" • Choose based on your total stake amount") terminal.PrintLine() valNum = prompt.PromptInputWithRange("Number of Validators", 7, 1, 32) } else { if *valNumOpt < 1 || *valNumOpt > 32 { terminal.PrintErrorMsgf("%v is not in valid range of validator number, it should be between 1 and 32", *valNumOpt) return } valNum = *valNumOpt } chain := genesis.Mainnet // The order of checking the network (chain type) matters here. if *testnetOpt { crypto.ToTestnetHRP() chain = genesis.Testnet } if *localnetOpt { crypto.ToTestnetHRP() chain = genesis.Localnet } ctx := context.Background() wlt, rewardAddrs, err := cmd.CreateNode(ctx, valNum, chain, workingDir, mnemonic, password) terminal.FatalErrorCheck(err) // Recovering addresses if *restoreOpt != "" { cmd.RecoverWalletAddresses(wlt, password) } terminal.PrintLine() terminal.PrintInfoMsgBoldf("🏛️ Validator Addresses:") for i, addrInfo := range wlt.ListAddresses(wallet.OnlyValidatorAddresses()) { terminal.PrintInfoMsgf(" %d. %s", i+1, addrInfo.Address) } terminal.PrintLine() terminal.PrintInfoMsgBoldf("💰 Reward Address:") terminal.PrintInfoMsgf(" %s", rewardAddrs) terminal.PrintLine() terminal.PrintInfoMsgf("🌐 Network: %v", chain.String()) terminal.PrintInfoMsgf("📁 Working Directory: %v", workingDir) terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Pactus node successfully initialized!") terminal.PrintLine() terminal.PrintInfoMsgf("🚀 To start your node, run:") terminal.PrintInfoMsgBoldf(" %s start -w %s", cmd.PactusDaemonName(), workingDir) } } ================================================ FILE: cmd/daemon/main.go ================================================ package main import ( "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/version" "github.com/spf13/cobra" ) func init() { version.NodeAgent.AppType = "daemon" } func main() { rootCmd := &cobra.Command{ Use: "pactus-daemon", Short: "Pactus daemon", CompletionOptions: cobra.CompletionOptions{HiddenDefaultCmd: true}, } // Hide the "help" sub-command rootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) buildVersionCmd(rootCmd) buildInitCmd(rootCmd) buildStartCmd(rootCmd) buildPruneCmd(rootCmd) buildImportCmd(rootCmd) err := rootCmd.Execute() if err != nil { terminal.PrintErrorMsgf(err.Error()) } } func addWorkingDirOption(c *cobra.Command) *string { return c.Flags().StringP("working-dir", "w", cmd.PactusDefaultHomeDir(), "the path to the working directory that keeps the wallets and node files") } ================================================ FILE: cmd/daemon/prune.go ================================================ package main import ( "context" "fmt" "os" "path/filepath" "github.com/ezex-io/gopkg/signal" "github.com/gofrs/flock" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) func buildPruneCmd(parentCmd *cobra.Command) { pruneCmd := &cobra.Command{ Use: "prune", Short: "prune old blocks and transactions from the node", Long: "The prune command optimizes blockchain storage by removing outdated blocks and transactions, " + "freeing up disk space and enhancing node performance.", } parentCmd.AddCommand(pruneCmd) workingDirOpt := addWorkingDirOption(pruneCmd) pruneCmd.Run = func(_ *cobra.Command, _ []string) { workingDir, _ := filepath.Abs(*workingDirOpt) // change working directory err := os.Chdir(workingDir) terminal.FatalErrorCheck(err) // Define the lock file path lockFilePath := filepath.Join(workingDir, ".pactus.lock") fileLock := flock.New(lockFilePath) locked, err := fileLock.TryLock() terminal.FatalErrorCheck(err) if !locked { terminal.PrintWarnMsgf("Could not lock '%s', another instance is running?", lockFilePath) return } conf, _, err := cmd.MakeConfig(workingDir) terminal.FatalErrorCheck(err) // Disable logger conf.Logger.Targets = []string{} logger.InitGlobalLogger(context.Background(), conf.Logger) terminal.PrintLine() terminal.PrintWarnMsgf("⚠️ PRUNE OPERATION WARNING") terminal.PrintWarnMsgf(" This will remove all blocks and transactions older than %d days", conf.Store.RetentionDays) terminal.PrintWarnMsgf(" and convert your node to prune mode.") terminal.PrintWarnMsgf(" This action cannot be undone.") terminal.PrintLine() confirmed := prompt.PromptConfirm("Are you sure you want to continue") if !confirmed { return } terminal.PrintLine() store, err := store.NewStore(conf.Store) terminal.FatalErrorCheck(err) prunedCount := uint32(0) skippedCount := uint32(0) totalCount := uint32(0) canceled := false closed := make(chan bool, 1) signal.HandleInterrupt(func() { canceled = true <-closed }) err = store.Prune(func(pruned bool, pruningHeight types.Height) bool { if pruned { prunedCount++ } else { skippedCount++ } if totalCount == 0 { totalCount = uint32(pruningHeight) } pruningProgressBar(prunedCount, skippedCount, totalCount) return canceled }) terminal.PrintLine() terminal.FatalErrorCheck(err) if canceled { terminal.PrintLine() terminal.PrintWarnMsgf("❌ Prune operation cancelled.") terminal.PrintLine() } else if prunedCount == 0 { terminal.PrintLine() terminal.PrintInfoMsgf("ℹ️ No pruning needed") terminal.PrintInfoMsgf(" Your node has not reached the retention period (%d days)", conf.Store.RetentionDays) terminal.PrintInfoMsgf(" or is already in prune mode.") terminal.PrintLine() } else { terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Your node successfully pruned and changed to prune mode.") terminal.PrintLine() terminal.PrintInfoMsgf("🚀 To start your node, run:") terminal.PrintInfoMsgBoldf(" %s start -w %s", cmd.PactusDaemonName(), workingDir) } store.Close() _ = fileLock.Unlock() closed <- true } } func pruningProgressBar(prunedCount, skippedCount, totalCount uint32) { if (prunedCount+skippedCount)%1000 != 0 { return } bar := terminal.ProgressBar(int64(totalCount), 30) bar.Describe(fmt.Sprintf("Pruned: %d | Skipped: %d", prunedCount, skippedCount)) err := bar.Add(int(prunedCount + skippedCount)) terminal.FatalErrorCheck(err) } ================================================ FILE: cmd/daemon/start.go ================================================ package main import ( "context" "os" "path/filepath" "strings" "github.com/ezex-io/gopkg/signal" "github.com/gofrs/flock" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) // buildStartCmd builds a sub-command to starts the Pactus blockchain node. func buildStartCmd(parentCmd *cobra.Command) { startCmd := &cobra.Command{ Use: "start", Short: "start the Pactus blockchain node", } parentCmd.AddCommand(startCmd) workingDirOpt := addWorkingDirOption(startCmd) passwordOpt := startCmd.Flags().StringP("password", "p", "", "the wallet password") passwordFromFileOpt := startCmd.Flags().String("password-from-file", "", "the file containing the wallet password") gRPCOpt := startCmd.Flags().String("grpc", "", "enable gRPC transport, example: localhost:50051") gRPCWalletOpt := startCmd.Flags().Bool("grpc-wallet", false, "enable gRPC wallet service") startCmd.Run = func(_ *cobra.Command, _ []string) { workingDir, _ := filepath.Abs(*workingDirOpt) // change working directory err := os.Chdir(workingDir) terminal.FatalErrorCheck(err) // Define the lock file path lockFilePath := filepath.Join(workingDir, ".pactus.lock") fileLock := flock.New(lockFilePath) locked, err := fileLock.TryLock() terminal.FatalErrorCheck(err) if !locked { terminal.PrintWarnMsgf("Could not lock '%s', another instance is running?", lockFilePath) return } passwordFetcher := func() (string, bool) { var password string if *passwordOpt != "" { password = *passwordOpt } else if *passwordFromFileOpt != "" { b, err := util.ReadFile(*passwordFromFileOpt) terminal.FatalErrorCheck(err) password = strings.TrimSpace(string(b)) } else { password = prompt.PromptPassword("Wallet password", false) } return password, true } configModifier := func(cfg *config.Config) *config.Config { if *gRPCOpt != "" { cfg.GRPC.Enable = true cfg.GRPC.EnableWallet = *gRPCWalletOpt cfg.GRPC.Listen = *gRPCOpt } return cfg } ctx, cancel := context.WithCancel(context.Background()) node, err := cmd.StartNode(ctx, workingDir, passwordFetcher, configModifier) terminal.FatalErrorCheck(err) signal.HandleInterrupt(func() { terminal.PrintInfoMsgf("Exiting...") cancel() _ = fileLock.Unlock() node.Stop() }) // run forever (the node will not be returned) select {} } } ================================================ FILE: cmd/daemon/version.go ================================================ package main import ( "github.com/pactus-project/pactus/version" "github.com/spf13/cobra" ) // Version prints the version of the Pactus node. func buildVersionCmd(parentCmd *cobra.Command) { versionCmd := &cobra.Command{ Use: "version", Short: "prints the Pactus version", } parentCmd.AddCommand(versionCmd) versionCmd.Run = func(c *cobra.Command, _ []string) { c.Printf("Pactus version: %s\n", version.NodeVersion().StringWithAlias()) } } ================================================ FILE: cmd/gtk/app/run.go ================================================ //go:build gtk package app import ( "context" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/cmd/gtk/controller" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc" ) type GUI struct { MainWindow *view.MainWindowView NodeCtrl *controller.NodeWidgetController WalletCtrl *controller.WalletWidgetController ValidatorCtrl *controller.ValidatorWidgetController CommitteeCtrl *controller.CommitteeWidgetController NetworkCtrl *controller.NetworkWidgetController } // Run builds and shows the main window, wiring views/controllers. // It accepts a gRPC connection to the node (standard grpc.ClientConn or gRPC-Web). // connectionLabel is "Remote address" or "Working directory"; connectionValue is the address or path. // It returns a cleanup function that closes the window and stops timers. func Run(ctx context.Context, conn grpc.ClientConnInterface, gtkApp *gtk.Application, notify func(string), connectionLabel, connectionValue string, ) (*GUI, error) { blockchainClient := pactus.NewBlockchainClient(conn) transactionClient := pactus.NewTransactionClient(conn) networkClient := pactus.NewNetworkClient(conn) walletClient := pactus.NewWalletClient(conn) nodeModel := model.NewNodeModel(ctx, blockchainClient, networkClient) validatorModel := model.NewValidatorModel(ctx, blockchainClient) walletModel := model.NewWalletModel(ctx, walletClient, transactionClient, blockchainClient, cmd.DefaultWalletName) committeeModel := model.NewCommitteeModel(ctx, blockchainClient) networkModel := model.NewNetworkModel(ctx, networkClient) nodeView := gtkutil.IdleAddSyncT(view.NewNodeWidgetView) walletView := gtkutil.IdleAddSyncT(view.NewWalletWidgetView) validatorView := gtkutil.IdleAddSyncT(view.NewValidatorWidgetView) committeeView := gtkutil.IdleAddSyncT(view.NewCommitteeWidgetView) networkView := gtkutil.IdleAddSyncT(view.NewNetworkWidgetView) nodeCtrl := controller.NewNodeWidgetController(nodeView, nodeModel) walletCtrl := controller.NewWalletWidgetController(walletView, walletModel) validatorCtrl := controller.NewValidatorWidgetController(validatorView, validatorModel) committeeCtrl := controller.NewCommitteeWidgetController(committeeView, committeeModel) networkCtrl := controller.NewNetworkWidgetController(networkView, networkModel) nav := controller.NewNavigator(gtkApp, walletModel, walletCtrl) notify("Fetching Node info...") err := nodeCtrl.BuildView(ctx, connectionLabel, connectionValue) if err != nil { return nil, err } notify("Fetching Validators info...") err = validatorCtrl.BuildView(ctx) if err != nil { return nil, err } notify("Fetching Wallet info...") err = walletCtrl.BuildView(ctx, nav) if err != nil { return nil, err } notify("Fetching Committee info...") err = committeeCtrl.BuildView(ctx) if err != nil { return nil, err } notify("Fetching Network info...") err = networkCtrl.BuildView(ctx) if err != nil { return nil, err } mwView := gtkutil.IdleAddSyncT(func() *view.MainWindowView { mwView := view.NewMainWindowView() mwView.BoxNode.Add(nodeView.Box) mwView.BoxDefaultWallet.Add(walletView.Box) mwView.BoxValidators.Add(validatorView.Box) mwView.BoxCommittee.Add(committeeView.Box) mwView.BoxNetwork.Add(networkView.Box) mwCtrl := controller.NewMainWindowController(mwView) mwCtrl.BuildView(nav) mwView.Window.ShowAll() gtkApp.AddWindow(mwView.Window) return mwView }) return &GUI{ MainWindow: mwView, NodeCtrl: nodeCtrl, WalletCtrl: walletCtrl, ValidatorCtrl: validatorCtrl, CommitteeCtrl: committeeCtrl, NetworkCtrl: networkCtrl, }, nil } func (g *GUI) Cleanup() { g.MainWindow.Cleanup() } ================================================ FILE: cmd/gtk/assets/assets.go ================================================ //go:build gtk package assets import ( "github.com/gotk3/gotk3/gdk" "github.com/gotk3/gotk3/gtk" ) func InitAssets() { initIcons() initImages() } // missingPixbuf tries to return an icon-theme "missing image" pixbuf and falls // back to a simple solid square if the theme isn't available. func missingPixbuf(size int) *gdk.Pixbuf { theme, err := gtk.IconThemeGetDefault() if err == nil && theme != nil { pixbuf, err := theme.LoadIcon("image-missing", size, 0) if err == nil || pixbuf != nil { return pixbuf } } // Last resort: a tiny gray square (ARGB32). pixbuf, err := gdk.PixbufNew(gdk.COLORSPACE_RGB, true, 8, size, size) if err == nil && pixbuf != nil { // 0xAARRGGBB pixbuf.Fill(0xFF666666) return pixbuf } return nil } ================================================ FILE: cmd/gtk/assets/css/style.css ================================================ .inline_button { padding: 2px; margin-right: 3px; } .copyable_entry { padding-right: 36px; } .warning { color: red; } ================================================ FILE: cmd/gtk/assets/css.go ================================================ //go:build gtk package assets import _ "embed" // Main CSS. //go:embed css/style.css var MainWindowCSS string ================================================ FILE: cmd/gtk/assets/dialogs.go ================================================ //go:build gtk package assets import ( _ "embed" ) // Dialogs/UI used by the GTK app. // About dialogs. //go:embed ui/dialog_about.ui var DialogAboutUI []byte //go:embed ui/dialog_about_gtk.ui var DialogAboutGTKUI []byte // Wallet dialogs. //go:embed ui/dialog_wallet_password.ui var WalletPasswordDialogUI []byte //go:embed ui/dialog_wallet_create_address.ui var WalletCreateAddressDialogUI []byte //go:embed ui/dialog_wallet_change_password.ui var WalletChangePasswordDialogUI []byte //go:embed ui/dialog_wallet_set_default_fee.ui var WalletSetDefaultFeeDialogUI []byte //go:embed ui/dialog_wallet_show_seed.ui var WalletShowSeedDialogUI []byte // Address dialogs. //go:embed ui/dialog_address_label.ui var AddressLabelDialogUI []byte //go:embed ui/dialog_address_details.ui var AddressDetailsDialogUI []byte //go:embed ui/dialog_address_private_key.ui var AddressPrivateKeyDialogUI []byte // Transaction dialogs. //go:embed ui/dialog_transaction_transfer.ui var TxTransferDialogUI []byte //go:embed ui/dialog_transaction_bond.ui var TxBondDialogUI []byte //go:embed ui/dialog_transaction_unbond.ui var TxUnbondDialogUI []byte //go:embed ui/dialog_transaction_withdraw.ui var TxWithdrawDialogUI []byte ================================================ FILE: cmd/gtk/assets/icons.go ================================================ //go:build gtk package assets import ( _ "embed" "github.com/gotk3/gotk3/gdk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) var ( //go:embed icons/add.svg iconAddData []byte IconAddPixbuf16 *gdk.Pixbuf //go:embed icons/ok.svg iconOKData []byte IconOkPixbuf16 *gdk.Pixbuf //go:embed icons/cancel.svg iconCancelData []byte IconCancelPixbuf16 *gdk.Pixbuf //go:embed icons/password.svg iconPasswordData []byte IconPasswordPixbuf16 *gdk.Pixbuf //go:embed icons/seed.svg iconSeedData []byte IconSeedPixbuf16 *gdk.Pixbuf //go:embed icons/close.svg iconCloseData []byte IconClosePixbuf16 *gdk.Pixbuf //go:embed icons/send.svg iconSendData []byte IconSendPixbuf16 *gdk.Pixbuf //go:embed icons/fee.svg iconFeeData []byte IconFeePixbuf16 *gdk.Pixbuf //go:embed icons/refresh.svg iconRefreshData []byte IconRefreshPixbuf16 *gdk.Pixbuf //go:embed icons/prev.svg iconPrevData []byte IconPrevPixbuf16 *gdk.Pixbuf //go:embed icons/next.svg iconNextData []byte IconNextPixbuf16 *gdk.Pixbuf ) func initIcons() { toPixbuf := func(data []byte) *gdk.Pixbuf { pixbuf, err := gtkutil.PixbufFromBytes(data, gtkutil.WithSize(16, 16)) if err != nil { return missingPixbuf(16) } return pixbuf } IconAddPixbuf16 = toPixbuf(iconAddData) IconOkPixbuf16 = toPixbuf(iconOKData) IconCancelPixbuf16 = toPixbuf(iconCancelData) IconPasswordPixbuf16 = toPixbuf(iconPasswordData) IconSeedPixbuf16 = toPixbuf(iconSeedData) IconClosePixbuf16 = toPixbuf(iconCloseData) IconSendPixbuf16 = toPixbuf(iconSendData) IconFeePixbuf16 = toPixbuf(iconFeeData) IconRefreshPixbuf16 = toPixbuf(iconRefreshData) IconPrevPixbuf16 = toPixbuf(iconPrevData) IconNextPixbuf16 = toPixbuf(iconNextData) } ================================================ FILE: cmd/gtk/assets/images.go ================================================ //go:build gtk package assets import ( _ "embed" "github.com/gotk3/gotk3/gdk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) var ( //go:embed images/pactus.png imagePactusLogoData []byte ImagePactusLogoPixbuf *gdk.Pixbuf //go:embed images/gtk.png imageGTKLogoData []byte ImageGTKLogoPixbuf *gdk.Pixbuf //go:embed images/seed.svg imageSeedData []byte ImageSeedPixbuf *gdk.Pixbuf ) func initImages() { toPixbuf := func(data []byte) *gdk.Pixbuf { pixbuf, err := gtkutil.PixbufFromBytes(data) if err != nil { return missingPixbuf(128) } return pixbuf } ImagePactusLogoPixbuf = toPixbuf(imagePactusLogoData) ImageGTKLogoPixbuf = toPixbuf(imageGTKLogoData) ImageSeedPixbuf = toPixbuf(imageSeedData) } ================================================ FILE: cmd/gtk/assets/main_ui.go ================================================ //go:build gtk package assets import ( _ "embed" ) // Main window / widgets UI and CSS. //go:embed ui/main_window.ui var MainWindowUI []byte //go:embed ui/widget_node.ui var NodeWidgetUI []byte //go:embed ui/widget_wallet.ui var WalletWidgetUI []byte //go:embed ui/widget_validator.ui var ValidatorWidgetUI []byte //go:embed ui/widget_committee.ui var CommitteeWidgetUI []byte //go:embed ui/widget_network.ui var NetworkWidgetUI []byte ================================================ FILE: cmd/gtk/assets/ui/dialog_about.ui ================================================ False About Pactus dialog Pactus 0.0.0 Building Decentralized Future Together! Pactus is a low-cost, high-performance, and scalable decentralized blockchain protocol with the SSPoS consensus mechanism. https://pactus.org mit-x11 False vertical 2 False end False False 0 ================================================ FILE: cmd/gtk/assets/ui/dialog_about_gtk.ui ================================================ False About GTK dialog GTK Gtk – 3.0 GTK is a free and open-source cross-platform widget toolkit for creating graphical user interfaces. It is licensed under the terms of the GNU Lesser General Public License, allowing both free and proprietary software to use it. https://www.gtk.org/ lgpl-2-1 False vertical 2 False end False False 0 ================================================ FILE: cmd/gtk/assets/ui/dialog_address_details.ui ================================================ False Address details 480 dialog False 8 8 4 4 vertical 2 False end _Close True True False True True True True True True True 1 False False 0 True False vertical 4 True False start Address: False True 0 True False False True 1 True False start Public Key: False True 2 True False False True 3 True False start Derivation path: False True 4 True True True False 32 False False True 5 True True 8 1 id_button_close ================================================ FILE: cmd/gtk/assets/ui/dialog_address_label.ui ================================================ False Enter label 320 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False False True True True True 0 _Ok True True False True True True True True True True 1 False False 0 True False 8 8 True False start Enter label for the address: 0 0 True True 32 0 1 True True 8 1 id_button_cancel id_button_ok ================================================ FILE: cmd/gtk/assets/ui/dialog_address_private_key.ui ================================================ False Private key 480 dialog False 8 8 4 4 vertical 2 False end _Close True True False True True True True True True True 1 False False 0 True False vertical 4 True False start Address: False True 0 True True True False 32 False False True 1 True False start Private Key: False True 2 True True True False 32 False False True 3 True False ⚠️ Keep your private key secure. False True 4 True True 8 1 id_button_close ================================================ FILE: cmd/gtk/assets/ui/dialog_transaction_bond.ui ================================================ 600 False Broadcasting Bond transaction True 480 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False True True True True True True True 0 _Send True True False True True True True True True True 1 False False 0 True False vertical 4 True False start Account address: False True 0 True False False True 1 True False start True False True 2 True False False True 3 True False start Validator address: False True 4 True True True True True True False True 5 True False start False True 6 True False False True 7 True False start Validator public key (Optional; Only set when it is not your validator): False True 8 True True False True 9 True False False True 10 True False start Amount: False True 11 True True True False number False True 12 True False start True False True 13 True False False True 14 True False start Fee: False True 15 True True True False number False True 16 True False start True False True 17 True False False True 18 True False start Memo (Up to 64 characters, Optional): False True 19 True True True False False True 20 True True 8 1 id_button_cancel ================================================ FILE: cmd/gtk/assets/ui/dialog_transaction_transfer.ui ================================================ 600 False Broadcasting Transfer transaction True 480 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False True True True True True True True 0 _Send True True False True True True True True True True 1 False False 1 True False vertical 4 True False start Sender: False True 0 True False False True 1 True False start True False True 2 True False False True 3 True False start Receiver: False True 4 True True True False False True 5 True False start False True 6 True False False True 7 True False start Amount: False True 8 True True True False number False True 9 True False start True False True 10 True False False True 11 True False start Fee: False True 12 True True True False number False True 13 True False start True False True 14 True False False True 15 True False start Memo (Up to 64 characters, Optional): False True 16 True True True False False True 17 True True 8 0 id_button_cancel ================================================ FILE: cmd/gtk/assets/ui/dialog_transaction_unbond.ui ================================================ 600 False Broadcasting Unbond transaction True 480 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False True True True True True True True 0 _Send True True False True True True True True True True 1 False False 0 True False vertical 4 True False start Validator address: False True 0 True True True True True True False True 1 True False start False True 2 True False False True 3 True False start Memo (Up to 64 characters, Optional): False True 4 True True True False False True 5 True True 8 1 id_button_cancel ================================================ FILE: cmd/gtk/assets/ui/dialog_transaction_withdraw.ui ================================================ 600 False Broadcasting Withdraw transaction True 480 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False True True True True True True True 0 _Send True True False True True True True True True True 1 False False 1 True False vertical 4 True False start Sender: False True 0 True False False True 1 True False start True False True 2 True False False True 3 True False start Receiver: False True 4 True True True True True True False True 5 True False start False True 6 True False start Stake: False True 7 True True True False number False True 8 True False start True False True 9 True False False True 10 True False start Fee: False True 12 True True True False number False True 13 True False start True False True 14 True False False True 15 True False start Memo (Up to 64 characters, Optional): False True 16 True True True False False True 17 True True 8 0 id_button_cancel ================================================ FILE: cmd/gtk/assets/ui/dialog_wallet_change_password.ui ================================================ False Change password 320 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False False True True True True 0 _Ok True True False True True True True True True True 1 False False 0 True False 8 8 True False start Old password: 0 0 True True False True 24 password 1 0 True False start New password: 0 1 True True False True 24 password 1 1 True True False True 24 password 1 2 True False start Repeat: 0 2 True True 8 1 id_button_cancel id_button_ok ================================================ FILE: cmd/gtk/assets/ui/dialog_wallet_create_address.ui ================================================ False New address 320 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False False True True True True 0 _Ok True True False True True True True True True True 1 False False 0 True False 8 8 True False start Label: 0 0 True True True 24 1 0 True False start Type: 0 1 True False 1 1 True True 8 1 id_button_cancel id_button_ok ================================================ FILE: cmd/gtk/assets/ui/dialog_wallet_password.ui ================================================ False Enter password 320 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False False True True True True 0 _Ok True True False True True True True True True True 1 False False 0 True False 8 8 True True False True 24 password 0 1 True False start Enter your wallet password: 0 0 True True 8 1 id_button_cancel id_button_ok ================================================ FILE: cmd/gtk/assets/ui/dialog_wallet_set_default_fee.ui ================================================ False Set Default Fee 320 dialog False 8 8 4 4 vertical 2 False end _Cancel True True False False True True True True 0 _Ok True True False True True True True True True True 1 False False 0 True False 8 8 True False start Default Fee (PAC): 0 0 True True True 24 number 1 0 True False start Current: 0 1 True False start 0.01 PAC 1 1 True True 8 1 id_button_cancel id_button_ok ================================================ FILE: cmd/gtk/assets/ui/dialog_wallet_show_seed.ui ================================================ False Wallet seed 320 dialog False 8 8 4 4 vertical 2 False end _Close True True False True True True True True True True 1 False False 0 True False 8 8 True True True False word 2 2 2 2 1 0 True False gtk-missing-image 0 0 True False <span allow_breaks="true"> <b>⚠️ CRITICAL: Write down this seed phrase and store it safely!</b> This is the ONLY way to recover your wallet if needed. Never share it with anyone or store it electronically.</span> True 1 1 True True 8 1 id_button_close ================================================ FILE: cmd/gtk/assets/ui/main_window.ui ================================================ False Pactus GUI 880 440 True False vertical True False True False _File True True False True False True False _Quit True True False _Wallet True True False True False _New Address True True False True False Change _Password True True False Show _Seed True True False True False Set Default _Fee True True False _Transaction True True False True False _Transfer True True False _Bond True True False _Unbond True True False _Withdraw True True False _Help True True False True False _Website True True False _Explorer True True False _Documentation True True False True False About _Pactus True True False About _GTK True False True 0 True True True True False True True False Node right False True False True 1 True False Committee 1 False True False True 2 True False Network 2 False True False True 3 True False My Validators 3 False True False True 4 True False Default wallet 4 False False True 1 ================================================ FILE: cmd/gtk/assets/ui/widget_committee.ui ================================================ True False vertical True True True left True False True True True False 12 12 12 12 6 12 True False start Committee Size: 0 0 True False start True 1 0 True False start Committee Power: 0 1 True False start True 1 1 True False start Total Power: 0 2 True False start True 1 2 True False start Protocol Versions: 0 3 True False start start True True 1 3 0 True False Info False True True True True in True True 1 True False Members 1 False True True 0 ================================================ FILE: cmd/gtk/assets/ui/widget_network.ui ================================================ True False vertical True True True left True False True True True False 12 12 12 12 6 12 True False start Network Name: 0 0 True False start True 1 0 True False start Connected Peers: 0 1 True False start True 1 1 0 True False Info False True True True True in True True 1 True False Peers 1 False True True 0 ================================================ FILE: cmd/gtk/assets/ui/widget_node.ui ================================================ True False vertical top True False 6 6 32 32 True False 0 0 True False start False vertical top True False start start 6 6 6 6 False 0.019999999552965164 in 400 True False start start 6 6 6 6 True 6 6 True False start start True True 0 0 True False start start True True True 1 0 True False start start True True 🌐 Network: 0 1 True False start start True True True 1 1 True False start start True True 🧾 Network ID: 0 2 True False start start True True True 1 2 True False start start True True 🤖 Node Agent: 0 3 True False start start True True True 1 3 True False start start True True ⏰ Clock Offset: 0 4 True False start start True True 1 4 True False start start True True 📡 Connections: 0 5 True False start start True True True 1 5 True False start start True True 🔰 Moniker: 0 6 True False start start True True True 1 6 True False start start True True 🔍 Reachability: 0 7 True False start start True True True 1 7 True False start True True ✂️ Pruned: 0 8 True False start start True True 1 8 True False start start True True ⛓️ Last Block Height: 0 9 True False start start True True 1 9 True False start start True True 🕔 Last Block Time: 0 10 True False start start True True 1 10 True False start start True True 📦 Remaining Blocks: 0 11 True False start start True True 1 11 True False start start True True 🔄 Syncing Progress: 0 12 True False False 0.01 True 1 12 True False Node info False True 0 True False start start 6 6 6 6 6 6 False 0.019999999552965164 in 400 True False start start 6 6 6 6 6 6 True 6 6 True False start start True True 👥 Committee Size: 0 0 True False start start True True 💎 In Committee Now: 0 4 True False start start True True ⚡️ Committee Power: 0 2 True False start start True True True 1 0 True False start start True True True 1 4 True False start start True True True 1 2 True False start start True True True 1 3 True False start start True True ✨ Total Power: 0 3 True False start start True True ✅ Active Validators: 0 1 True False start start True True True 1 1 True False start start True True 📈 Average Score: 0 5 True False start start True True True 1 5 True False Committee info False True 1 1 1 32 32 True False 2 2 False True 0 ================================================ FILE: cmd/gtk/assets/ui/widget_validator.ui ================================================ True False vertical True True True True in True True True True 0 ================================================ FILE: cmd/gtk/assets/ui/widget_wallet.ui ================================================ True False vertical True True True left True False 6 6 True False start start 6 6 6 6 True 0.019999999552965164 in 400 True False 6 6 6 6 6 6 True False start start True True Name: 0 0 True False start start True True Location: 0 1 True False start start True True True 1 0 True False start start True True True 1 1 True False start start True True 1 4 True False start start True True Encrypted: 0 4 True False start start True True Total Balance: 0 5 True False start start True True 1 5 True False start start True True Total Stake: 0 6 True False start start True True 1 6 True False start start True True Default Fee: 0 7 True False start start True True 1 7 True False start start True True Driver: True 0 2 True False start start True True Created At: True 0 3 True False start start True True True 1 2 True False start start True True True 1 3 True False Overview 1 1 32 32 True False 0 0 32 32 True False 2 2 True False Overview False True False vertical True False True True True False True 0 True False True False Refresh wallet addresses True _Refresh True False True True False Create a new address True _New Address True False True True False Set the default fee of the wallet True Default _Fee True False True True False Change the wallet password Change _Password True False True True False Show the wallet seed _Seed True False True False True 1 1 True False Addresses 1 False True False vertical True True True True True False True 0 True False True False Reload transactions True _Refresh True False True True False Previous page _Prev True False True True False Next page _Next True False True False True 1 2 True False Transactions 2 False False True 0 ================================================ FILE: cmd/gtk/controller/address_details_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" ) type AddressDetailsDialogController struct { view *view.AddressDetailsDialogView model *model.WalletModel } func NewAddressDetailsDialogController( view *view.AddressDetailsDialogView, model *model.WalletModel, ) *AddressDetailsDialogController { return &AddressDetailsDialogController{view: view, model: model} } func (c *AddressDetailsDialogController) Run(addr string) { info := c.model.AddressInfo(addr) if info == nil { gtkutil.ShowErrorDialog(nil, "address not found") return } c.view.AddressEntry.SetText(info.Address) c.view.PubKeyEntry.SetText(info.PublicKey) c.view.PathEntry.SetText(info.Path) onClose := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_close": onClose, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/address_label_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" ) type AddressLabelDialogController struct { view *view.AddressLabelDialogView model *model.WalletModel } func NewAddressLabelDialogController( view *view.AddressLabelDialogView, model *model.WalletModel, ) *AddressLabelDialogController { return &AddressLabelDialogController{view: view, model: model} } func (c *AddressLabelDialogController) Run(address string) { oldLabel := c.model.AddressLabel(address) c.view.LabelEntry.SetText(oldLabel) onOk := func() { newLabel := gtkutil.GetEntryText(c.view.LabelEntry) if err := c.model.SetAddressLabel(address, newLabel); err != nil { gtkutil.ShowError(err) return } c.view.Dialog.Close() } onCancel := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_ok": onOk, "on_cancel": onCancel, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/address_private_key_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" ) type AddressPrivateKeyDialogController struct { view *view.AddressPrivateKeyDialogView model *model.WalletModel } func NewAddressPrivateKeyDialogController( view *view.AddressPrivateKeyDialogView, model *model.WalletModel, ) *AddressPrivateKeyDialogController { return &AddressPrivateKeyDialogController{view: view, model: model} } func (c *AddressPrivateKeyDialogController) Run(addr string) { password, ok := PasswordProvider(c.model) if !ok { return } prv, err := c.model.PrivateKey(password, addr) if err != nil { gtkutil.ShowError(err) return } c.view.AddressEntry.SetText(addr) c.view.PrvKeyEntry.SetText(prv.String()) c.view.ConnectSignals(map[string]any{ "on_close": func() { c.view.Dialog.Close() }, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/committee_widget_controller.go ================================================ //go:build gtk package controller import ( "context" "fmt" "slices" "strconv" "strings" "time" "github.com/ezex-io/gopkg/scheduler" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" ) type CommitteeWidgetController struct { view *view.CommitteeWidgetView model *model.CommitteeModel } func NewCommitteeWidgetController( view *view.CommitteeWidgetView, model *model.CommitteeModel, ) *CommitteeWidgetController { return &CommitteeWidgetController{view: view, model: model} } func (c *CommitteeWidgetController) BuildView(ctx context.Context) error { scheduler.Every(10*time.Second).Do(ctx, c.refresh) c.refresh(ctx) return nil } func (c *CommitteeWidgetController) refresh(_ context.Context) { res, err := c.model.GetCommitteeInfo() if err != nil { return } committeePowerStr := amount.Amount(res.CommitteePower).String() totalPowerStr := amount.Amount(res.TotalPower).String() // Protocol versions: map[int32]float64 -> "v1: 80%, v2: 20%" protocolLines := make([]string, 0, len(res.ProtocolVersions)) for ver, percentage := range res.ProtocolVersions { protocolLines = append(protocolLines, fmt.Sprintf("%s: %.2f%%", protocol.Version(ver), percentage)) } slices.SortFunc(protocolLines, strings.Compare) protocolStr := "" for i, s := range protocolLines { if i > 0 { protocolStr += ", " } protocolStr += s } if protocolStr == "" { protocolStr = "—" } gtkutil.IdleAddAsync(func() { c.view.LabelCommitteeSize.SetText(strconv.Itoa(int(res.CommitteeSize))) c.view.LabelCommitteePower.SetText(committeePowerStr) c.view.LabelTotalPower.SetText(totalPowerStr) c.view.LabelProtocolVersions.SetText(protocolStr) c.view.ClearRows() for i, val := range res.Validators { stakeStr := amount.Amount(val.GetStake()).String() c.view.AppendRow( []int{0, 1, 2, 3, 4, 5, 6, 7}, []any{ strconv.Itoa(i + 1), val.GetAddress(), strconv.Itoa(int(val.GetNumber())), stakeStr, strconv.Itoa(int(val.GetLastBondingHeight())), strconv.Itoa(int(val.GetLastSortitionHeight())), strconv.Itoa(int(val.GetProtocolVersion())), gtkutil.AvailabilityScorePercent(val.GetAvailabilityScore()), }, ) } }) } ================================================ FILE: cmd/gtk/controller/controller.go ================================================ //go:build gtk package controller ================================================ FILE: cmd/gtk/controller/main_window_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/view" ) type MainWindowController struct { view *view.MainWindowView } func NewMainWindowController(view *view.MainWindowView) *MainWindowController { return &MainWindowController{view: view} } func (c *MainWindowController) BuildView(nav *Navigator) { gtkutil.IdleAddSync(func() { c.view.ConnectSignals(map[string]any{ "on_quit": nav.Quit, "on_transaction_transfer": nav.ShowTransactionTransfer, "on_transaction_bond": nav.ShowTransactionBond, "on_transaction_unbond": nav.ShowTransactionUnbond, "on_transaction_withdraw": nav.ShowTransactionWithdraw, "on_wallet_new_address": nav.ShowWalletNewAddress, "on_wallet_change_password": nav.ShowWalletChangePassword, "on_wallet_show_seed": nav.ShowWalletShowSeed, "on_wallet_set_default_fee": nav.ShowWalletSetDefaultFee, "on_about_gtk": nav.ShowAboutGtk, "on_about": nav.ShowAbout, "on_open_explorer": nav.BrowseExplorer, "on_open_website": nav.BrowseWebsite, "on_open_docs": nav.BrowseDocs, }) }) } ================================================ FILE: cmd/gtk/controller/navigator.go ================================================ //go:build gtk package controller import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/version" ) // Navigator owns dialog creation and UI flows (open -> run -> post-actions). type Navigator struct { walletModel *model.WalletModel walletCtrl *WalletWidgetController gtkApp *gtk.Application } func NewNavigator(gtkApp *gtk.Application, walletModel *model.WalletModel, walletCtrl *WalletWidgetController, ) *Navigator { return &Navigator{ walletModel: walletModel, walletCtrl: walletCtrl, gtkApp: gtkApp, } } func (*Navigator) ShowAbout() { gtkutil.IdleAddSync(func() { dlg := view.NewAboutDialog() dlg.SetVersion(version.NodeVersion().StringWithAlias()) gtkutil.RunDialog(&dlg.Dialog) }) } func (*Navigator) ShowAboutGtk() { gtkutil.IdleAddSync(func() { dlg := view.NewAboutGTKDialog() dlg.Dialog.SetModal(true) gtkutil.RunDialog(&dlg.Dialog) }) } func (n *Navigator) ShowWalletShowSeed() { gtkutil.IdleAddSync(func() { dlgView := view.NewWalletSeedDialogView() dlgCtrl := NewWalletSeedDialogController(dlgView, n.walletModel) dlgCtrl.Run() }) } func (n *Navigator) ShowWalletNewAddress() { gtkutil.IdleAddSync(func() { dlgView := view.NewWalletCreateAddressDialogView() dlgCtrl := NewWalletCreateAddressDialogController(dlgView, n.walletModel) dlgCtrl.Run() }) go func() { n.walletCtrl.RefreshAddresses() }() } func (n *Navigator) ShowWalletSetDefaultFee() { gtkutil.IdleAddSync(func() { dlgView := view.NewWalletDefaultFeeDialogView() dlgCtrl := NewWalletDefaultFeeDialogController(dlgView, n.walletModel) dlgCtrl.Run() }) go func() { n.walletCtrl.RefreshInfo() }() } func (n *Navigator) ShowWalletChangePassword() { gtkutil.IdleAddSync(func() { dlgView := view.NewWalletChangePasswordDialogView() dlgCtrl := NewWalletChangePasswordDialogController(dlgView, n.walletModel) dlgCtrl.Run() }) go func() { n.walletCtrl.RefreshInfo() }() } func (n *Navigator) ShowTransactionTransfer() { gtkutil.IdleAddSync(func() { dialogView := view.NewTxTransferDialogView() ctrl := NewTxTransferDialogController(dialogView, n.walletModel) ctrl.Run() }) go func() { n.walletCtrl.RefreshTransactions() }() } func (n *Navigator) ShowTransactionBond() { gtkutil.IdleAddSync(func() { dialogView := view.NewTxBondDialogView() ctrl := NewTxBondDialogController(dialogView, n.walletModel) ctrl.Run() }) go func() { n.walletCtrl.RefreshTransactions() }() } func (n *Navigator) ShowTransactionUnbond() { gtkutil.IdleAddSync(func() { dialogView := view.NewTxUnbondDialogView() ctrl := NewTxUnbondDialogController(dialogView, n.walletModel) ctrl.Run() }) go func() { n.walletCtrl.RefreshTransactions() }() } func (n *Navigator) ShowTransactionWithdraw() { gtkutil.IdleAddSync(func() { dialogView := view.NewTxWithdrawDialogView() ctrl := NewTxWithdrawDialogController(dialogView, n.walletModel) ctrl.Run() }) go func() { n.walletCtrl.RefreshTransactions() }() } func (n *Navigator) BrowseWebsite() { n.openWebsite("https://pactus.org/") } func (n *Navigator) BrowseExplorer() { n.openWebsite("https://pacviewer.com/") } func (n *Navigator) BrowseDocs() { n.openWebsite("https://docs.pactus.org/") } func (*Navigator) openWebsite(url string) { _ = gtkutil.OpenURLInBrowser(url) } func (n *Navigator) Quit() { n.gtkApp.Quit() } ================================================ FILE: cmd/gtk/controller/network_widget_controller.go ================================================ //go:build gtk package controller import ( "context" "strconv" "time" "github.com/ezex-io/gopkg/scheduler" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) func peerDirectionString(d pactus.Direction) string { switch d { case pactus.Direction_DIRECTION_UNKNOWN: return "Unknown" case pactus.Direction_DIRECTION_INBOUND: return "Inbound" case pactus.Direction_DIRECTION_OUTBOUND: return "Outbound" default: return "Unknown" } } type NetworkWidgetController struct { view *view.NetworkWidgetView model *model.NetworkModel } func NewNetworkWidgetController( view *view.NetworkWidgetView, model *model.NetworkModel, ) *NetworkWidgetController { return &NetworkWidgetController{view: view, model: model} } func (c *NetworkWidgetController) BuildView(ctx context.Context) error { scheduler.Every(10*time.Second).Do(ctx, func(context.Context) { c.refresh() }) c.refresh() return nil } func (c *NetworkWidgetController) refresh() { netInfo, err := c.model.GetNetworkInfo() if err != nil { return } peersRes, err := c.model.ListPeers(false) // active peers only if err != nil { return } gtkutil.IdleAddAsync(func() { c.view.LabelNetworkName.SetText(netInfo.GetNetworkName()) c.view.LabelConnectedPeers.SetText(strconv.Itoa(int(netInfo.GetConnectedPeersCount()))) c.view.ClearRows() for i, peer := range peersRes.GetPeers() { c.view.AppendRow( []int{0, 1, 2, 3, 4, 5, 6}, []any{ strconv.Itoa(i + 1), peer.GetMoniker(), peer.GetAddress(), peer.GetPeerId(), strconv.Itoa(int(peer.GetHeight())), peer.GetAgent(), peerDirectionString(peer.GetDirection()), }, ) } }) } ================================================ FILE: cmd/gtk/controller/node_widget_controller.go ================================================ //go:build gtk package controller import ( "context" "fmt" "math" "strconv" "time" "github.com/ezex-io/gopkg/scheduler" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/logger" ) // clockOutOfSyncThreshold is the clock offset above which we show a warning. const clockOutOfSyncThreshold = 5 * time.Second type NodeWidgetController struct { view *view.NodeWidgetView model *model.NodeModel } func NewNodeWidgetController(view *view.NodeWidgetView, model *model.NodeModel) *NodeWidgetController { return &NodeWidgetController{view: view, model: model} } // BuildView builds the node widget. connectionLabel is either "Remote address" or "Working directory"; // connectionValue is the remote address or working directory path respectively. func (c *NodeWidgetController) BuildView(ctx context.Context, connectionLabel, connectionValue string) error { nodeInfo, err := c.model.GetNodeInfo() if err != nil { return err } chainInfo, err := c.model.GetBlockchainInfo() if err != nil { return err } gtkutil.IdleAddSync(func() { c.view.LabelConnectionType.SetText(connectionLabel + ":") c.view.LabelConnectionValue.SetText(connectionValue) c.view.LabelNetwork.SetText(nodeInfo.NetworkName) c.view.LabelNetworkID.SetText(nodeInfo.PeerId) c.view.LabelAgent.SetText(nodeInfo.Agent) c.view.LabelMoniker.SetText(nodeInfo.Moniker) c.view.LabelIsPrune.SetText(strconv.FormatBool(chainInfo.IsPruned)) c.view.ConnectSignals(map[string]any{}) }) scheduler.Every(10*time.Second).Do(ctx, func(context.Context) { c.timeout1() }) scheduler.Every(10*time.Second).Do(ctx, func(context.Context) { c.timeout10() }) // Initial refresh. c.timeout1() c.timeout10() return nil } // syncProgressWindowBlocks is the number of blocks behind that maps to 0% sync progress (~10 min at 10s/block). const syncProgressWindowBlocks = 60 func (c *NodeWidgetController) timeout1() { chainInfo, err := c.model.GetBlockchainInfo() if err != nil { return } lastBlockTime := time.Unix(chainInfo.LastBlockTime, 0) lastBlockHeight := chainInfo.LastBlockHeight gtkutil.IdleAddSync(func() { c.view.LabelLastBlockTime.SetText(lastBlockTime.Format("02 Jan 06 15:04:05 MST")) c.view.LabelLastBlockHeight.SetText(strconv.FormatInt(int64(lastBlockHeight), 10)) nowSec := time.Now().Unix() lastBlockTimeSec := lastBlockTime.Unix() blocksLeft := (nowSec - lastBlockTimeSec) / 10 c.view.LabelBlocksLeft.SetText(strconv.FormatInt(blocksLeft, 10)) // Sync progress: 100% when up-to-date, 0% when syncProgressWindowBlocks behind (no genesis time). percentage := 1.0 - float64(blocksLeft)/float64(syncProgressWindowBlocks) if percentage < 0 { percentage = 0 } if percentage > 1 { percentage = 1 } c.view.ProgressBarSynced.SetFraction(percentage) c.view.ProgressBarSynced.SetText(fmt.Sprintf("%s %%", strconv.FormatFloat(percentage*100, 'f', 2, 64))) }) } func (c *NodeWidgetController) timeout10() { chainInfo, err := c.model.GetBlockchainInfo() if err != nil { return } nodeInfo, err := c.model.GetNodeInfo() if err != nil { return } var clockOffset time.Duration var clockOffsetErr error if nodeInfo != nil { clockOffset = time.Duration(nodeInfo.ClockOffset * float64(time.Second)) } var numConnections, reachability string if nodeInfo != nil && nodeInfo.ConnectionInfo != nil { ci := nodeInfo.ConnectionInfo numConnections = fmt.Sprintf("%v (Inbound: %v, Outbound %v)", ci.Connections, ci.InboundConnections, ci.OutboundConnections) reachability = nodeInfo.Reachability } committeeStake := amount.Amount(chainInfo.CommitteePower) totalStake := amount.Amount(chainInfo.TotalPower) gtkutil.IdleAddSync(func() { styleContext, err := c.view.LabelClockOffset.GetStyleContext() if err != nil { logger.Error("failed to get style context", "err", err) return } c.view.LabelClockOffset.SetTooltipText( "Difference between time of your machine and network time (NTP) " + "for synchronization.", ) c.setClockOffset(styleContext, clockOffset, clockOffsetErr) c.view.LabelCommitteeSize.SetText(fmt.Sprintf("%v", chainInfo.CommitteeSize)) c.view.LabelActiveValidator.SetText(fmt.Sprintf("%v", chainInfo.ActiveValidators)) c.view.LabelCommitteeStake.SetText(committeeStake.String()) c.view.LabelTotalStake.SetText(totalStake.String()) c.view.LabelAverageScore.SetText(fmt.Sprintf("%.2f", chainInfo.AverageScore)) c.view.LabelNumConnections.SetText(numConnections) c.view.LabelReachability.SetText(reachability) c.setInCommittee(chainInfo.InCommittee) }) } func (c *NodeWidgetController) setClockOffset(styleContext *gtk.StyleContext, offset time.Duration, offsetErr error) { if offsetErr != nil { styleContext.AddClass("warning") c.view.LabelClockOffset.SetText("N/A") return } o := math.Round(offset.Seconds()) if o == 0 { o = math.Abs(o) // To fix "-0 second(s)" issue } c.view.LabelClockOffset.SetText(fmt.Sprintf("%v second(s)", o)) if offset > clockOutOfSyncThreshold || offset < -clockOutOfSyncThreshold { styleContext.AddClass("warning") return } styleContext.RemoveClass("warning") } func (c *NodeWidgetController) setInCommittee(inCommittee bool) { if inCommittee { c.view.LabelInCommittee.SetMarkup("Yes") return } c.view.LabelInCommittee.SetText("No") } ================================================ FILE: cmd/gtk/controller/password_prompt.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" ) // Controller represents a UI controller that can be executed. // All controllers should have a Run method to execute their primary function. func PasswordProvider(model *model.WalletModel) (string, bool) { if model == nil || !model.IsEncrypted() { return "", true } return PromptWalletPassword() } // PromptWalletPassword shows the wallet password dialog and returns the entered password. // It is used by the boot sequence (before models are constructed). func PromptWalletPassword() (string, bool) { view := view.NewWalletPasswordDialogView() ctrl := NewWalletPasswordDialogController(view) return ctrl.Run() } ================================================ FILE: cmd/gtk/controller/tx_bond_dialog_controller.go ================================================ //go:build gtk package controller import ( "fmt" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" ) type TxBondDialogController struct { view *view.TxBondDialogView model *model.WalletModel } func NewTxBondDialogController( view *view.TxBondDialogView, model *model.WalletModel, ) *TxBondDialogController { return &TxBondDialogController{view: view, model: model} } func setHint(lbl *gtk.Label, hint string) { if hint == "" { lbl.SetMarkup("") return } lbl.SetMarkup(gtkutil.SmallGray(hint)) } func (c *TxBondDialogController) Run() { if info, err := c.model.WalletInfo(); err == nil { c.view.FeeEntry.SetText(fmt.Sprintf("%g", info.DefaultFee.ToPAC())) } for _, ai := range c.model.ListAddresses(crypto.AddressTypeBLSAccount, crypto.AddressTypeEd25519Account) { c.view.SenderCombo.Append(ai.Address, ai.Address) } for _, vi := range c.model.ListAddresses(crypto.AddressTypeValidator) { c.view.ReceiverCombo.Append(vi.Address, vi.Address) } c.view.SenderCombo.SetActive(0) c.view.ConnectSignals(map[string]any{ "on_sender_changed": c.onSenderChanged, "on_receiver_changed": c.onReceiverChanged, "on_fee_changed": c.onFeeChanged, "on_send": c.onSend, "on_cancel": c.onCancel, }) c.onSenderChanged() gtkutil.RunDialog(c.view.Dialog) } func (c *TxBondDialogController) onSenderChanged() { sender := c.view.SenderCombo.GetActiveID() if info := c.model.AddressInfo(sender); info != nil && info.Label != "" { setHint(c.view.SenderHint, fmt.Sprintf("label: %s", info.Label)) } else { setHint(c.view.SenderHint, "") } bal, err := c.model.Balance(sender) if err == nil { setHint(c.view.AmountHint, fmt.Sprintf("Account Balance: %s", bal)) } else { setHint(c.view.AmountHint, "") } } func (c *TxBondDialogController) onReceiverChanged() { receiverEntry, _ := c.view.ReceiverCombo.GetEntry() receiver := gtkutil.GetEntryText(receiverEntry) stake, err := c.model.Stake(receiver) hint := "" if err == nil { hint = fmt.Sprintf("stake: %s", stake) } if info := c.model.AddressInfo(receiver); info != nil && info.Label != "" { if hint != "" { hint += ", " } hint += "label: " + info.Label } setHint(c.view.ReceiverHint, hint) } func (c *TxBondDialogController) onFeeChanged() { _ = payload.TypeBond setHint(c.view.FeeHint, "") } func (c *TxBondDialogController) onSend() { sender := c.view.SenderCombo.GetActiveID() receiverEntry, _ := c.view.ReceiverCombo.GetEntry() receiver := gtkutil.GetEntryText(receiverEntry) publicKey := gtkutil.GetEntryText(c.view.PublicKeyEntry) amountStr := gtkutil.GetEntryText(c.view.AmountEntry) feeStr := gtkutil.GetEntryText(c.view.FeeEntry) memo := gtkutil.GetEntryText(c.view.MemoEntry) amt, err := amount.FromString(amountStr) if err != nil { gtkutil.ShowError(err) return } fee, err := amount.FromString(feeStr) if err != nil { gtkutil.ShowError(err) return } trx, err := c.model.MakeBondTx(sender, receiver, publicKey, amt, fee, memo) if err != nil { gtkutil.ShowError(err) return } msg := fmt.Sprintf(` 📝 Transaction Details: Type: Bond From: %s To: %s Amount: %s Fee: %s Memo: %s You are going to sign and broadcast this transaction. ⚠️ This action cannot be undone. Do you want to continue with this transaction?`, sender, receiver, amt, trx.Fee(), trx.Memo()) if !gtkutil.ShowQuestionDialog(c.view.Dialog, msg) { return } password, ok := PasswordProvider(c.model) if !ok { return } if err := c.model.SignTransaction(password, trx); err != nil { gtkutil.ShowError(err) return } txID, err := c.model.BroadcastTransaction(trx) if err != nil { gtkutil.ShowError(err) return } gtkutil.ShowInfoDialog(c.view.Dialog, fmt.Sprintf("✅ Transaction sent successfully!\n\n"+ "Transaction ID: %s", txID, txID)) c.view.Dialog.Close() } func (c *TxBondDialogController) onCancel() { c.view.Dialog.Close() } ================================================ FILE: cmd/gtk/controller/tx_transfer_dialog_controller.go ================================================ //go:build gtk package controller import ( "fmt" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" ) type TxTransferDialogController struct { view *view.TxTransferDialogView model *model.WalletModel } func NewTxTransferDialogController( view *view.TxTransferDialogView, model *model.WalletModel, ) *TxTransferDialogController { return &TxTransferDialogController{view: view, model: model} } func setHintLabel(lbl *gtk.Label, hint string) { if hint == "" { lbl.SetMarkup("") return } lbl.SetMarkup(gtkutil.SmallGray(hint)) } func (c *TxTransferDialogController) Run() { // Defaults if info, err := c.model.WalletInfo(); err == nil { c.view.FeeEntry.SetText(fmt.Sprintf("%g", info.DefaultFee.ToPAC())) } // Fill sender accounts for _, ai := range c.model.ListAddresses(crypto.AddressTypeBLSAccount, crypto.AddressTypeEd25519Account) { c.view.SenderCombo.Append(ai.Address, ai.Address) } c.view.SenderCombo.SetActive(0) c.view.ConnectSignals(map[string]any{ "on_sender_changed": c.onSenderChanged, "on_receiver_changed": c.onReceiverChanged, "on_fee_changed": c.onFeeChanged, "on_send": c.onSend, "on_cancel": c.onCancel, }) c.onSenderChanged() gtkutil.RunDialog(c.view.Dialog) } func (c *TxTransferDialogController) onSenderChanged() { sender := c.view.SenderCombo.GetActiveID() if info := c.model.AddressInfo(sender); info != nil && info.Label != "" { setHintLabel(c.view.SenderHint, fmt.Sprintf("label: %s", info.Label)) } else { setHintLabel(c.view.SenderHint, "") } bal, err := c.model.Balance(sender) if err == nil { setHintLabel(c.view.AmountHint, fmt.Sprintf("Account Balance: %s", bal)) } else { setHintLabel(c.view.AmountHint, "") } } func (c *TxTransferDialogController) onReceiverChanged() { receiver := gtkutil.GetEntryText(c.view.ReceiverEntry) if info := c.model.AddressInfo(receiver); info != nil && info.Label != "" { setHintLabel(c.view.ReceiverHint, fmt.Sprintf("label: %s", info.Label)) } else { setHintLabel(c.view.ReceiverHint, "") } } func (c *TxTransferDialogController) onFeeChanged() { // Placeholder (confirmation time estimation) _ = payload.TypeTransfer setHintLabel(c.view.FeeHint, "") } func (c *TxTransferDialogController) onSend() { sender := c.view.SenderCombo.GetActiveID() receiver := gtkutil.GetEntryText(c.view.ReceiverEntry) amountStr := gtkutil.GetEntryText(c.view.AmountEntry) feeStr := gtkutil.GetEntryText(c.view.FeeEntry) memo := gtkutil.GetEntryText(c.view.MemoEntry) amt, err := amount.FromString(amountStr) if err != nil { gtkutil.ShowError(err) return } fee, err := amount.FromString(feeStr) if err != nil { gtkutil.ShowError(err) return } trx, err := c.model.MakeTransferTx(sender, receiver, amt, fee, memo) if err != nil { gtkutil.ShowError(err) return } msg := fmt.Sprintf(` 📝 Transaction Details: Type: Transfer From: %s To: %s Amount: %s Fee: %s Memo: %s You are going to sign and broadcast this transaction. ⚠️ This action cannot be undone. Do you want to continue with this transaction?`, sender, receiver, amt, trx.Fee(), trx.Memo()) if !gtkutil.ShowQuestionDialog(c.view.Dialog, msg) { return } password, ok := PasswordProvider(c.model) if !ok { return } if err := c.model.SignTransaction(password, trx); err != nil { gtkutil.ShowError(err) return } txID, err := c.model.BroadcastTransaction(trx) if err != nil { gtkutil.ShowError(err) return } gtkutil.ShowInfoDialog(c.view.Dialog, fmt.Sprintf("✅ Transaction sent successfully!\n\n"+ "Transaction ID: %s", txID, txID)) c.view.Dialog.Close() } func (c *TxTransferDialogController) onCancel() { c.view.Dialog.Close() } ================================================ FILE: cmd/gtk/controller/tx_unbond_dialog_controller.go ================================================ //go:build gtk package controller import ( "fmt" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/crypto" ) type TxUnbondDialogController struct { view *view.TxUnbondDialogView model *model.WalletModel } func NewTxUnbondDialogController( view *view.TxUnbondDialogView, model *model.WalletModel, ) *TxUnbondDialogController { return &TxUnbondDialogController{view: view, model: model} } func (c *TxUnbondDialogController) Run() { for _, ai := range c.model.ListAddresses(crypto.AddressTypeValidator) { c.view.ValidatorCombo.Append(ai.Address, ai.Address) } c.view.ConnectSignals(map[string]any{ "on_validator_changed": c.onValidatorChanged, "on_send": c.onSend, "on_cancel": c.onCancel, }) c.onValidatorChanged() gtkutil.RunDialog(c.view.Dialog) } func (c *TxUnbondDialogController) onValidatorChanged() { receiverEntry, _ := c.view.ValidatorCombo.GetEntry() validator := gtkutil.GetEntryText(receiverEntry) stake, err := c.model.Stake(validator) hint := "" if err == nil { hint = fmt.Sprintf("stake: %s", stake) } if info := c.model.AddressInfo(validator); info != nil && info.Label != "" { if hint != "" { hint += ", " } hint += "label: " + info.Label } if hint == "" { c.view.ValidatorHint.SetMarkup("") } else { c.view.ValidatorHint.SetMarkup(gtkutil.SmallGray(hint)) } } func (c *TxUnbondDialogController) onSend() { validatorEntry, _ := c.view.ValidatorCombo.GetEntry() validatorAddr := gtkutil.GetEntryText(validatorEntry) memo := gtkutil.GetEntryText(c.view.MemoEntry) trx, err := c.model.MakeUnbondTx(validatorAddr, memo) if err != nil { gtkutil.ShowError(err) return } msg := fmt.Sprintf(` 📝 Transaction Details: Type: Unbond Validator: %s Fee: %s Memo: %s You are going to sign and broadcast this transaction. ⚠️ This action cannot be undone. Do you want to continue with this transaction?`, validatorAddr, trx.Fee(), trx.Memo()) if !gtkutil.ShowQuestionDialog(c.view.Dialog, msg) { return } password, ok := PasswordProvider(c.model) if !ok { return } if err := c.model.SignTransaction(password, trx); err != nil { gtkutil.ShowError(err) return } txID, err := c.model.BroadcastTransaction(trx) if err != nil { gtkutil.ShowError(err) return } gtkutil.ShowInfoDialog(c.view.Dialog, fmt.Sprintf("✅ Transaction sent successfully!\n\n"+ "Transaction ID: %s", txID, txID)) c.view.Dialog.Close() } func (c *TxUnbondDialogController) onCancel() { c.view.Dialog.Close() } ================================================ FILE: cmd/gtk/controller/tx_withdraw_dialog_controller.go ================================================ //go:build gtk package controller import ( "fmt" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" ) type TxWithdrawDialogController struct { view *view.TxWithdrawDialogView model *model.WalletModel } func NewTxWithdrawDialogController( view *view.TxWithdrawDialogView, model *model.WalletModel, ) *TxWithdrawDialogController { return &TxWithdrawDialogController{view: view, model: model} } func (c *TxWithdrawDialogController) Run() { c.applyDefaults() c.populateCombos() onCancel := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_sender_changed": func() { c.onSenderChanged() }, "on_receiver_changed": func() { c.onReceiverChanged() }, "on_fee_changed": func() { c.onFeeChanged() }, "on_send": func() { c.onSend() }, "on_cancel": onCancel, }) c.onSenderChanged() gtkutil.RunDialog(c.view.Dialog) } func (c *TxWithdrawDialogController) applyDefaults() { if info, err := c.model.WalletInfo(); err == nil { c.view.FeeEntry.SetText(fmt.Sprintf("%g", info.DefaultFee.ToPAC())) } } func (c *TxWithdrawDialogController) populateCombos() { for _, ai := range c.model.ListAddresses(crypto.AddressTypeValidator) { c.view.ValidatorCombo.Append(ai.Address, ai.Address) } c.view.ValidatorCombo.SetActive(0) for _, ai := range c.model.ListAddresses(crypto.AddressTypeBLSAccount, crypto.AddressTypeEd25519Account) { c.view.ReceiverCombo.Append(ai.Address, ai.Address) } } func (c *TxWithdrawDialogController) onSenderChanged() { sender := c.view.ValidatorCombo.GetActiveID() stake, err := c.model.Stake(sender) hint := "" if err == nil { hint = fmt.Sprintf("stake: %s", stake) } if info := c.model.AddressInfo(sender); info != nil && info.Label != "" { if hint != "" { hint += ", " } hint += "label: " + info.Label } setHintLabel(c.view.ValidatorHint, hint) if err == nil { setHintLabel(c.view.StakeHint, fmt.Sprintf("Validator Stake: %s", stake)) } else { setHintLabel(c.view.StakeHint, "") } } func (c *TxWithdrawDialogController) onReceiverChanged() { receiverEntry, _ := c.view.ReceiverCombo.GetEntry() receiver := gtkutil.GetEntryText(receiverEntry) if info := c.model.AddressInfo(receiver); info != nil && info.Label != "" { setHintLabel(c.view.ReceiverHint, fmt.Sprintf("label: %s", info.Label)) } else { setHintLabel(c.view.ReceiverHint, "") } } func (c *TxWithdrawDialogController) onFeeChanged() { _ = payload.TypeWithdraw setHintLabel(c.view.FeeHint, "") } func (c *TxWithdrawDialogController) onSend() { sender := c.view.ValidatorCombo.GetActiveID() receiverEntry, _ := c.view.ReceiverCombo.GetEntry() receiver := gtkutil.GetEntryText(receiverEntry) amountStr := gtkutil.GetEntryText(c.view.StakeEntry) feeStr := gtkutil.GetEntryText(c.view.FeeEntry) memo := gtkutil.GetEntryText(c.view.MemoEntry) amt, err := amount.FromString(amountStr) if err != nil { gtkutil.ShowError(err) return } fee, err := amount.FromString(feeStr) if err != nil { gtkutil.ShowError(err) return } trx, err := c.model.MakeWithdrawTx(sender, receiver, amt, fee, memo) if err != nil { gtkutil.ShowError(err) return } msg := fmt.Sprintf(` 📝 Transaction Details: Type: Withdraw From: %s To: %s Amount: %s Fee: %s Memo: %s You are going to sign and broadcast this transaction. ⚠️ This action cannot be undone. Do you want to continue with this transaction?`, sender, receiver, amt, trx.Fee(), trx.Memo()) if !gtkutil.ShowQuestionDialog(c.view.Dialog, msg) { return } password, ok := PasswordProvider(c.model) if !ok { return } if err := c.model.SignTransaction(password, trx); err != nil { gtkutil.ShowError(err) return } txID, err := c.model.BroadcastTransaction(trx) if err != nil { gtkutil.ShowError(err) return } gtkutil.ShowInfoDialog(c.view.Dialog, fmt.Sprintf("✅ Transaction sent successfully!\n\n"+ "Transaction ID: %s", txID, txID)) c.view.Dialog.Close() } ================================================ FILE: cmd/gtk/controller/validator_widget_controller.go ================================================ //go:build gtk package controller import ( "context" "strconv" "time" "github.com/ezex-io/gopkg/scheduler" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/types/amount" ) type ValidatorWidgetController struct { view *view.ValidatorWidgetView model *model.ValidatorModel } func NewValidatorWidgetController( view *view.ValidatorWidgetView, model *model.ValidatorModel, ) *ValidatorWidgetController { return &ValidatorWidgetController{view: view, model: model} } func (c *ValidatorWidgetController) BuildView(ctx context.Context) error { scheduler.Every(10*time.Second).Do(ctx, func(context.Context) { c.refresh() }) // Initial refresh. c.refresh() return nil } func (c *ValidatorWidgetController) refresh() { vals, err := c.model.Validators() if err != nil { return } gtkutil.IdleAddAsync(func() { c.view.ClearRows() for i, val := range vals { stakeStr := amount.Amount(val.GetStake()).String() c.view.AppendRow( []int{0, 1, 2, 3, 4, 5, 6, 7}, []any{ strconv.Itoa(i + 1), val.GetAddress(), strconv.Itoa(int(val.GetNumber())), stakeStr, strconv.Itoa(int(val.GetLastBondingHeight())), strconv.Itoa(int(val.GetLastSortitionHeight())), strconv.Itoa(int(val.GetUnbondingHeight())), gtkutil.AvailabilityScorePercent(val.GetAvailabilityScore()), }, ) } }) } ================================================ FILE: cmd/gtk/controller/wallet_change_password_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" ) type WalletChangePasswordDialogController struct { view *view.WalletChangePasswordDialogView model *model.WalletModel } func NewWalletChangePasswordDialogController( view *view.WalletChangePasswordDialogView, model *model.WalletModel, ) *WalletChangePasswordDialogController { return &WalletChangePasswordDialogController{view: view, model: model} } func (c *WalletChangePasswordDialogController) Run() { if !c.model.IsEncrypted() { c.view.OldPasswordEntry.SetVisible(false) c.view.OldPasswordLabel.SetVisible(false) } onOk := func() { oldPassword := gtkutil.GetEntryText(c.view.OldPasswordEntry) newPassword := gtkutil.GetEntryText(c.view.NewPasswordEntry) repeatPassword := gtkutil.GetEntryText(c.view.RepeatEntry) if newPassword != repeatPassword { gtkutil.ShowWarningDialog(c.view.Dialog, "Passwords do not match") return } if err := c.model.UpdatePassword(oldPassword, newPassword); err != nil { gtkutil.ShowError(err) return } c.view.Dialog.Close() } onCancel := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_ok": onOk, "on_cancel": onCancel, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/wallet_create_address_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/crypto" ) type WalletCreateAddressDialogController struct { view *view.WalletCreateAddressDialogView model *model.WalletModel } func NewWalletCreateAddressDialogController( view *view.WalletCreateAddressDialogView, model *model.WalletModel, ) *WalletCreateAddressDialogController { return &WalletCreateAddressDialogController{view: view, model: model} } func (c *WalletCreateAddressDialogController) Run() { combo := c.view.AddressTypeCombo combo.Append(crypto.AddressTypeEd25519Account.String(), "ED25519 Account") combo.Append(crypto.AddressTypeBLSAccount.String(), "BLS Account") combo.Append(crypto.AddressTypeValidator.String(), "Validator") combo.SetActive(0) onOk := func() { c.view.ButtonOK.SetSensitive(false) defer c.view.ButtonOK.SetSensitive(true) label := gtkutil.GetEntryText(c.view.LabelEntry) typ := combo.GetActiveID() var err error switch typ { case crypto.AddressTypeEd25519Account.String(): password, ok := PasswordProvider(c.model) if !ok { return } _, err = c.model.NewAddress( crypto.AddressTypeEd25519Account, label, password, ) case crypto.AddressTypeBLSAccount.String(): _, err = c.model.NewAddress(crypto.AddressTypeBLSAccount, label, "") case crypto.AddressTypeValidator.String(): _, err = c.model.NewAddress(crypto.AddressTypeValidator, label, "") default: return } if err != nil { gtkutil.ShowError(err) return } c.view.Dialog.Close() } onCancel := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_ok": onOk, "on_cancel": onCancel, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/wallet_default_fee_dialog_controller.go ================================================ //go:build gtk package controller import ( "fmt" "strings" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/types/amount" ) type WalletDefaultFeeDialogController struct { view *view.WalletDefaultFeeDialogView model *model.WalletModel } func NewWalletDefaultFeeDialogController( view *view.WalletDefaultFeeDialogView, model *model.WalletModel, ) *WalletDefaultFeeDialogController { return &WalletDefaultFeeDialogController{view: view, model: model} } func (c *WalletDefaultFeeDialogController) Run() { info, err := c.model.WalletInfo() if err != nil { gtkutil.ShowErrorDialog(c.view.Dialog, fmt.Sprintf("Failed to get wallet info: %v", err)) return } currentFee := info.DefaultFee c.view.CurrentFeeLabel.SetText(currentFee.String()) c.view.FeeEntry.SetText(strings.ReplaceAll(currentFee.String(), " PAC", "")) onOk := func() { feeStr := gtkutil.GetEntryText(c.view.FeeEntry) feeAmount, err := amount.FromString(feeStr) if err != nil { gtkutil.ShowErrorDialog(c.view.Dialog, fmt.Sprintf("Invalid fee amount: %v", err)) return } if err := c.model.SetDefaultFee(feeAmount); err != nil { gtkutil.ShowErrorDialog(c.view.Dialog, fmt.Sprintf("Failed to set default fee: %v", err)) return } c.view.Dialog.Close() } onCancel := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_ok": onOk, "on_cancel": onCancel, }) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/wallet_password_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/view" ) type WalletPasswordDialogController struct { view *view.WalletPasswordDialogView } func NewWalletPasswordDialogController( view *view.WalletPasswordDialogView, ) *WalletPasswordDialogController { return &WalletPasswordDialogController{view: view} } func (c *WalletPasswordDialogController) Run() (string, bool) { password := "" ok := false onOk := func() { password = gtkutil.GetEntryText(c.view.PasswordEntry) ok = true c.view.Dialog.Close() } andClose := func() { c.view.Dialog.Close() } c.view.ConnectSignals(map[string]any{ "on_ok": onOk, "on_cancel": andClose, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) return password, ok } ================================================ FILE: cmd/gtk/controller/wallet_seed_dialog_controller.go ================================================ //go:build gtk package controller import ( "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" ) type WalletSeedDialogController struct { view *view.WalletSeedDialogView model *model.WalletModel } func NewWalletSeedDialogController( view *view.WalletSeedDialogView, model *model.WalletModel, ) *WalletSeedDialogController { return &WalletSeedDialogController{view: view, model: model} } func (c *WalletSeedDialogController) Run() { password, ok := PasswordProvider(c.model) if !ok { return } seed, err := c.model.Mnemonic(password) if err != nil { gtkutil.ShowError(err) return } gtkutil.SetTextViewContent(c.view.TextView, seed) c.view.ConnectSignals(map[string]any{ "on_close": func() { c.view.Dialog.Close() }, }) c.view.Dialog.SetModal(true) gtkutil.RunDialog(c.view.Dialog) } ================================================ FILE: cmd/gtk/controller/wallet_widget_controller.go ================================================ //go:build gtk package controller import ( "context" "strconv" "time" "github.com/ezex-io/gopkg/scheduler" "github.com/gotk3/gotk3/gdk" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/model" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/wallet/types" ) type WalletWidgetController struct { view *view.WalletWidgetView model *model.WalletModel txSkip int txCount int } func NewWalletWidgetController(view *view.WalletWidgetView, model *model.WalletModel) *WalletWidgetController { return &WalletWidgetController{ view: view, model: model, txCount: 20, } } func (c *WalletWidgetController) BuildView(ctx context.Context, nav *Navigator) error { info, err := c.model.WalletInfo() gtkutil.IdleAddSync(func() { if err == nil { c.view.LabelName.SetText(c.model.WalletName()) c.view.LabelDriver.SetText(info.Driver) c.view.LabelCreatedAt.SetText(info.CreatedAt.Format(time.RFC1123)) c.view.LabelLocation.SetText(info.Path) } c.view.ConnectSignals(map[string]any{ "on_new_address": nav.ShowWalletNewAddress, "on_set_default_fee": nav.ShowWalletSetDefaultFee, "on_change_password": nav.ShowWalletChangePassword, "on_show_seed": nav.ShowWalletShowSeed, "on_address_refresh": c.RefreshAddresses, "on_tx_refresh": c.RefreshTransactions, "on_tx_prev": c.prevTransactionsPage, "on_tx_next": c.nextTransactionsPage, }) // Context menu actions. c.view.MenuItemUpdateLabel.Connect("activate", func(_ *gtk.MenuItem) { addr := c.selectedAddress() if addr != "" { c.ShowUpdateLabel(addr) } }) c.view.MenuItemDetails.Connect("activate", func(_ *gtk.MenuItem) { addr := c.selectedAddress() if addr != "" { c.ShowAddressDetails(addr) } }) c.view.MenuItemPrivateKey.Connect("activate", func(_ *gtk.MenuItem) { addr := c.selectedAddress() if addr != "" { c.ShowPrivateKey(addr) } }) // Right-click popup. c.view.TreeViewWallet.Connect("button-press-event", func(_ *gtk.TreeView, event *gdk.Event) bool { eventButton := gdk.EventButtonNewFromEvent(event) if eventButton.Type() == gdk.EVENT_BUTTON_PRESS && eventButton.Button() == gdk.BUTTON_SECONDARY { c.view.ContextMenu.PopupAtPointer(event) } return false }) // Double-click opens details. c.view.TreeViewWallet.Connect("row-activated", func(_ *gtk.TreeView, _ *gtk.TreePath, _ *gtk.TreeViewColumn) { addr := c.selectedAddress() if addr != "" { c.ShowAddressDetails(addr) } }) totalBalance1, _ := c.model.TotalBalance() scheduler.Every(15*time.Second).Do(ctx, func(context.Context) { totalBalance2, _ := c.model.TotalBalance() if totalBalance1 != totalBalance2 { c.Refresh() totalBalance1 = totalBalance2 } }) }) c.Refresh() return nil } func (c *WalletWidgetController) selectedAddress() string { addr, ok, err := c.view.SelectionAddress(1) if err != nil || !ok { return "" } return addr } // getDirectionTextWithIcon returns formatted text with icon for the transaction direction. func getDirectionTextWithIcon(dir types.TxDirection) string { switch dir { case types.TxDirectionIncoming: return "incoming ↘" case types.TxDirectionOutgoing: return "outgoing ↗" case types.TxDirectionAny: return "any" default: return "unknown" } } func (c *WalletWidgetController) Refresh() { c.RefreshInfo() c.RefreshAddresses() c.RefreshTransactions() } func (c *WalletWidgetController) RefreshInfo() { // Update info lines. balance, _ := c.model.TotalBalance() stake, _ := c.model.TotalStake() balanceStr := balance.String() stakeStr := stake.String() info, err := c.model.WalletInfo() if err != nil { return } gtkutil.IdleAddSync(func() { c.view.LabelEncrypted.SetText(gtkutil.YesNo(info.Encrypted)) c.view.LabelTotalBalance.SetText(balanceStr) c.view.LabelTotalStake.SetText(stakeStr) c.view.LabelDefaultFee.SetText(info.DefaultFee.String()) }) } func (c *WalletWidgetController) RefreshAddresses() { rows := c.model.AddressRows() gtkutil.IdleAddSync(func() { c.view.ClearRows() for _, item := range rows { c.view.AppendRow( []int{0, 1, 2, 3, 4}, []any{ strconv.Itoa(item.No), item.Address, gtkutil.ImportedLabel(item.Label, item.Imported), item.Balance.String(), item.Stake.String(), }, ) } }) } func (c *WalletWidgetController) RefreshTransactions() { trxs := c.model.Transactions(c.txCount, c.txSkip) hasNext := len(trxs) == c.txCount gtkutil.IdleAddSync(func() { c.view.ClearTxRows() for _, trx := range trxs { c.view.AppendTxRow( []int{0, 1, 2, 3, 4, 5, 6, 7, 8}, []any{ trx.No, cmd.ShortHash(trx.TxId), cmd.ShortAddress(trx.Sender), cmd.ShortAddress(trx.Receiver), payload.Type(trx.PayloadType).String(), amount.Amount(trx.Amount).String(), getDirectionTextWithIcon(types.TxDirection(trx.Direction)), types.TransactionStatus(trx.Status).String(), trx.Comment, }, ) } c.view.SetTxPager(c.txSkip > 0, hasNext) }) } func (c *WalletWidgetController) ShowUpdateLabel(address string) { dlgView := view.NewAddressLabelDialogView() dlgCtrl := NewAddressLabelDialogController(dlgView, c.model) dlgCtrl.Run(address) c.RefreshAddresses() } func (c *WalletWidgetController) ShowAddressDetails(address string) { dlgView := view.NewAddressDetailsDialogView() dlgCtrl := NewAddressDetailsDialogController(dlgView, c.model) dlgCtrl.Run(address) } func (c *WalletWidgetController) ShowPrivateKey(address string) { dlgView := view.NewAddressPrivateKeyDialogView() dlgCtrl := NewAddressPrivateKeyDialogController(dlgView, c.model) dlgCtrl.Run(address) } func (c *WalletWidgetController) prevTransactionsPage() { if c.txSkip >= c.txCount { c.txSkip -= c.txCount } else { c.txSkip = 0 } c.RefreshTransactions() } func (c *WalletWidgetController) nextTransactionsPage() { c.txSkip += c.txCount c.RefreshTransactions() } ================================================ FILE: cmd/gtk/gtkutil/format.go ================================================ //go:build gtk package gtkutil import ( "fmt" "strings" ) func escapeMarkup(text string) string { // Minimal escaping for Pango markup contexts. r := strings.NewReplacer( "&", "&", "<", "<", ">", ">", "\"", """, "'", "'", ) return r.Replace(text) } // SmallGray wraps text in a small gray Pango markup span. func SmallGray(text string) string { return fmt.Sprintf("%s", escapeMarkup(text)) } // ImportedLabel appends the imported suffix if needed. func ImportedLabel(label string, imported bool) string { if !imported { return label } if strings.TrimSpace(label) == "" { return "(Imported)" } return label + " (Imported)" } func YesNo(v bool) string { if v { return "Yes" } return "No" } // AvailabilityScorePercent formats an availability score (0–1) as a percentage string with 2 decimal places. func AvailabilityScorePercent(score float64) string { return fmt.Sprintf("%.2f%%", score*100) } ================================================ FILE: cmd/gtk/gtkutil/format_test.go ================================================ //go:build gtk package gtkutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestSmallGray_EscapesMarkup(t *testing.T) { got := SmallGray(`a 0 && options.height > 0 { resized, err := pixbuf.ScaleSimple(options.width, options.height, gdk.INTERP_NEAREST) if err != nil { return nil, err } return resized, nil } return pixbuf, nil } // ImageFromPixbuf creates a gtk.Image from a pixbuf and applies a marginEnd. // If pixbuf is nil, it returns an empty gtk.Image. func ImageFromPixbuf(pixbuf *gdk.Pixbuf) *gtk.Image { image, err := gtk.ImageNewFromPixbuf(pixbuf) if err != nil { return nil } image.ShowAll() return image } func GetTextViewContent(tv *gtk.TextView) string { buf, _ := tv.GetBuffer() startIter, endIter := buf.GetBounds() content, err := buf.GetText(startIter, endIter, true) if err != nil { return "" } return content } func SetTextViewContent(tv *gtk.TextView, content string) { buf, err := tv.GetBuffer() if err != nil { return } buf.SetText(content) } // OpenURLInBrowser opens a URL in the OS default browser. func OpenURLInBrowser(address string) error { var cmd string args := make([]string, 0, 2) addr, err := url.Parse(address) if err != nil { return err } switch addr.Scheme { case "http", "https": default: return errors.New("address scheme is invalid") } switch runtime.GOOS { case "windows": cmd = "cmd" args = []string{"/c", "start"} case "darwin": cmd = "open" default: // "linux", "freebsd", "openbsd", "netbsd" cmd = "xdg-open" } args = append(args, address) return exec.CommandContext(context.Background(), cmd, args...).Start() } func BuildExtendedEntry(builder *gtk.Builder, overlayID string) *gtk.Entry { obj, err := builder.GetObject(overlayID) FatalErrorCheck(err) overlay := obj.(*gtk.Overlay) // Create a new Entry entry, err := gtk.EntryNew() FatalErrorCheck(err) entry.SetCanFocus(true) entry.SetHExpand(true) entry.SetEditable(false) SetCSSClass(&entry.Widget, "copyable_entry") // Create a new Button button, err := gtk.ButtonNewFromIconName("edit-copy-symbolic", gtk.ICON_SIZE_BUTTON) FatalErrorCheck(err) button.SetTooltipText("Copy to Clipboard") // TODO: Not working! button.SetHAlign(gtk.ALIGN_END) button.SetVAlign(gtk.ALIGN_CENTER) button.SetHExpand(false) button.SetVExpand(false) button.SetBorderWidth(0) SetCSSClass(&button.Widget, "inline_button") // Set the click event for the Button button.Connect("clicked", func() { buffer := GetEntryText(entry) clipboard, _ := gtk.ClipboardGet(gdk.SELECTION_CLIPBOARD) clipboard.SetText(buffer) }) overlay.Add(entry) overlay.AddOverlay(button) overlay.ShowAll() // Ensure all child widgets are shown return entry } func SetCSSClass(widget *gtk.Widget, name string) { styleContext, err := widget.GetStyleContext() FatalErrorCheck(err) styleContext.AddClass(name) } func RunDialog(dlg *gtk.Dialog) gtk.ResponseType { return IdleAddSyncT(func() gtk.ResponseType { response := dlg.Run() // Destroy should be done after the dialog is closed // Read more here: https://docs.gtk.org/gtk3/method.Dialog.run.html dlg.Destroy() return response }) } func ComboBoxActiveValue(combo *gtk.ComboBox) int { iter, err := combo.GetActiveIter() FatalErrorCheck(err) model, err := combo.GetModel() FatalErrorCheck(err) val, err := model.ToTreeModel().GetValue(iter, 0) FatalErrorCheck(err) valueInterface, err := val.GoValue() FatalErrorCheck(err) return valueInterface.(int) } func GetEntryText(entry *gtk.Entry) string { txt, err := entry.GetText() FatalErrorCheck(err) return txt } // Color represents different text colors for UI elements. type Color int const ( ColorRed Color = iota ColorGreen ColorBlue ColorYellow ColorOrange ColorPurple ColorGray ) // getColorHex returns the hex color code for the given Color enum. func getColorHex(color Color) string { switch color { case ColorRed: return "#FF0000" case ColorGreen: return "#00FF00" case ColorBlue: return "#0000FF" case ColorYellow: return "#FFFF00" case ColorOrange: return "#FFA500" case ColorPurple: return "#800080" case ColorGray: return "#808080" default: return "#000000" // Default to black } } func SetColoredText(label *gtk.Label, str string, color Color) { colorHex := getColorHex(color) formattedText := fmt.Sprintf("%s", colorHex, str) label.SetMarkup(formattedText) } func IdleAddAsync(fun func()) { go func() { glib.IdleAdd(func() bool { fun() return false }) }() } func IdleAddSync(fun func()) { IdleAddSyncT(func() bool { fun() return false }) } func IdleAddSyncT[T any](fun func() T) T { res, _ := IdleAddSyncTT(func() (T, bool) { return fun(), false }) return res } func IdleAddSyncTT[T1, T2 any](fun func() (T1, T2)) (T1, T2) { done := make(chan bool, 1) var va1l T1 var val2 T2 go func() { glib.IdleAdd(func() bool { va1l, val2 = fun() done <- true return false }) }() glibContext := glib.MainContextDefault() for { select { case <-done: return va1l, val2 default: time.Sleep(10 * time.Millisecond) glibContext.Iteration(false) } } } func Logf(msg string, args ...any) { log.Printf("(Go Routine ID %d) %s", GoroutineID(), fmt.Sprintf(msg, args...)) } func GoroutineID() int64 { var buf [64]byte n := runtime.Stack(buf[:], false) var id int64 _, _ = fmt.Sscanf(string(buf[:n]), "goroutine %d ", &id) return id } ================================================ FILE: cmd/gtk/gtkutil/gtkutil_test.go ================================================ //go:build gtk package gtkutil ================================================ FILE: cmd/gtk/main.go ================================================ //go:build gtk package main import ( "context" "crypto/tls" "flag" "os" "path/filepath" "runtime" "sync" "time" "github.com/ezex-io/gopkg/signal" "github.com/gofrs/flock" "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd" gtkapp "github.com/pactus-project/pactus/cmd/gtk/app" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/controller" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/cmd/gtk/view" "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/node" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/version" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" ) const appID = "com.github.pactus-project.pactus.pactus-gui" var ( workingDirOpt *string passwordOpt *string testnetOpt *bool grpcAddrOpt *string grpcInsecureOpt *bool ) func init() { workingDirOpt = flag.String("working-dir", cmd.PactusDefaultHomeDir(), "working directory path") passwordOpt = flag.String("password", "", "wallet password") testnetOpt = flag.Bool("testnet", false, "initializing for the testnet") grpcAddrOpt = flag.String("grpc-addr", "", "connect to remote gRPC server instead of starting local node") grpcInsecureOpt = flag.Bool("grpc-insecure", false, "use insecure connection to gRPC server") version.NodeAgent.AppType = "gui" if runtime.GOOS == "darwin" { // Changing the PANGOCAIRO_BACKEND is necessary on MacOS to render emoji _ = os.Setenv("PANGOCAIRO_BACKEND", "fontconfig") } gtk.Init(nil) } //nolint:gocognit // needs refactoring func main() { flag.Parse() gtkutil.Logf("Starting Pactus GUI") // The gtk should run on main thread. runtime.UnlockOSThread() runtime.LockOSThread() gtkutil.Logf("Locking main thread") // Create a new app. app, err := gtk.ApplicationNew(appID, glib.APPLICATION_NON_UNIQUE) gtkutil.FatalErrorCheck(err) settings, err := gtk.SettingsGetDefault() gtkutil.FatalErrorCheck(err) err = settings.Object.Set("gtk-application-prefer-dark-theme", true) gtkutil.FatalErrorCheck(err) assets.InitAssets() workingDir, err := filepath.Abs(*workingDirOpt) if err != nil { gtkutil.Logf("Aborted! %v", err) return } ctx, cancel := context.WithCancel(context.Background()) var fileLock *flock.Flock //nolint:nestif // complexity acceptable here if *grpcAddrOpt == "" { // If node is not initialized yet if util.IsDirNotExistsOrEmpty(workingDir) { network := genesis.Mainnet if *testnetOpt { network = genesis.Testnet } if !startupAssistant(ctx, workingDir, network) { return } } // Define the lock file path lockFilePath := filepath.Join(workingDir, ".pactus.lock") fileLock = flock.New(lockFilePath) locked, err := fileLock.TryLock() gtkutil.FatalErrorCheck(err) if !locked { gtkutil.Logf("Could not lock '%s', another instance is running?", lockFilePath) return } } var guiNode *node.Node // Connect function to application startup event, this is not required. app.Connect("startup", func() { gtkutil.Logf("application startup") }) var gui *gtkapp.GUI var grpcConn *grpc.ClientConn activateOnce := new(sync.Once) shutdownOnce := new(sync.Once) shutdown := func() { shutdownOnce.Do(func() { cancel() if grpcConn != nil { _ = grpcConn.Close() } if gui != nil { gui.Cleanup() } if guiNode != nil { guiNode.Stop() } if fileLock != nil { _ = fileLock.Unlock() } }) } // Connect function to application shutdown event, this is not required. app.Connect("shutdown", func() { gtkutil.Logf("Application shutdown") shutdown() }) // Connect function to application activate event app.Connect("activate", func() { activateOnce.Do(func() { gtkutil.Logf("application activate") splash := view.NewSplashWindow(app) splash.SetVersion(version.NodeVersion().StringWithAlias()) gtk.WindowSetAutoStartupNotification(false) splash.ShowAll() gtk.WindowSetAutoStartupNotification(true) app.AddWindow(splash.Window()) notify := func(msg string) { gtkutil.Logf("Splash msg: %s", msg) gtkutil.IdleAddAsync(func() { splash.SetStatus(msg) }) } go func() { var grpcAddr string var grpcInsecure bool if *grpcAddrOpt == "" { reportStatus(notify, "Starting local node...") time.Sleep(1 * time.Second) guiNode, err = newNode(ctx, workingDir, notify) gtkutil.FatalErrorCheck(err) grpcAddr = guiNode.GRPC().Address() grpcInsecure = true } else { reportStatus(notify, "Connecting to remote node...") time.Sleep(1 * time.Second) grpcAddr = *grpcAddrOpt grpcInsecure = *grpcInsecureOpt } grpcConn, err = newRemoteGRPCConn(grpcAddr, grpcInsecure) gtkutil.FatalErrorCheck(err) var connectionLabel, connectionValue string if *grpcAddrOpt == "" { connectionLabel = "📁 Working directory" connectionValue = workingDir } else { connectionLabel = "📡 Remote address" connectionValue = *grpcAddrOpt } gui, err = gtkapp.Run(ctx, grpcConn, app, notify, connectionLabel, connectionValue) gtkutil.FatalErrorCheck(err) gtkutil.IdleAddSync(func() { splash.Destroy() }) }() }) }) signal.HandleInterrupt(func() { gtkutil.Logf("Exiting...") gtkutil.IdleAddSync(func() { shutdown() }) }) // Launch the application os.Exit(app.Run(nil)) } type statusReporter func(string) func reportStatus(cb statusReporter, msg string) { if cb != nil { cb(msg) } } // newRemoteGRPCConn creates a gRPC client for a remote URL. func newRemoteGRPCConn(addr string, insecureCredentials bool) (*grpc.ClientConn, error) { target, prefix, err := util.ParseGRPCAddr(addr, insecureCredentials) if err != nil { return nil, err } var creds credentials.TransportCredentials if insecureCredentials { gtkutil.Logf("Connecting to node using insecure credentials. target: %s, prefix: %s", target, prefix) creds = insecure.NewCredentials() } else { gtkutil.Logf("Connecting to node using TLS. target: %s, prefix: %s", target, prefix) creds = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12}) } opts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithUnaryInterceptor(methodPrefixUnaryInterceptor(prefix)), grpc.WithStreamInterceptor(methodPrefixStreamInterceptor(prefix)), } return grpc.NewClient(target, opts...) } func methodPrefixUnaryInterceptor(prefix string) grpc.UnaryClientInterceptor { return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, ) error { return invoker(ctx, prefix+method, req, reply, cc, opts...) } } func methodPrefixStreamInterceptor(prefix string) grpc.StreamClientInterceptor { return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption, ) (grpc.ClientStream, error) { return streamer(ctx, desc, cc, prefix+method, opts...) } } func newNode(ctx context.Context, workingDir string, statusCb statusReporter) (*node.Node, error) { // change working directory if err := os.Chdir(workingDir); err != nil { gtkutil.Logf("Aborted! Unable to changes working directory. %v", err) return nil, err } reportStatus(statusCb, "Opening wallet...") passwordFetcher := func() (string, bool) { gtkutil.Logf("Fetching wallet password") if *passwordOpt != "" { return *passwordOpt, true } return gtkutil.IdleAddSyncTT(controller.PromptWalletPassword) } configModifier := func(cfg *config.Config) *config.Config { if !cfg.GRPC.Enable { cfg.GRPC.Enable = true cfg.GRPC.EnableWallet = true cfg.GRPC.Listen = "localhost:0" } return cfg } reportStatus(statusCb, "Starting node services...") n, err := cmd.StartNode(ctx, workingDir, passwordFetcher, configModifier) if err != nil { return nil, err } return n, nil } ================================================ FILE: cmd/gtk/model/committee_model.go ================================================ //go:build gtk package model import ( "context" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) // CommitteeModel holds blockchain gRPC client and provides committee data // for the committee widget (size, power, total power, validators, protocol versions). type CommitteeModel struct { ctx context.Context blockchainClient pactus.BlockchainClient } // NewCommitteeModel creates a CommitteeModel that uses gRPC to fetch committee data. func NewCommitteeModel( ctx context.Context, blockchainClient pactus.BlockchainClient, ) *CommitteeModel { return &CommitteeModel{ ctx: ctx, blockchainClient: blockchainClient, } } // GetCommitteeInfo returns current committee info from gRPC. func (m *CommitteeModel) GetCommitteeInfo() (*pactus.GetCommitteeInfoResponse, error) { return m.blockchainClient.GetCommitteeInfo(m.ctx, &pactus.GetCommitteeInfoRequest{}) } ================================================ FILE: cmd/gtk/model/network_model.go ================================================ //go:build gtk package model import ( "context" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) // NetworkModel holds network gRPC client and provides network and peer data // for the network widget. type NetworkModel struct { ctx context.Context networkClient pactus.NetworkClient } // NewNetworkModel creates a NetworkModel that uses gRPC to fetch network data. func NewNetworkModel( ctx context.Context, networkClient pactus.NetworkClient, ) *NetworkModel { return &NetworkModel{ ctx: ctx, networkClient: networkClient, } } // GetNetworkInfo returns overall network info from gRPC. func (m *NetworkModel) GetNetworkInfo() (*pactus.GetNetworkInfoResponse, error) { return m.networkClient.GetNetworkInfo(m.ctx, &pactus.GetNetworkInfoRequest{}) } // ListPeers returns active (connected) peers only. Set includeDisconnected true to include disconnected. func (m *NetworkModel) ListPeers(includeDisconnected bool) (*pactus.ListPeersResponse, error) { return m.networkClient.ListPeers(m.ctx, &pactus.ListPeersRequest{ IncludeDisconnected: includeDisconnected, }) } ================================================ FILE: cmd/gtk/model/node_model.go ================================================ //go:build gtk package model import ( "context" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) // NodeModel holds blockchain and network gRPC clients and provides node/chain // data for the node widget. No controller uses node.Node; they use this model. type NodeModel struct { ctx context.Context blockchainClient pactus.BlockchainClient networkClient pactus.NetworkClient } // NewNodeModel creates a NodeModel that uses gRPC to fetch node and chain data. func NewNodeModel( ctx context.Context, blockchainClient pactus.BlockchainClient, networkClient pactus.NetworkClient, ) *NodeModel { return &NodeModel{ ctx: ctx, blockchainClient: blockchainClient, networkClient: networkClient, } } // GetBlockchainInfo returns current blockchain info. func (m *NodeModel) GetBlockchainInfo() (*pactus.GetBlockchainInfoResponse, error) { return m.blockchainClient.GetBlockchainInfo(m.ctx, &pactus.GetBlockchainInfoRequest{}) } // GetCommitteeInfo returns current committee info. func (m *NodeModel) GetCommitteeInfo() (*pactus.GetCommitteeInfoResponse, error) { return m.blockchainClient.GetCommitteeInfo(m.ctx, &pactus.GetCommitteeInfoRequest{}) } // GetConsensusInfo returns consensus instances (used to determine "in committee"). func (m *NodeModel) GetConsensusInfo() (*pactus.GetConsensusInfoResponse, error) { return m.blockchainClient.GetConsensusInfo(m.ctx, &pactus.GetConsensusInfoRequest{}) } // GetNodeInfo returns this node's info (moniker, peer ID, reachability, clock offset, connections). func (m *NodeModel) GetNodeInfo() (*pactus.GetNodeInfoResponse, error) { return m.networkClient.GetNodeInfo(m.ctx, &pactus.GetNodeInfoRequest{}) } ================================================ FILE: cmd/gtk/model/validator_model.go ================================================ //go:build gtk package model import ( "context" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) // ValidatorModel holds blockchain gRPC client and provides validator data // for the validator widget (this node's consensus instances). type ValidatorModel struct { ctx context.Context blockchainClient pactus.BlockchainClient } // NewValidatorModel creates a ValidatorModel that uses gRPC to fetch validator data. func NewValidatorModel( ctx context.Context, blockchainClient pactus.BlockchainClient, ) *ValidatorModel { return &ValidatorModel{ ctx: ctx, blockchainClient: blockchainClient, } } // Validators returns validator info for this node's consensus instances. // It calls GetConsensusInfo to get instance addresses, then GetValidator for each. func (m *ValidatorModel) Validators() ([]*pactus.ValidatorInfo, error) { res, err := m.blockchainClient.GetConsensusInfo(m.ctx, &pactus.GetConsensusInfoRequest{}) if err != nil { return nil, err } vals := make([]*pactus.ValidatorInfo, 0, len(res.Instances)) for _, inst := range res.Instances { vres, err := m.blockchainClient.GetValidator(m.ctx, &pactus.GetValidatorRequest{ Address: inst.Address, }) if err != nil { continue // skip inactive validator } vals = append(vals, vres.Validator) } return vals, nil } ================================================ FILE: cmd/gtk/model/wallet_model.go ================================================ //go:build gtk package model import ( "context" "encoding/hex" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/wallet/types" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) type WalletModel struct { ctx context.Context walletClient pactus.WalletClient transactionClient pactus.TransactionClient blockchainClient pactus.BlockchainClient walletName string } // AddressRow is a UI-friendly but UI-agnostic representation of an address entry. // Formatting (strings/markup) should be done by presenters/controllers, not here. type AddressRow struct { No int Address string Label string Path string Imported bool Balance amount.Amount Stake amount.Amount } func NewWalletModel( ctx context.Context, walletClient pactus.WalletClient, transactionClient pactus.TransactionClient, blockchainClient pactus.BlockchainClient, walletName string, ) *WalletModel { return &WalletModel{ ctx: ctx, walletClient: walletClient, transactionClient: transactionClient, blockchainClient: blockchainClient, walletName: walletName, } } // WalletName returns the display name used in the UI. func (model *WalletModel) WalletName() string { return model.walletName } func (model *WalletModel) IsEncrypted() bool { info, err := model.walletClient.GetWalletInfo(model.ctx, &pactus.GetWalletInfoRequest{ WalletName: model.walletName, }) if err != nil { return false } return info.Encrypted } func (model *WalletModel) WalletInfo() (*types.WalletInfo, error) { info, err := model.walletClient.GetWalletInfo(model.ctx, &pactus.GetWalletInfoRequest{ WalletName: model.walletName, }) if err != nil { return nil, err } chainType := genesis.Localnet switch info.Network { case "Mainnet": chainType = genesis.Mainnet case "Testnet": chainType = genesis.Testnet } return &types.WalletInfo{ Path: info.Path, Encrypted: info.Encrypted, UUID: info.Uuid, Network: chainType, DefaultFee: amount.Amount(info.DefaultFee), }, nil } func (model *WalletModel) TotalBalance() (amount.Amount, error) { res, err := model.walletClient.GetTotalBalance(model.ctx, &pactus.GetTotalBalanceRequest{ WalletName: model.walletName, }) if err != nil { return 0, err } return amount.Amount(res.TotalBalance), nil } func (model *WalletModel) TotalStake() (amount.Amount, error) { res, err := model.walletClient.GetTotalStake(model.ctx, &pactus.GetTotalStakeRequest{ WalletName: model.walletName, }) if err != nil { return 0, err } return amount.Amount(res.TotalStake), nil } func (model *WalletModel) AddressInfo(addr string) *pactus.AddressInfo { res, err := model.walletClient.GetAddressInfo(model.ctx, &pactus.GetAddressInfoRequest{ WalletName: model.walletName, Address: addr, }) if err != nil { return nil } return res.Addr } func (model *WalletModel) ListAddresses(addressTypes ...crypto.AddressType) []*pactus.AddressInfo { addressTypesPB := make([]pactus.AddressType, 0, len(addressTypes)) for _, at := range addressTypes { addressTypesPB = append(addressTypesPB, pactus.AddressType(at)) } res, err := model.walletClient.ListAddresses(model.ctx, &pactus.ListAddressesRequest{ WalletName: model.walletName, AddressTypes: addressTypesPB, }) if err != nil { return nil } return res.Addrs } func (model *WalletModel) Balance(addr string) (amount.Amount, error) { res, err := model.blockchainClient.GetAccount(model.ctx, &pactus.GetAccountRequest{ Address: addr, }) if err != nil { return 0, err } return amount.Amount(res.Account.Balance), nil } func (model *WalletModel) Stake(addr string) (amount.Amount, error) { res, err := model.blockchainClient.GetValidator(model.ctx, &pactus.GetValidatorRequest{ Address: addr, }) if err != nil { return 0, err } return amount.Amount(res.Validator.Stake), nil } func (model *WalletModel) ValidatorInfo(addr string) *pactus.ValidatorInfo { res, err := model.blockchainClient.GetValidator(model.ctx, &pactus.GetValidatorRequest{ Address: addr, }) if err != nil { return nil } return res.Validator } func (model *WalletModel) PrivateKey(password, addr string) (crypto.PrivateKey, error) { res, err := model.walletClient.GetPrivateKey(model.ctx, &pactus.GetPrivateKeyRequest{ WalletName: model.walletName, Password: password, Address: addr, }) if err != nil { return nil, err } _, typ, _, err := bech32m.DecodeToBase256WithTypeNoLimit(res.PrivateKey) if err != nil { return nil, err } switch typ { case crypto.SignatureTypeBLS: return bls.PrivateKeyFromString(res.PrivateKey) case crypto.SignatureTypeEd25519: return ed25519.PrivateKeyFromString(res.PrivateKey) default: return nil, crypto.InvalidSignatureTypeError(typ) } } func (model *WalletModel) Mnemonic(password string) (string, error) { res, err := model.walletClient.GetMnemonic(model.ctx, &pactus.GetMnemonicRequest{ WalletName: model.walletName, Password: password, }) if err != nil { return "", err } return res.Mnemonic, nil } func (model *WalletModel) UpdatePassword(oldPassword, newPassword string) error { _, err := model.walletClient.UpdatePassword(model.ctx, &pactus.UpdatePasswordRequest{ WalletName: model.walletName, OldPassword: oldPassword, NewPassword: newPassword, }) return err } func (model *WalletModel) SetDefaultFee(fee amount.Amount) error { _, err := model.walletClient.SetDefaultFee(model.ctx, &pactus.SetDefaultFeeRequest{ WalletName: model.walletName, Amount: int64(fee), }) return err } func (model *WalletModel) NewAddress( addressType crypto.AddressType, label string, password string, ) (*types.AddressInfo, error) { res, err := model.walletClient.GetNewAddress(model.ctx, &pactus.GetNewAddressRequest{ WalletName: model.walletName, AddressType: pactus.AddressType(addressType), Label: label, Password: password, }) if err != nil { return nil, err } return &types.AddressInfo{ Address: res.Addr.Address, PublicKey: res.Addr.PublicKey, Label: res.Addr.Label, Path: res.Addr.Path, }, nil } func (model *WalletModel) AddressLabel(addr string) string { res, err := model.walletClient.GetAddressInfo(model.ctx, &pactus.GetAddressInfoRequest{ WalletName: model.walletName, Address: addr, }) if err != nil { return "" } return res.Addr.Label } func (model *WalletModel) SetAddressLabel(addr, label string) error { _, err := model.walletClient.SetAddressLabel(model.ctx, &pactus.SetAddressLabelRequest{ WalletName: model.walletName, Address: addr, Label: label, }) return err } // AddressRows returns typed address rows with domain data only. func (model *WalletModel) AddressRows() []AddressRow { rows := make([]AddressRow, 0) res, err := model.walletClient.ListAddresses(model.ctx, &pactus.ListAddressesRequest{ WalletName: model.walletName, }) if err != nil { return rows } for no, info := range res.Addrs { balance, _ := model.Balance(info.Address) stake, _ := model.Stake(info.Address) rows = append(rows, AddressRow{ No: no + 1, Address: info.Address, Label: info.Label, Path: info.Path, Imported: info.Path == "", Balance: balance, Stake: stake, }) } return rows } func (model *WalletModel) MakeTransferTx( sender, receiver string, amt amount.Amount, fee amount.Amount, memo string, ) (*tx.Tx, error) { res, err := model.transactionClient.GetRawTransferTransaction(model.ctx, &pactus.GetRawTransferTransactionRequest{ Sender: sender, Receiver: receiver, Amount: int64(amt), Fee: int64(fee), Memo: memo, }) if err != nil { return nil, err } return tx.FromString(res.RawTransaction) } func (model *WalletModel) MakeBondTx( sender, receiver, publicKey string, amt amount.Amount, fee amount.Amount, memo string, ) (*tx.Tx, error) { if publicKey == "" { valInfo := model.ValidatorInfo(receiver) if valInfo == nil { // Let's check if we can get public key from the wallet info := model.AddressInfo(receiver) if info != nil { publicKey = info.PublicKey } } } res, err := model.transactionClient.GetRawBondTransaction(model.ctx, &pactus.GetRawBondTransactionRequest{ Sender: sender, Receiver: receiver, PublicKey: publicKey, Stake: int64(amt), Fee: int64(fee), Memo: memo, }) if err != nil { return nil, err } return tx.FromString(res.RawTransaction) } func (model *WalletModel) MakeUnbondTx(validatorAddr, memo string) (*tx.Tx, error) { res, err := model.transactionClient.GetRawUnbondTransaction(model.ctx, &pactus.GetRawUnbondTransactionRequest{ ValidatorAddress: validatorAddr, Memo: memo, }) if err != nil { return nil, err } return tx.FromString(res.RawTransaction) } func (model *WalletModel) MakeWithdrawTx( sender, receiver string, amt amount.Amount, fee amount.Amount, memo string, ) (*tx.Tx, error) { res, err := model.transactionClient.GetRawWithdrawTransaction(model.ctx, &pactus.GetRawWithdrawTransactionRequest{ ValidatorAddress: sender, AccountAddress: receiver, Amount: int64(amt), Fee: int64(fee), Memo: memo, }) if err != nil { return nil, err } return tx.FromString(res.RawTransaction) } func (model *WalletModel) SignTransaction(password string, trx *tx.Tx) error { raw, err := trx.Bytes() if err != nil { return err } res, err := model.walletClient.SignRawTransaction(model.ctx, &pactus.SignRawTransactionRequest{ WalletName: model.walletName, RawTransaction: hex.EncodeToString(raw), Password: password, }) if err != nil { return err } signedTx, err := tx.FromString(res.SignedRawTransaction) if err != nil { return err } *trx = *signedTx return nil } func (model *WalletModel) BroadcastTransaction(trx *tx.Tx) (string, error) { raw, err := trx.Bytes() if err != nil { return "", err } res, err := model.transactionClient.BroadcastTransaction(model.ctx, &pactus.BroadcastTransactionRequest{ SignedRawTransaction: hex.EncodeToString(raw), }) if err != nil { return "", err } return res.Id, nil } func (model *WalletModel) Transactions(count, skip int) []*pactus.WalletTransactionInfo { res, err := model.walletClient.ListTransactions(model.ctx, &pactus.ListTransactionsRequest{ WalletName: model.walletName, Count: int32(count), Skip: int32(skip), }) if err != nil { return nil } return res.Txs } ================================================ FILE: cmd/gtk/startup_assistant.go ================================================ //go:build gtk package main import ( "context" "errors" "fmt" "log" "path/filepath" "regexp" "strings" "time" "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/downloader" "github.com/pactus-project/pactus/wallet" ) type assistantFunc func(assistant *gtk.Assistant, content gtk.IWidget, name, title, subject, desc string) *gtk.Widget func setMargin(widget gtk.IWidget, top, bottom, start, end int) { widget.ToWidget().SetMarginTop(top) widget.ToWidget().SetMarginBottom(bottom) widget.ToWidget().SetMarginStart(start) widget.ToWidget().SetMarginEnd(end) } //nolint:all // complexity can't be reduced more. It needs to refactor. func startupAssistant(ctx context.Context, workingDir string, chain genesis.ChainType) bool { successful := false assistant, err := gtk.AssistantNew() gtkutil.FatalErrorCheck(err) assistant.SetDefaultSize(600, 400) assistant.SetTitle("Pactus - Node Setup Wizard") assistFunc := pageAssistant() // --- page_mode wgtWalletMode, radioRestoreWallet, pageModeName := pageWalletMode(assistant, assistFunc) // --- page_seed_generate wgtSeedGenerate, txtSeed, pageSeedGenerateName := pageSeedGenerate(assistant, assistFunc) // --- page_seed_confirm wgtSeedConfirm, pageSeedConfirmName := pageSeedConfirm(assistant, assistFunc, txtSeed) // -- page_seed_restore wgtSeedRestore, textRestoreSeed, pageSeedRestoreName := pageSeedRestore(assistant, assistFunc) // --- page_password wgtPassword, entryPassword, pagePasswordName := pagePassword(assistant, assistFunc) // --- page_num_validators wgtNumValidators, comboNumValidators, pageNumValidatorsName := pageNumValidators(assistant, assistFunc) // -- page_node_type wgtNodeType, gridImport, radioImport, pageNodeTypeName := pageNodeType(assistant, assistFunc) // --- page_address_recovery wgtAddressRecovery, txtRecoveryLog, btnCancelRecovery, lblRecoveryStatus, pageAddressRecoveryName := pageAddressRecovery(assistant, assistFunc) // --- page_summary wgtSummary, txtNodeInfo, pageSummaryName := pageSummary(assistant, assistFunc) assistant.Connect("cancel", func() { assistant.Close() assistant.Destroy() gtk.MainQuit() }) assistant.Connect("close", func() { assistant.Close() assistant.Destroy() gtk.MainQuit() }) assistant.SetPageType(wgtWalletMode, gtk.ASSISTANT_PAGE_INTRO) // page 0 assistant.SetPageType(wgtSeedGenerate, gtk.ASSISTANT_PAGE_CONTENT) // page 1 assistant.SetPageType(wgtSeedConfirm, gtk.ASSISTANT_PAGE_CONTENT) // page 2 assistant.SetPageType(wgtSeedRestore, gtk.ASSISTANT_PAGE_CONTENT) // page 3 assistant.SetPageType(wgtPassword, gtk.ASSISTANT_PAGE_CONTENT) // page 4 assistant.SetPageType(wgtNumValidators, gtk.ASSISTANT_PAGE_CONTENT) // page 5 assistant.SetPageType(wgtNodeType, gtk.ASSISTANT_PAGE_CONTENT) // page 6 assistant.SetPageType(wgtAddressRecovery, gtk.ASSISTANT_PAGE_CONTENT) // page 7 assistant.SetPageType(wgtSummary, gtk.ASSISTANT_PAGE_SUMMARY) // page 8 mnemonic := "" prevPageIndex := -1 prevPageAdjust := 0 rewardAddr := "" recoveredAddrs := []string{} nodeCreated := false addressedRecovered := false var nodeWallet *wallet.Wallet assistant.Connect("prepare", func(assistant *gtk.Assistant, page *gtk.Widget) { isRestoreMode := radioRestoreWallet.GetActive() curPageName, err := page.GetName() curPageIndex := assistant.GetCurrentPage() gtkutil.FatalErrorCheck(err) isForward := true if curPageIndex > 0 && curPageIndex < prevPageIndex { isForward = false } log.Printf("%v (restore: %v, prev: %v, cur: %v)\n", curPageName, isRestoreMode, prevPageIndex, curPageIndex) switch curPageName { case pageModeName: assistantPageComplete(assistant, wgtWalletMode, true) case pageSeedGenerateName: if isRestoreMode { if isForward { // forward log.Print("jumping forward from seedGenerate page") assistant.NextPage() prevPageAdjust = 1 } else { // backward log.Print("jumping backward from seedGenerate page") assistant.PreviousPage() prevPageAdjust = -1 } assistantPageComplete(assistant, wgtSeedGenerate, false) } else { mnemonic, _ = wallet.GenerateMnemonic(128) gtkutil.SetTextViewContent(txtSeed, mnemonic) assistantPageComplete(assistant, wgtSeedGenerate, true) } case pageSeedConfirmName: if isRestoreMode { if isForward { // forward log.Print("jumping forward from seedConfirm page") assistant.NextPage() prevPageAdjust = 1 } else { // backward log.Print("jumping backward from seedConfirm page") assistant.PreviousPage() prevPageAdjust = -1 } assistantPageComplete(assistant, wgtSeedConfirm, false) } else { assistantPageComplete(assistant, wgtSeedConfirm, false) } case pageSeedRestoreName: if !isRestoreMode { if isForward { // forward log.Print("jumping forward from seedRestore page") assistant.NextPage() prevPageAdjust = 1 } else { // backward log.Print("jumping backward from seedRestore page") assistant.PreviousPage() prevPageAdjust = -1 } assistantPageComplete(assistant, wgtSeedConfirm, false) } else { assistantPageComplete(assistant, wgtSeedRestore, true) } case pagePasswordName: if isRestoreMode { mnemonic = gtkutil.GetTextViewContent(textRestoreSeed) if err := wallet.CheckMnemonic(mnemonic); err != nil { gtkutil.ShowErrorDialog(assistant, "Invalid seed phrase. Please check your seed phrase and try again.") assistant.PreviousPage() } } assistantPageComplete(assistant, wgtPassword, true) case pageNumValidatorsName: assistantPageComplete(assistant, wgtNumValidators, true) case pageNodeTypeName: assistantPageComplete(assistant, wgtNodeType, true) ssLabel, err := gtk.LabelNew("") gtkutil.FatalErrorCheck(err) setMargin(ssLabel, 6, 6, 6, 6) ssLabel.SetHAlign(gtk.ALIGN_START) listBox, err := gtk.ListBoxNew() gtkutil.FatalErrorCheck(err) setMargin(listBox, 6, 6, 6, 6) listBox.SetHAlign(gtk.ALIGN_CENTER) listBox.SetSizeRequest(700, -1) ssDLBtn, err := gtk.ButtonNewWithLabel("⏬ Download") gtkutil.FatalErrorCheck(err) setMargin(ssDLBtn, 6, 6, 6, 6) ssDLBtn.SetHAlign(gtk.ALIGN_CENTER) ssDLBtn.SetSizeRequest(700, -1) ssPBLabel, err := gtk.LabelNew("") gtkutil.FatalErrorCheck(err) setMargin(ssPBLabel, 6, 6, 6, 6) ssPBLabel.SetHAlign(gtk.ALIGN_START) gridImport.Attach(ssLabel, 0, 1, 1, 1) gridImport.Attach(listBox, 0, 2, 1, 1) gridImport.Attach(ssDLBtn, 0, 3, 1, 1) gridImport.Attach(ssPBLabel, 0, 5, 1, 1) ssLabel.SetVisible(false) listBox.SetVisible(false) ssDLBtn.SetVisible(false) ssPBLabel.SetVisible(false) snapshotIndex := 0 if !nodeCreated { numValidators := gtkutil.ComboBoxActiveValue(comboNumValidators) walletPassword := gtkutil.GetEntryText(entryPassword) nodeWallet, rewardAddr, err = cmd.CreateNode(ctx, numValidators, chain, workingDir, mnemonic, walletPassword) if err != nil { gtkutil.ShowError(err) return } // Prevent re-entry nodeCreated = true } radioImport.Connect("toggled", func() { if radioImport.GetActive() { assistantPageComplete(assistant, wgtNodeType, false) ssLabel.SetVisible(true) ssLabel.SetText("♻️ Please wait, loading snapshot list...") go func() { time.Sleep(1 * time.Second) glib.IdleAdd(func() { snapshotURL := cmd.DefaultSnapshotURL // TODO: make me optional... storeDir := filepath.Join(workingDir, "data") importer, err := cmd.NewImporter(chain, snapshotURL, storeDir) if err != nil { gtkutil.ShowError(err) return } mdCh := getMetadata(ctx, importer, listBox) if metadata := <-mdCh; metadata == nil { gtkutil.SetColoredText(ssLabel, "❌ Failed to get snapshot list. Please try again later.", gtkutil.ColorRed) } else { ssLabel.SetText("🔽 Please select a snapshot to download:") listBox.SetVisible(true) listBox.Connect("row-selected", func(_ *gtk.ListBox, row *gtk.ListBoxRow) { if row != nil { snapshotIndex = row.GetIndex() ssDLBtn.SetVisible(true) } }) ssDLBtn.Connect("clicked", func() { radioGroup, _ := radioImport.GetParent() radioImport.SetSensitive(false) radioGroup.ToWidget().SetSensitive(false) ssLabel.SetSensitive(false) listBox.SetSensitive(false) ssDLBtn.SetSensitive(false) ssDLBtn.SetVisible(false) ssPBLabel.SetVisible(true) listBox.SetSelectionMode(gtk.SELECTION_NONE) go func() { log.Print("start downloading...\n") time.Sleep(1 * time.Second) err := importer.Download(ctx, &metadata[snapshotIndex], func(fileName string) func(stats downloader.Stats) { return func(stats downloader.Stats) { if !stats.Completed { percent := int(stats.Percent) glib.IdleAdd(func() { dlMessage := fmt.Sprintf("🌐 Downloading %s | %d%% (%s / %s)", fileName, percent, util.FormatBytesToHumanReadable(uint64(stats.Downloaded)), util.FormatBytesToHumanReadable(uint64(stats.TotalSize)), ) ssPBLabel.SetText(dlMessage) }) } } }, ) glib.IdleAdd(func() { if err != nil { gtkutil.SetColoredText(ssPBLabel, fmt.Sprintf("❌ Import failed: %v", err), gtkutil.ColorRed) return } log.Print("extracting data...\n") ssPBLabel.SetText("📂 Extracting downloaded files...") err := importer.ExtractAndStoreFiles() if err != nil { gtkutil.SetColoredText(ssPBLabel, fmt.Sprintf("❌ Import failed: %v", err), gtkutil.ColorRed) return } log.Print("moving data...\n") ssPBLabel.SetText("📑 Moving data...") err = importer.MoveStore() if err != nil { gtkutil.SetColoredText(ssPBLabel, fmt.Sprintf("❌ Import failed: %v", err), gtkutil.ColorRed) return } log.Print("cleanup...\n") err = importer.Cleanup() if err != nil { gtkutil.SetColoredText(ssPBLabel, fmt.Sprintf("❌ Import failed: %v", err), gtkutil.ColorRed) return } gtkutil.SetColoredText(ssPBLabel, "✅ Import completed.", gtkutil.ColorGreen) assistantPageComplete(assistant, wgtNodeType, true) }) }() }) } }) }() } else { assistantPageComplete(assistant, wgtNodeType, true) ssLabel.SetVisible(false) listBox.SetVisible(false) ssDLBtn.SetVisible(false) ssPBLabel.SetVisible(false) } }) case pageAddressRecoveryName: // Only handle recovery for restore mode if !isRestoreMode { // Skip this page for new wallets if isForward { log.Print("jumping forward from addressRecovery page") assistant.NextPage() prevPageAdjust = 1 } else { log.Print("jumping backward from addressRecovery page") assistant.PreviousPage() prevPageAdjust = -1 } return } if !addressedRecovered { // Prevent re-entry addressedRecovered = true // Disable next button initially assistantPageComplete(assistant, wgtAddressRecovery, false) lblRecoveryStatus.SetText("Processing...") // Reset recovery context recoveryCtx, cancelRecovery := context.WithCancel(ctx) // Setup cancel recovery button handler btnCancelRecovery.Connect("clicked", func() { lblRecoveryStatus.SetText("Cancelling recovery...") cancelRecovery() btnCancelRecovery.SetSensitive(false) }) go func() { walletPassword := gtkutil.GetEntryText(entryPassword) recoveryIndex := 0 err = nodeWallet.RecoveryAddresses(recoveryCtx, walletPassword, func(addr string) { glib.IdleAdd(func() { currentText := gtkutil.GetTextViewContent(txtRecoveryLog) newText := fmt.Sprintf("%s%d. %s\n", currentText, recoveryIndex+1, addr) gtkutil.SetTextViewContent(txtRecoveryLog, newText) recoveredAddrs = append(recoveredAddrs, addr) recoveryIndex++ }) }) glib.IdleAdd(func() { if err != nil { if errors.Is(err, context.Canceled) { gtkutil.SetColoredText(lblRecoveryStatus, "Address recovery aborted", gtkutil.ColorYellow) btnCancelRecovery.SetVisible(false) assistantPageComplete(assistant, wgtAddressRecovery, true) } else { gtkutil.SetColoredText(lblRecoveryStatus, fmt.Sprintf("Address recovery failed: %v", err), gtkutil.ColorRed) btnCancelRecovery.SetVisible(false) assistantPageComplete(assistant, wgtAddressRecovery, true) } } else { gtkutil.SetColoredText(lblRecoveryStatus, "✅ Wallet addresses successfully recovered", gtkutil.ColorGreen) btnCancelRecovery.SetVisible(false) assistantPageComplete(assistant, wgtAddressRecovery, true) } }) }() } case pageSummaryName: // Done! showing the node information successful = true nodeInfo := "" nodeInfo += "🔄 Recovered Addresses:\n" for i, addr := range recoveredAddrs { nodeInfo += fmt.Sprintf("%v- %s\n", i+1, addr) } nodeInfo += "\n🏛️ Validator Addresses:\n" for i, info := range nodeWallet.ListAddresses(wallet.OnlyValidatorAddresses()) { nodeInfo += fmt.Sprintf("%v- %s\n", i+1, info.Address) } nodeInfo += "\n💰 Reward Address:\n" nodeInfo += fmt.Sprintf("%s\n", rewardAddr) nodeInfo += fmt.Sprintf("\n📁 Working Directory: %s", workingDir) nodeInfo += fmt.Sprintf("\n🌐 Network: %s\n", chain.String()) gtkutil.SetTextViewContent(txtNodeInfo, nodeInfo) } prevPageIndex = curPageIndex + prevPageAdjust }) assistant.SetModal(true) assistant.ShowAll() gtk.Main() if nodeWallet != nil { nodeWallet.Close() } return successful } func pageAssistant() assistantFunc { return func(assistant *gtk.Assistant, content gtk.IWidget, name, title, subject, desc string) *gtk.Widget { page, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 20) gtkutil.FatalErrorCheck(err) page.SetHExpand(true) frame, err := gtk.FrameNew(subject) gtkutil.FatalErrorCheck(err) frame.SetHExpand(true) labelDesc, err := gtk.LabelNew("") gtkutil.FatalErrorCheck(err) labelDesc.SetUseMarkup(true) labelDesc.SetMarkup("" + desc + "") labelDesc.SetVExpand(true) labelDesc.SetVAlign(gtk.ALIGN_END) labelDesc.SetHAlign(gtk.ALIGN_START) setMargin(labelDesc, 0, 0, 0, 0) frame.Add(content) box, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10) gtkutil.FatalErrorCheck(err) box.Add(frame) box.Add(labelDesc) page.Add(box) page.SetName(name) assistant.AppendPage(page) assistant.SetPageTitle(page, title) return page.ToWidget() } } func pageWalletMode(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.Widget, *gtk.RadioButton, string) { var mode *gtk.Widget newWalletRadio, err := gtk.RadioButtonNewWithLabel(nil, "Create a new wallet from scratch") gtkutil.FatalErrorCheck(err) restoreWalletRadio, err := gtk.RadioButtonNewWithLabelFromWidget(newWalletRadio, "Restore a wallet from seed phrase") gtkutil.FatalErrorCheck(err) radioBox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0) gtkutil.FatalErrorCheck(err) radioBox.Add(newWalletRadio) setMargin(newWalletRadio, 6, 6, 6, 6) radioBox.Add(restoreWalletRadio) setMargin(restoreWalletRadio, 6, 6, 6, 6) pageModeName := "page_wallet_mode" pageModeTitle := "Wallet Mode" pageModeSubject := "How to create your wallet?" pageModeDesc := "If you are setting up the node for the first time, choose the first option." mode = assistFunc( assistant, radioBox, pageModeName, pageModeTitle, pageModeSubject, pageModeDesc) return mode, restoreWalletRadio, pageModeName } func pageSeedGenerate(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.Widget, *gtk.TextView, string) { var pageWidget *gtk.Widget textViewSeed, err := gtk.TextViewNew() gtkutil.FatalErrorCheck(err) setMargin(textViewSeed, 6, 6, 6, 6) textViewSeed.SetWrapMode(gtk.WRAP_WORD) textViewSeed.SetEditable(false) textViewSeed.SetMonospace(true) textViewSeed.SetSizeRequest(0, 80) pageSeedName := "page_seed_generate" pageSeedTitle := "Wallet Seed" pageSeedSubject := "Your wallet seed phrase:" pageSeedDesc := `⚠️ CRITICAL: Write down this seed phrase and store it safely! This is the ONLY way to recover your wallet if needed. Never share it with anyone or store it electronically.` pageWidget = assistFunc( assistant, textViewSeed, pageSeedName, pageSeedTitle, pageSeedSubject, pageSeedDesc) return pageWidget, textViewSeed, pageSeedName } func pageSeedRestore(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.Widget, *gtk.TextView, string) { var pageWidget *gtk.Widget textViewRestoreSeed, err := gtk.TextViewNew() gtkutil.FatalErrorCheck(err) setMargin(textViewRestoreSeed, 6, 6, 6, 6) textViewRestoreSeed.SetWrapMode(gtk.WRAP_WORD) textViewRestoreSeed.SetEditable(true) textViewRestoreSeed.SetMonospace(true) textViewRestoreSeed.SetSizeRequest(0, 80) pageSeedName := "page_seed_restore" pageSeedTitle := "Wallet Seed Restore" pageSeedSubject := "Enter your wallet seed phrase:" pageSeedDesc := "Please enter your wallet seed phrase to restore your wallet." pageWidget = assistFunc( assistant, textViewRestoreSeed, pageSeedName, pageSeedTitle, pageSeedSubject, pageSeedDesc) return pageWidget, textViewRestoreSeed, pageSeedName } func pageSeedConfirm(assistant *gtk.Assistant, assistFunc assistantFunc, textViewSeed *gtk.TextView, ) (*gtk.Widget, string) { pageWidget := new(gtk.Widget) textViewConfirmSeed, err := gtk.TextViewNew() gtkutil.FatalErrorCheck(err) setMargin(textViewConfirmSeed, 6, 6, 6, 6) textViewConfirmSeed.SetWrapMode(gtk.WRAP_WORD) textViewConfirmSeed.SetEditable(true) textViewConfirmSeed.SetMonospace(true) textViewConfirmSeed.SetSizeRequest(0, 80) textViewConfirmSeed.Connect("paste_clipboard", func(_ *gtk.TextView) { gtkutil.ShowInfoDialog(assistant, "Copy and paste is not allowed") textViewConfirmSeed.StopEmission("paste_clipboard") }) seedConfirmTextBuffer, err := textViewConfirmSeed.GetBuffer() gtkutil.FatalErrorCheck(err) seedConfirmTextBuffer.Connect("changed", func(_ *gtk.TextBuffer) { mnemonic1 := gtkutil.GetTextViewContent(textViewSeed) mnemonic2 := gtkutil.GetTextViewContent(textViewConfirmSeed) space := regexp.MustCompile(`\s+`) mnemonic2 = space.ReplaceAllString(mnemonic2, " ") mnemonic2 = strings.TrimSpace(mnemonic2) if mnemonic1 == mnemonic2 { assistantPageComplete(assistant, pageWidget, true) } else { assistantPageComplete(assistant, pageWidget, false) } }) pageSeedConfirmName := "page_seed_confirm" pageSeedConfirmTitle := "Confirm Seed" pageSeedConfirmSubject := "What was your seed?" pageSeedConfirmDesc := `Your seed phrase is critical for wallet recovery! To ensure you have properly saved your seed phrase, please retype it here.` pageWidget = assistFunc( assistant, textViewConfirmSeed, pageSeedConfirmName, pageSeedConfirmTitle, pageSeedConfirmSubject, pageSeedConfirmDesc) return pageWidget, pageSeedConfirmName } func pageNodeType(assistant *gtk.Assistant, assistFunc assistantFunc) ( *gtk.Widget, *gtk.Grid, *gtk.RadioButton, string, ) { var pageWidget *gtk.Widget vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0) gtkutil.FatalErrorCheck(err) grid, err := gtk.GridNew() gtkutil.FatalErrorCheck(err) btnFullNode, err := gtk.RadioButtonNewWithLabel(nil, "Full node") gtkutil.FatalErrorCheck(err) btnFullNode.SetActive(true) btnPruneNode, err := gtk.RadioButtonNewWithLabelFromWidget(btnFullNode, "Pruned node") gtkutil.FatalErrorCheck(err) radioBox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0) gtkutil.FatalErrorCheck(err) radioBox.Add(btnFullNode) setMargin(btnFullNode, 6, 6, 6, 6) radioBox.Add(btnPruneNode) setMargin(btnPruneNode, 6, 10, 6, 6) grid.Attach(radioBox, 0, 0, 1, 1) vbox.PackStart(grid, true, true, 0) pageName := "page_node_type" pageTitle := "Node Type" pageSubject := "How do you want to start your node?" pageDesc := `A pruned node doesn't keep all the historical blockchain data. Instead, it only retains the most recent part of the blockchain, deleting older data to save disk space. Historical data is available at: https://snapshot.pactus.org/` // Create and return the page widget using assistFunc pageWidget = assistFunc( assistant, vbox, pageName, pageTitle, pageSubject, pageDesc, ) return pageWidget, grid, btnPruneNode, pageName } func pagePassword(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.Widget, *gtk.Entry, string) { pageWidget := new(gtk.Widget) entryPassword, err := gtk.EntryNew() gtkutil.FatalErrorCheck(err) setMargin(entryPassword, 6, 6, 6, 6) entryPassword.SetVisibility(false) labelPassword, err := gtk.LabelNew("Password: ") gtkutil.FatalErrorCheck(err) labelPassword.SetHAlign(gtk.ALIGN_START) setMargin(labelPassword, 6, 6, 6, 6) entryConfirmPassword, err := gtk.EntryNew() gtkutil.FatalErrorCheck(err) setMargin(entryConfirmPassword, 6, 6, 6, 6) entryConfirmPassword.SetVisibility(false) labelConfirmPassword, err := gtk.LabelNew("Confirmation: ") gtkutil.FatalErrorCheck(err) labelConfirmPassword.SetHAlign(gtk.ALIGN_START) setMargin(labelConfirmPassword, 6, 6, 6, 6) grid, err := gtk.GridNew() gtkutil.FatalErrorCheck(err) labelMessage, err := gtk.LabelNew("") gtkutil.FatalErrorCheck(err) grid.Attach(labelPassword, 0, 0, 1, 1) grid.Attach(entryPassword, 1, 0, 1, 1) grid.Attach(labelConfirmPassword, 0, 1, 1, 1) grid.Attach(entryConfirmPassword, 1, 1, 1, 1) grid.Attach(labelMessage, 1, 2, 1, 1) validatePassword := func() { pass1 := gtkutil.GetEntryText(entryPassword) pass2 := gtkutil.GetEntryText(entryConfirmPassword) if pass1 == pass2 { labelMessage.SetText("") assistantPageComplete(assistant, pageWidget, true) } else { if pass2 != "" { gtkutil.SetColoredText(labelMessage, "Passwords do not match", gtkutil.ColorYellow) } assistantPageComplete(assistant, pageWidget, false) } } entryPassword.Connect("changed", func(_ *gtk.Entry) { validatePassword() }) entryConfirmPassword.Connect("changed", func(_ *gtk.Entry) { validatePassword() }) pagePasswordName := "page_password" pagePasswordTitle := "Wallet Password" pagePasswordSubject := "Enter password for your wallet:" pagePsswrdDesc := "Please choose a strong password to protect your wallet." pageWidget = assistFunc( assistant, grid, pagePasswordName, pagePasswordTitle, pagePasswordSubject, pagePsswrdDesc) return pageWidget, entryPassword, pagePasswordName } func pageNumValidators(assistant *gtk.Assistant, assistFunc assistantFunc, ) (*gtk.Widget, *gtk.ComboBox, string) { var pageWidget *gtk.Widget lsNumValidators, err := gtk.ListStoreNew(glib.TYPE_INT) gtkutil.FatalErrorCheck(err) for i := 0; i < 32; i++ { iter := lsNumValidators.Append() err = lsNumValidators.SetValue(iter, 0, i+1) gtkutil.FatalErrorCheck(err) } comboNumValidators, err := gtk.ComboBoxNewWithModel(lsNumValidators) gtkutil.FatalErrorCheck(err) cellRenderer, err := gtk.CellRendererTextNew() gtkutil.FatalErrorCheck(err) // Set the default selected value to 7 (index 6) comboNumValidators.SetActive(6) comboNumValidators.PackStart(cellRenderer, true) comboNumValidators.AddAttribute(cellRenderer, "text", 0) labelNumValidators, err := gtk.LabelNew("Number of validators: ") gtkutil.FatalErrorCheck(err) setMargin(labelNumValidators, 6, 6, 6, 6) setMargin(comboNumValidators, 6, 6, 6, 6) grid, err := gtk.GridNew() gtkutil.FatalErrorCheck(err) grid.Add(labelNumValidators) grid.Attach(comboNumValidators, 1, 0, 1, 1) pageNumValidatorsName := "page_num_validators" pageNumValidatorsTitle := "Number of Validators" pageNumValidatorsSubject := "How many validators do you want to create?" pageNumValidatorsDesc := `Each node can run up to 32 validators, and each validator can hold up to 1000 staked coins. You can define validators based on the amount of coins you want to stake. For more information, look here` pageWidget = assistFunc( assistant, grid, pageNumValidatorsName, pageNumValidatorsTitle, pageNumValidatorsSubject, pageNumValidatorsDesc) return pageWidget, comboNumValidators, pageNumValidatorsName } func pageAddressRecovery(assistant *gtk.Assistant, assistFunc assistantFunc) ( *gtk.Widget, *gtk.TextView, *gtk.Button, *gtk.Label, string, ) { var pageWidget *gtk.Widget // Create a vertical box to hold all elements vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10) gtkutil.FatalErrorCheck(err) // Create TextView for recovery log (read-only, scrollable) textViewRecoveryLog, err := gtk.TextViewNew() gtkutil.FatalErrorCheck(err) setMargin(textViewRecoveryLog, 6, 6, 6, 6) textViewRecoveryLog.SetWrapMode(gtk.WRAP_WORD) textViewRecoveryLog.SetEditable(false) textViewRecoveryLog.SetMonospace(true) // Create scrolled window for the text view scrolledWindow, err := gtk.ScrolledWindowNew(nil, nil) gtkutil.FatalErrorCheck(err) scrolledWindow.SetSizeRequest(0, 200) scrolledWindow.Add(textViewRecoveryLog) // Create status label lblRecoveryStatus, err := gtk.LabelNew("") gtkutil.FatalErrorCheck(err) setMargin(lblRecoveryStatus, 6, 6, 6, 6) lblRecoveryStatus.SetHAlign(gtk.ALIGN_START) // Create cancel button btnCancelRecovery, err := gtk.ButtonNewWithLabel("Cancel") gtkutil.FatalErrorCheck(err) setMargin(btnCancelRecovery, 6, 6, 6, 6) btnCancelRecovery.SetHAlign(gtk.ALIGN_CENTER) btnCancelRecovery.SetSizeRequest(150, -1) // Add widgets to vbox vbox.PackStart(scrolledWindow, true, true, 0) vbox.PackStart(lblRecoveryStatus, false, false, 0) vbox.PackStart(btnCancelRecovery, false, false, 0) pageAddressRecoveryName := "page_address_recovery" pageAddressRecoveryTitle := "Address Recovery" pageAddressRecoverySubject := "Recovered Addresses" pageAddressRecoveryDesc := `Please wait while wallet addresses are recovered...` pageWidget = assistFunc( assistant, vbox, pageAddressRecoveryName, pageAddressRecoveryTitle, pageAddressRecoverySubject, pageAddressRecoveryDesc) return pageWidget, textViewRecoveryLog, btnCancelRecovery, lblRecoveryStatus, pageAddressRecoveryName } func pageSummary(assistant *gtk.Assistant, assistFunc assistantFunc) (*gtk.Widget, *gtk.TextView, string) { var pageWidget *gtk.Widget textViewNodeInfo, err := gtk.TextViewNew() gtkutil.FatalErrorCheck(err) setMargin(textViewNodeInfo, 6, 6, 6, 6) textViewNodeInfo.SetWrapMode(gtk.WRAP_WORD) textViewNodeInfo.SetEditable(false) textViewNodeInfo.SetMonospace(true) scrolledWindow, err := gtk.ScrolledWindowNew(nil, nil) gtkutil.FatalErrorCheck(err) scrolledWindow.SetSizeRequest(0, 300) scrolledWindow.Add(textViewNodeInfo) pageFinalName := "page_summary" pageFinalTitle := "Summary" pageFinalSubject := "Your node information:" pageFinalDesc := `Congratulation. Your node is initialized successfully. Now you are ready to start the node!` pageWidget = assistFunc( assistant, scrolledWindow, pageFinalName, pageFinalTitle, pageFinalSubject, pageFinalDesc) return pageWidget, textViewNodeInfo, pageFinalName } func assistantPageComplete(assistant *gtk.Assistant, page gtk.IWidget, completed bool) { assistant.SetPageComplete(page, completed) assistant.UpdateButtonsState() } func getMetadata( ctx context.Context, importer *cmd.Importer, listBox *gtk.ListBox, ) <-chan []cmd.Metadata { mdCh := make(chan []cmd.Metadata, 1) go func() { defer close(mdCh) children := listBox.GetChildren() for children.Length() > 0 { child := children.Data().(*gtk.Widget) listBox.Remove(child) children = children.Next() } metadata, err := importer.GetMetadata(ctx) if err != nil { mdCh <- nil return } for _, md := range metadata { label, err := gtk.LabelNew(fmt.Sprintf("snapshot %s (%s)", md.CreatedAtTime().Format("2006-01-02"), util.FormatBytesToHumanReadable(md.Data.Size), )) gtkutil.FatalErrorCheck(err) listBoxRow, err := gtk.ListBoxRowNew() gtkutil.FatalErrorCheck(err) listBoxRow.Add(label) listBox.Add(listBoxRow) } listBox.ShowAll() mdCh <- metadata }() return mdCh } ================================================ FILE: cmd/gtk/view/about_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" ) func NewAboutDialog() *gtk.AboutDialog { builder := NewViewBuilder(assets.DialogAboutUI) dlg := builder.GetAboutDialogObj("id_dialog_about") dlg.SetLogo(assets.ImagePactusLogoPixbuf) return dlg } ================================================ FILE: cmd/gtk/view/about_gtk_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" ) func NewAboutGTKDialog() *gtk.AboutDialog { builder := NewViewBuilder(assets.DialogAboutGTKUI) dlg := builder.GetAboutDialogObj("id_dialog_about_gtk") dlg.SetLogo(assets.ImageGTKLogoPixbuf) return dlg } ================================================ FILE: cmd/gtk/view/address_details_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type AddressDetailsDialogView struct { ViewBuilder Dialog *gtk.Dialog AddressEntry *gtk.Entry PubKeyEntry *gtk.Entry PathEntry *gtk.Entry ButtonClose *gtk.Button } func NewAddressDetailsDialogView() *AddressDetailsDialogView { builder := NewViewBuilder(assets.AddressDetailsDialogUI) view := &AddressDetailsDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_address_details"), AddressEntry: builder.BuildExtendedEntry("id_overlay_address"), PubKeyEntry: builder.BuildExtendedEntry("id_overlay_public_key"), PathEntry: builder.GetEntryObj("id_entry_path"), ButtonClose: builder.GetButtonObj("id_button_close"), } view.ButtonClose.SetImage(gtkutil.ImageFromPixbuf(assets.IconClosePixbuf16)) return view } ================================================ FILE: cmd/gtk/view/address_label_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type AddressLabelDialogView struct { ViewBuilder Dialog *gtk.Dialog LabelEntry *gtk.Entry ButtonOK *gtk.Button ButtonCancel *gtk.Button } func NewAddressLabelDialogView() *AddressLabelDialogView { builder := NewViewBuilder(assets.AddressLabelDialogUI) view := &AddressLabelDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_address_label"), LabelEntry: builder.GetEntryObj("id_entry_label"), ButtonOK: builder.GetButtonObj("id_button_ok"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), } view.ButtonOK.SetImage(gtkutil.ImageFromPixbuf(assets.IconOkPixbuf16)) view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/address_private_key_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type AddressPrivateKeyDialogView struct { ViewBuilder Dialog *gtk.Dialog AddressEntry *gtk.Entry PrvKeyEntry *gtk.Entry ButtonClose *gtk.Button } func NewAddressPrivateKeyDialogView() *AddressPrivateKeyDialogView { builder := NewViewBuilder(assets.AddressPrivateKeyDialogUI) view := &AddressPrivateKeyDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_address_private_key"), AddressEntry: builder.GetEntryObj("id_entry_address"), PrvKeyEntry: builder.GetEntryObj("id_entry_private_key"), ButtonClose: builder.GetButtonObj("id_button_close"), } view.ButtonClose.SetImage(gtkutil.ImageFromPixbuf(assets.IconClosePixbuf16)) return view } ================================================ FILE: cmd/gtk/view/committee_widget_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type CommitteeWidgetView struct { ViewBuilder Box *gtk.Box LabelCommitteeSize *gtk.Label LabelCommitteePower *gtk.Label LabelTotalPower *gtk.Label LabelProtocolVersions *gtk.Label TreeViewMembers *gtk.TreeView listStore *gtk.ListStore } func NewCommitteeWidgetView() *CommitteeWidgetView { builder := NewViewBuilder(assets.CommitteeWidgetUI) treeViewMembers := builder.GetTreeViewObj("id_treeview_committee_members") view := &CommitteeWidgetView{ ViewBuilder: builder, Box: builder.GetBoxObj("id_box_committee"), LabelCommitteeSize: builder.GetLabelObj("id_label_committee_size"), LabelCommitteePower: builder.GetLabelObj("id_label_committee_power"), LabelTotalPower: builder.GetLabelObj("id_label_total_power"), LabelProtocolVersions: builder.GetLabelObj("id_label_protocol_versions"), TreeViewMembers: treeViewMembers, } // Build list store for committee members table. listStore, err := gtk.ListStoreNew( glib.TYPE_STRING, // No glib.TYPE_STRING, // Address glib.TYPE_STRING, // Number glib.TYPE_STRING, // Stake glib.TYPE_STRING, // Last Bonding Height glib.TYPE_STRING, // Last Sortition Height glib.TYPE_STRING, // Protocol Version glib.TYPE_STRING, // Availability Score ) gtkutil.FatalErrorCheck(err) view.listStore = listStore view.TreeViewMembers.SetModel(listStore.ToTreeModel()) colNo := createTextColumn("No", 0) colAddress := createTextColumn("Address", 1) colNumber := createTextColumn("Number", 2) colStake := createTextColumn("Stake", 3) colBondingHeight := createTextColumn("Bonding Height", 4) colSortitionHeight := createTextColumn("Sortition Height", 5) colProtocolVersion := createTextColumn("Protocol", 6) colScore := createTextColumn("Availability", 7) view.TreeViewMembers.AppendColumn(colNo) view.TreeViewMembers.AppendColumn(colAddress) view.TreeViewMembers.AppendColumn(colNumber) view.TreeViewMembers.AppendColumn(colStake) view.TreeViewMembers.AppendColumn(colBondingHeight) view.TreeViewMembers.AppendColumn(colSortitionHeight) view.TreeViewMembers.AppendColumn(colProtocolVersion) view.TreeViewMembers.AppendColumn(colScore) return view } func (view *CommitteeWidgetView) ClearRows() { view.listStore.Clear() } func (view *CommitteeWidgetView) AppendRow(cols []int, values []any) { iter := view.listStore.Append() _ = view.listStore.Set(iter, cols, values) } ================================================ FILE: cmd/gtk/view/main_window_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gdk" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type MainWindowView struct { ViewBuilder Window *gtk.ApplicationWindow BoxNode *gtk.Box BoxDefaultWallet *gtk.Box BoxValidators *gtk.Box BoxCommittee *gtk.Box BoxNetwork *gtk.Box } func NewMainWindowView() *MainWindowView { builder := NewViewBuilder(assets.MainWindowUI) boxNode := builder.GetBoxObj("id_box_node") boxDefaultWallet := builder.GetBoxObj("id_box_default_wallet") boxValidators := builder.GetBoxObj("id_box_validators") boxCommittee := builder.GetBoxObj("id_box_committee") boxNetwork := builder.GetBoxObj("id_box_network") view := &MainWindowView{ ViewBuilder: builder, Window: builder.GetApplicationWindowObj("id_main_window"), BoxNode: boxNode, BoxDefaultWallet: boxDefaultWallet, BoxValidators: boxValidators, BoxCommittee: boxCommittee, BoxNetwork: boxNetwork, } // apply custom css provider, err := gtk.CssProviderNew() gtkutil.FatalErrorCheck(err) err = provider.LoadFromData(assets.MainWindowCSS) gtkutil.FatalErrorCheck(err) screen, err := gdk.ScreenGetDefault() gtkutil.FatalErrorCheck(err) gtk.AddProviderForScreen(screen, provider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) return view } func (v *MainWindowView) Cleanup() { v.Window.Destroy() } ================================================ FILE: cmd/gtk/view/network_widget_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type NetworkWidgetView struct { ViewBuilder Box *gtk.Box LabelNetworkName *gtk.Label LabelConnectedPeers *gtk.Label TreeViewPeers *gtk.TreeView listStore *gtk.ListStore } func NewNetworkWidgetView() *NetworkWidgetView { builder := NewViewBuilder(assets.NetworkWidgetUI) treeViewPeers := builder.GetTreeViewObj("id_treeview_peers") view := &NetworkWidgetView{ ViewBuilder: builder, Box: builder.GetBoxObj("id_box_network"), LabelNetworkName: builder.GetLabelObj("id_label_network_name"), LabelConnectedPeers: builder.GetLabelObj("id_label_connected_peers"), TreeViewPeers: treeViewPeers, } listStore, err := gtk.ListStoreNew( glib.TYPE_STRING, // No glib.TYPE_STRING, // Moniker glib.TYPE_STRING, // Address glib.TYPE_STRING, // Peer ID glib.TYPE_STRING, // Height glib.TYPE_STRING, // Agent glib.TYPE_STRING, // Direction ) gtkutil.FatalErrorCheck(err) view.listStore = listStore view.TreeViewPeers.SetModel(listStore.ToTreeModel()) colNo := createTextColumn("No", 0) colMoniker := createTextColumn("Moniker", 1) colAddress := createTextColumn("Address", 2) colPeerID := createTextColumn("Peer ID", 3) colHeight := createTextColumn("Height", 4) colAgent := createTextColumn("Agent", 5) colDirection := createTextColumn("Direction", 6) view.TreeViewPeers.AppendColumn(colNo) view.TreeViewPeers.AppendColumn(colMoniker) view.TreeViewPeers.AppendColumn(colAddress) view.TreeViewPeers.AppendColumn(colPeerID) view.TreeViewPeers.AppendColumn(colHeight) view.TreeViewPeers.AppendColumn(colAgent) view.TreeViewPeers.AppendColumn(colDirection) return view } func (view *NetworkWidgetView) ClearRows() { view.listStore.Clear() } func (view *NetworkWidgetView) AppendRow(cols []int, values []any) { iter := view.listStore.Append() _ = view.listStore.Set(iter, cols, values) } ================================================ FILE: cmd/gtk/view/node_widget_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" ) type NodeWidgetView struct { ViewBuilder Box *gtk.Box LabelConnectionType *gtk.Label LabelConnectionValue *gtk.Label LabelNetwork *gtk.Label LabelNetworkID *gtk.Label LabelAgent *gtk.Label LabelMoniker *gtk.Label LabelIsPrune *gtk.Label LabelClockOffset *gtk.Label LabelLastBlockTime *gtk.Label LabelLastBlockHeight *gtk.Label LabelBlocksLeft *gtk.Label ProgressBarSynced *gtk.ProgressBar LabelCommitteeSize *gtk.Label LabelActiveValidator *gtk.Label LabelInCommittee *gtk.Label LabelCommitteeStake *gtk.Label LabelTotalStake *gtk.Label LabelAverageScore *gtk.Label LabelNumConnections *gtk.Label LabelReachability *gtk.Label } func NewNodeWidgetView() *NodeWidgetView { builder := NewViewBuilder(assets.NodeWidgetUI) view := &NodeWidgetView{ ViewBuilder: builder, Box: builder.GetBoxObj("id_box_node"), LabelConnectionType: builder.GetLabelObj("id_label_connection_type"), LabelConnectionValue: builder.GetLabelObj("id_label_connection_value"), LabelNetwork: builder.GetLabelObj("id_label_network"), LabelNetworkID: builder.GetLabelObj("id_label_network_id"), LabelAgent: builder.GetLabelObj("id_label_agent"), LabelMoniker: builder.GetLabelObj("id_label_moniker"), LabelIsPrune: builder.GetLabelObj("id_label_is_prune"), LabelClockOffset: builder.GetLabelObj("id_label_clock_offset"), LabelLastBlockTime: builder.GetLabelObj("id_label_last_block_time"), LabelLastBlockHeight: builder.GetLabelObj("id_label_last_block_height"), LabelBlocksLeft: builder.GetLabelObj("id_label_blocks_left"), ProgressBarSynced: builder.GetProgressBarObj("id_progress_synced"), LabelCommitteeSize: builder.GetLabelObj("id_label_committee_size"), LabelActiveValidator: builder.GetLabelObj("id_label_active_validators"), LabelInCommittee: builder.GetLabelObj("id_label_in_committee"), LabelCommitteeStake: builder.GetLabelObj("id_label_committee_power"), LabelTotalStake: builder.GetLabelObj("id_label_total_power"), LabelAverageScore: builder.GetLabelObj("id_label_average_score"), LabelNumConnections: builder.GetLabelObj("id_label_num_connections"), LabelReachability: builder.GetLabelObj("id_label_reachability"), } return view } ================================================ FILE: cmd/gtk/view/splash_window_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gdk" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) // SplashWindow is a lightweight splash screen that stays visible while the // node boots up. Callers can update the status text via SetStatus. type SplashWindow struct { window *gtk.ApplicationWindow statusLabel *gtk.Label version *gtk.Label spinner *gtk.Spinner } func NewSplashWindow(app *gtk.Application) *SplashWindow { window, err := gtk.ApplicationWindowNew(app) gtkutil.FatalErrorCheck(err) window.SetDecorated(false) window.SetResizable(false) window.SetTypeHint(gdk.WINDOW_TYPE_HINT_SPLASHSCREEN) window.SetPosition(gtk.WIN_POS_CENTER) window.SetDefaultSize(420, 220) content, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 12) gtkutil.FatalErrorCheck(err) content.SetBorderWidth(24) logo := gtkutil.ImageFromPixbuf(assets.ImagePactusLogoPixbuf) if logo != nil { logo.SetMarginBottom(8) content.Add(logo) } spinner, err := gtk.SpinnerNew() gtkutil.FatalErrorCheck(err) spinner.Start() spinner.SetMarginBottom(6) content.Add(spinner) statusLabel, err := gtk.LabelNew("Starting node...") gtkutil.FatalErrorCheck(err) statusLabel.SetHAlign(gtk.ALIGN_START) content.Add(statusLabel) versionLabel, err := gtk.LabelNew("") gtkutil.FatalErrorCheck(err) versionLabel.SetHAlign(gtk.ALIGN_START) versionLabel.SetMarginTop(6) styleContext, err := versionLabel.GetStyleContext() gtkutil.FatalErrorCheck(err) styleContext.AddClass("dim-label") content.Add(versionLabel) window.Add(content) return &SplashWindow{ window: window, statusLabel: statusLabel, spinner: spinner, version: versionLabel, } } func (s *SplashWindow) ShowAll() { s.window.ShowAll() s.spinner.Start() } func (s *SplashWindow) Destroy() { s.window.Destroy() } func (s *SplashWindow) SetStatus(text string) { s.statusLabel.SetText(text) } func (s *SplashWindow) SetVersion(text string) { s.version.SetText(text) } func (s *SplashWindow) Window() *gtk.ApplicationWindow { return s.window } ================================================ FILE: cmd/gtk/view/tx_bond_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type TxBondDialogView struct { ViewBuilder Dialog *gtk.Dialog SenderCombo *gtk.ComboBoxText SenderHint *gtk.Label ReceiverCombo *gtk.ComboBoxText ReceiverHint *gtk.Label PublicKeyEntry *gtk.Entry AmountEntry *gtk.Entry AmountHint *gtk.Label FeeEntry *gtk.Entry FeeHint *gtk.Label MemoEntry *gtk.Entry ButtonCancel *gtk.Button ButtonSend *gtk.Button } func NewTxBondDialogView() *TxBondDialogView { builder := NewViewBuilder(assets.TxBondDialogUI) view := &TxBondDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_transaction_bond"), SenderCombo: builder.GetComboBoxTextObj("id_combo_sender"), SenderHint: builder.GetLabelObj("id_hint_sender"), ReceiverCombo: builder.GetComboBoxTextObj("id_combo_receiver"), ReceiverHint: builder.GetLabelObj("id_hint_receiver"), PublicKeyEntry: builder.GetEntryObj("id_entry_public_key"), AmountEntry: builder.GetEntryObj("id_entry_amount"), AmountHint: builder.GetLabelObj("id_hint_amount"), FeeEntry: builder.GetEntryObj("id_entry_fee"), FeeHint: builder.GetLabelObj("id_hint_fee"), MemoEntry: builder.GetEntryObj("id_entry_memo"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), ButtonSend: builder.GetButtonObj("id_button_send"), } view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) view.ButtonSend.SetImage(gtkutil.ImageFromPixbuf(assets.IconSendPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/tx_transfer_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type TxTransferDialogView struct { ViewBuilder Dialog *gtk.Dialog SenderCombo *gtk.ComboBoxText SenderHint *gtk.Label ReceiverEntry *gtk.Entry ReceiverHint *gtk.Label AmountEntry *gtk.Entry AmountHint *gtk.Label FeeEntry *gtk.Entry FeeHint *gtk.Label MemoEntry *gtk.Entry ButtonCancel *gtk.Button ButtonSend *gtk.Button } func NewTxTransferDialogView() *TxTransferDialogView { builder := NewViewBuilder(assets.TxTransferDialogUI) view := &TxTransferDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_transaction_transfer"), SenderCombo: builder.GetComboBoxTextObj("id_combo_sender"), SenderHint: builder.GetLabelObj("id_hint_sender"), ReceiverEntry: builder.GetEntryObj("id_entry_receiver"), ReceiverHint: builder.GetLabelObj("id_hint_receiver"), AmountEntry: builder.GetEntryObj("id_entry_amount"), AmountHint: builder.GetLabelObj("id_hint_amount"), FeeEntry: builder.GetEntryObj("id_entry_fee"), FeeHint: builder.GetLabelObj("id_hint_fee"), MemoEntry: builder.GetEntryObj("id_entry_memo"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), ButtonSend: builder.GetButtonObj("id_button_send"), } view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) view.ButtonSend.SetImage(gtkutil.ImageFromPixbuf(assets.IconSendPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/tx_unbond_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type TxUnbondDialogView struct { ViewBuilder Dialog *gtk.Dialog ValidatorCombo *gtk.ComboBoxText ValidatorHint *gtk.Label MemoEntry *gtk.Entry ButtonCancel *gtk.Button ButtonSend *gtk.Button } func NewTxUnbondDialogView() *TxUnbondDialogView { builder := NewViewBuilder(assets.TxUnbondDialogUI) view := &TxUnbondDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_transaction_unbond"), ValidatorCombo: builder.GetComboBoxTextObj("id_combo_validator"), ValidatorHint: builder.GetLabelObj("id_hint_validator"), MemoEntry: builder.GetEntryObj("id_entry_memo"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), ButtonSend: builder.GetButtonObj("id_button_send"), } view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) view.ButtonSend.SetImage(gtkutil.ImageFromPixbuf(assets.IconSendPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/tx_withdraw_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type TxWithdrawDialogView struct { ViewBuilder Dialog *gtk.Dialog ValidatorCombo *gtk.ComboBoxText ValidatorHint *gtk.Label ReceiverCombo *gtk.ComboBoxText ReceiverHint *gtk.Label StakeEntry *gtk.Entry StakeHint *gtk.Label FeeEntry *gtk.Entry FeeHint *gtk.Label MemoEntry *gtk.Entry ButtonCancel *gtk.Button ButtonSend *gtk.Button } func NewTxWithdrawDialogView() *TxWithdrawDialogView { builder := NewViewBuilder(assets.TxWithdrawDialogUI) view := &TxWithdrawDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_transaction_withdraw"), ValidatorCombo: builder.GetComboBoxTextObj("id_combo_validator"), ValidatorHint: builder.GetLabelObj("id_hint_validator"), ReceiverCombo: builder.GetComboBoxTextObj("id_combo_receiver"), ReceiverHint: builder.GetLabelObj("id_hint_receiver"), StakeEntry: builder.GetEntryObj("id_entry_stake"), StakeHint: builder.GetLabelObj("id_hint_stake"), FeeEntry: builder.GetEntryObj("id_entry_fee"), FeeHint: builder.GetLabelObj("id_hint_fee"), MemoEntry: builder.GetEntryObj("id_entry_memo"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), ButtonSend: builder.GetButtonObj("id_button_send"), } view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) view.ButtonSend.SetImage(gtkutil.ImageFromPixbuf(assets.IconSendPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/validator_widget_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type ValidatorWidgetView struct { ViewBuilder Box *gtk.Box TreeViewValidators *gtk.TreeView listStore *gtk.ListStore } func NewValidatorWidgetView() *ValidatorWidgetView { builder := NewViewBuilder(assets.ValidatorWidgetUI) treeViewValidators := builder.GetTreeViewObj("id_treeview_validators") view := &ValidatorWidgetView{ ViewBuilder: builder, Box: builder.GetBoxObj("id_box_validator"), TreeViewValidators: treeViewValidators, } // Build list store for validator table. listStore, err := gtk.ListStoreNew( glib.TYPE_STRING, // no glib.TYPE_STRING, // address glib.TYPE_STRING, // number glib.TYPE_STRING, // stake glib.TYPE_STRING, // last bonding height glib.TYPE_STRING, // last sortition height glib.TYPE_STRING, // unbonding height glib.TYPE_STRING, // availability score ) gtkutil.FatalErrorCheck(err) view.listStore = listStore view.TreeViewValidators.SetModel(listStore.ToTreeModel()) // Columns. colNo := createTextColumn("No", 0) colAddress := createTextColumn("Address", 1) colNumber := createTextColumn("Number", 2) colStake := createTextColumn("Stake", 3) colBondingHeight := createTextColumn("Bonding Height", 4) colSortitionHeight := createTextColumn("Last Sortition Height", 5) colUnbondingHeight := createTextColumn("Unbonding Height", 6) colScore := createTextColumn("Availability Score", 7) view.TreeViewValidators.AppendColumn(colNo) view.TreeViewValidators.AppendColumn(colAddress) view.TreeViewValidators.AppendColumn(colNumber) view.TreeViewValidators.AppendColumn(colStake) view.TreeViewValidators.AppendColumn(colBondingHeight) view.TreeViewValidators.AppendColumn(colSortitionHeight) view.TreeViewValidators.AppendColumn(colUnbondingHeight) view.TreeViewValidators.AppendColumn(colScore) return view } func (view *ValidatorWidgetView) ClearRows() { view.listStore.Clear() } func (view *ValidatorWidgetView) AppendRow(cols []int, values []any) { iter := view.listStore.Append() _ = view.listStore.Set(iter, cols, values) } ================================================ FILE: cmd/gtk/view/view_builder.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) // ViewBuilder is a small embedded helper for views created from a gtk.Builder. type ViewBuilder struct { builder *gtk.Builder } func NewViewBuilder(ui []byte) ViewBuilder { builder, err := gtk.BuilderNewFromString(string(ui)) gtkutil.FatalErrorCheck(err) return ViewBuilder{builder: builder} } func (vb *ViewBuilder) Builder() *gtk.Builder { return vb.builder } func (vb *ViewBuilder) GetObj(name string) glib.IObject { obj, err := vb.builder.GetObject(name) gtkutil.FatalErrorCheck(err) return obj } func (vb *ViewBuilder) GetApplicationWindowObj(name string) *gtk.ApplicationWindow { return vb.GetObj(name).(*gtk.ApplicationWindow) } func (vb *ViewBuilder) GetDialogObj(name string) *gtk.Dialog { return vb.GetObj(name).(*gtk.Dialog) } func (vb *ViewBuilder) GetAboutDialogObj(name string) *gtk.AboutDialog { return vb.GetObj(name).(*gtk.AboutDialog) } func (vb *ViewBuilder) GetComboBoxTextObj(name string) *gtk.ComboBoxText { return vb.GetObj(name).(*gtk.ComboBoxText) } func (vb *ViewBuilder) GetEntryObj(name string) *gtk.Entry { return vb.GetObj(name).(*gtk.Entry) } func (vb *ViewBuilder) GetOverlayObj(name string) *gtk.Overlay { return vb.GetObj(name).(*gtk.Overlay) } func (vb *ViewBuilder) GetTreeViewObj(name string) *gtk.TreeView { return vb.GetObj(name).(*gtk.TreeView) } func (vb *ViewBuilder) GetTextViewObj(name string) *gtk.TextView { return vb.GetObj(name).(*gtk.TextView) } func (vb *ViewBuilder) GetBoxObj(name string) *gtk.Box { return vb.GetObj(name).(*gtk.Box) } func (vb *ViewBuilder) GetLabelObj(name string) *gtk.Label { return vb.GetObj(name).(*gtk.Label) } func (vb *ViewBuilder) GetToolButtonObj(name string) *gtk.ToolButton { return vb.GetObj(name).(*gtk.ToolButton) } func (vb *ViewBuilder) GetButtonObj(name string) *gtk.Button { return vb.GetObj(name).(*gtk.Button) } func (vb *ViewBuilder) GetImageObj(name string) *gtk.Image { return vb.GetObj(name).(*gtk.Image) } func (vb *ViewBuilder) GetProgressBarObj(name string) *gtk.ProgressBar { return vb.GetObj(name).(*gtk.ProgressBar) } func (vb *ViewBuilder) GetMenuItem(name string) *gtk.MenuItem { return vb.GetObj(name).(*gtk.MenuItem) } func (vb *ViewBuilder) BuildExtendedEntry(name string) *gtk.Entry { return gtkutil.BuildExtendedEntry(vb.builder, name) } func (vb *ViewBuilder) ConnectSignals(signals map[string]any) { vb.builder.ConnectSignals(signals) } ================================================ FILE: cmd/gtk/view/wallet_change_password_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type WalletChangePasswordDialogView struct { ViewBuilder Dialog *gtk.Dialog OldPasswordEntry *gtk.Entry OldPasswordLabel *gtk.Label NewPasswordEntry *gtk.Entry RepeatEntry *gtk.Entry ButtonOK *gtk.Button ButtonCancel *gtk.Button } func NewWalletChangePasswordDialogView() *WalletChangePasswordDialogView { builder := NewViewBuilder(assets.WalletChangePasswordDialogUI) view := &WalletChangePasswordDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_wallet_change_password"), OldPasswordEntry: builder.GetEntryObj("id_entry_old_password"), OldPasswordLabel: builder.GetLabelObj("id_label_old_password"), NewPasswordEntry: builder.GetEntryObj("id_entry_new_password"), RepeatEntry: builder.GetEntryObj("id_entry_repeat_password"), ButtonOK: builder.GetButtonObj("id_button_ok"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), } view.ButtonOK.SetImage(gtkutil.ImageFromPixbuf(assets.IconOkPixbuf16)) view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/wallet_create_address_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type WalletCreateAddressDialogView struct { ViewBuilder Dialog *gtk.Dialog LabelEntry *gtk.Entry AddressTypeCombo *gtk.ComboBoxText ButtonOK *gtk.Button ButtonCancel *gtk.Button } func NewWalletCreateAddressDialogView() *WalletCreateAddressDialogView { builder := NewViewBuilder(assets.WalletCreateAddressDialogUI) view := &WalletCreateAddressDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_wallet_create_address"), LabelEntry: builder.GetEntryObj("id_entry_account_label"), AddressTypeCombo: builder.GetComboBoxTextObj("id_combo_address_type"), ButtonOK: builder.GetButtonObj("id_button_ok"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), } view.ButtonOK.SetImage(gtkutil.ImageFromPixbuf(assets.IconOkPixbuf16)) view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/wallet_default_fee_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type WalletDefaultFeeDialogView struct { ViewBuilder Dialog *gtk.Dialog FeeEntry *gtk.Entry CurrentFeeLabel *gtk.Label ButtonOK *gtk.Button ButtonCancel *gtk.Button } func NewWalletDefaultFeeDialogView() *WalletDefaultFeeDialogView { builder := NewViewBuilder(assets.WalletSetDefaultFeeDialogUI) view := &WalletDefaultFeeDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_wallet_set_default_fee"), FeeEntry: builder.GetEntryObj("id_entry_default_fee"), CurrentFeeLabel: builder.GetLabelObj("id_label_current_fee_value"), ButtonOK: builder.GetButtonObj("id_button_ok"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), } view.ButtonOK.SetImage(gtkutil.ImageFromPixbuf(assets.IconOkPixbuf16)) view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/wallet_password_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type WalletPasswordDialogView struct { ViewBuilder Dialog *gtk.Dialog PasswordEntry *gtk.Entry ButtonOK *gtk.Button ButtonCancel *gtk.Button } func NewWalletPasswordDialogView() *WalletPasswordDialogView { builder := NewViewBuilder(assets.WalletPasswordDialogUI) view := &WalletPasswordDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_wallet_password"), PasswordEntry: builder.GetEntryObj("id_entry_password"), ButtonOK: builder.GetButtonObj("id_button_ok"), ButtonCancel: builder.GetButtonObj("id_button_cancel"), } view.ButtonOK.SetImage(gtkutil.ImageFromPixbuf(assets.IconOkPixbuf16)) view.ButtonCancel.SetImage(gtkutil.ImageFromPixbuf(assets.IconCancelPixbuf16)) return view } ================================================ FILE: cmd/gtk/view/wallet_seed_dialog_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type WalletSeedDialogView struct { ViewBuilder Dialog *gtk.Dialog TextView *gtk.TextView Image *gtk.Image ButtonClose *gtk.Button } func NewWalletSeedDialogView() *WalletSeedDialogView { builder := NewViewBuilder(assets.WalletShowSeedDialogUI) view := &WalletSeedDialogView{ ViewBuilder: builder, Dialog: builder.GetDialogObj("id_dialog_wallet_show_seed"), TextView: builder.GetTextViewObj("id_textview_seed"), Image: builder.GetImageObj("id_image_seed"), ButtonClose: builder.GetButtonObj("id_button_close"), } view.Image.SetFromPixbuf(assets.ImageSeedPixbuf) view.ButtonClose.SetImage(gtkutil.ImageFromPixbuf(assets.IconClosePixbuf16)) return view } ================================================ FILE: cmd/gtk/view/wallet_widget_view.go ================================================ //go:build gtk package view import ( "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" "github.com/pactus-project/pactus/cmd/gtk/assets" "github.com/pactus-project/pactus/cmd/gtk/gtkutil" ) type WalletWidgetView struct { ViewBuilder Box *gtk.Box TreeViewWallet *gtk.TreeView TreeViewTransactions *gtk.TreeView LabelName *gtk.Label LabelDriver *gtk.Label LabelCreatedAt *gtk.Label LabelLocation *gtk.Label LabelEncrypted *gtk.Label LabelTotalBalance *gtk.Label LabelDefaultFee *gtk.Label LabelTotalStake *gtk.Label BtnRefreshAddresses *gtk.ToolButton BtnNewAddress *gtk.ToolButton BtnSetDefaultFee *gtk.ToolButton BtnChangePassword *gtk.ToolButton BtnShowSeed *gtk.ToolButton BtnTxRefresh *gtk.ToolButton BtnTxPrev *gtk.ToolButton BtnTxNext *gtk.ToolButton ContextMenu *gtk.Menu MenuItemUpdateLabel *gtk.MenuItem MenuItemDetails *gtk.MenuItem MenuItemPrivateKey *gtk.MenuItem listStore *gtk.ListStore txListStore *gtk.ListStore } func createTextColumn(title string, columnID int) *gtk.TreeViewColumn { cellRenderer, err := gtk.CellRendererTextNew() gtkutil.FatalErrorCheck(err) column, err := gtk.TreeViewColumnNewWithAttribute(title, cellRenderer, "text", columnID) gtkutil.FatalErrorCheck(err) column.SetResizable(true) return column } func NewWalletWidgetView() *WalletWidgetView { builder := NewViewBuilder(assets.WalletWidgetUI) treeViewWallet := builder.GetTreeViewObj("id_treeview_addresses") treeViewTransactions := builder.GetTreeViewObj("id_treeview_transactions") view := &WalletWidgetView{ ViewBuilder: builder, Box: builder.GetBoxObj("id_box_wallet"), TreeViewWallet: treeViewWallet, TreeViewTransactions: treeViewTransactions, LabelName: builder.GetLabelObj("id_label_wallet_name"), LabelDriver: builder.GetLabelObj("id_label_wallet_driver"), LabelCreatedAt: builder.GetLabelObj("id_label_wallet_created_at"), LabelLocation: builder.GetLabelObj("id_label_wallet_location"), LabelEncrypted: builder.GetLabelObj("id_label_wallet_encrypted"), LabelTotalBalance: builder.GetLabelObj("id_label_wallet_total_balance"), LabelTotalStake: builder.GetLabelObj("id_label_wallet_total_stake"), LabelDefaultFee: builder.GetLabelObj("id_label_wallet_default_fee"), BtnRefreshAddresses: builder.GetToolButtonObj("id_button_refresh_addresses"), BtnNewAddress: builder.GetToolButtonObj("id_button_new_address"), BtnSetDefaultFee: builder.GetToolButtonObj("id_button_set_default_fee"), BtnChangePassword: builder.GetToolButtonObj("id_button_change_password"), BtnShowSeed: builder.GetToolButtonObj("id_button_show_seed"), BtnTxRefresh: builder.GetToolButtonObj("id_button_tx_refresh"), BtnTxPrev: builder.GetToolButtonObj("id_button_tx_prev"), BtnTxNext: builder.GetToolButtonObj("id_button_tx_next"), } // Toolbar icons. view.BtnRefreshAddresses.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconRefreshPixbuf16)) view.BtnNewAddress.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconAddPixbuf16)) view.BtnSetDefaultFee.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconFeePixbuf16)) view.BtnChangePassword.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconPasswordPixbuf16)) view.BtnShowSeed.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconSeedPixbuf16)) view.BtnTxRefresh.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconRefreshPixbuf16)) view.BtnTxPrev.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconPrevPixbuf16)) view.BtnTxNext.SetIconWidget(gtkutil.ImageFromPixbuf(assets.IconNextPixbuf16)) view.BtnTxPrev.SetSensitive(false) view.BtnTxNext.SetSensitive(false) // Build list store for address table. listStore, err := gtk.ListStoreNew( glib.TYPE_STRING, // No glib.TYPE_STRING, // Address glib.TYPE_STRING, // Label glib.TYPE_STRING, // Balance glib.TYPE_STRING, // Stake ) gtkutil.FatalErrorCheck(err) view.listStore = listStore view.TreeViewWallet.SetModel(listStore.ToTreeModel()) // Columns. colNo := createTextColumn("No", 0) colAddress := createTextColumn("Address", 1) colLabel := createTextColumn("Label", 2) colBalance := createTextColumn("Balance", 3) colStake := createTextColumn("Stake", 4) view.TreeViewWallet.AppendColumn(colNo) view.TreeViewWallet.AppendColumn(colAddress) view.TreeViewWallet.AppendColumn(colLabel) view.TreeViewWallet.AppendColumn(colBalance) view.TreeViewWallet.AppendColumn(colStake) // Transactions list store and columns. txStore, err := gtk.ListStoreNew( glib.TYPE_STRING, // no glib.TYPE_STRING, // id glib.TYPE_STRING, // sender glib.TYPE_STRING, // receiver glib.TYPE_STRING, // type glib.TYPE_STRING, // amount glib.TYPE_STRING, // direction glib.TYPE_STRING, // status glib.TYPE_STRING, // comment ) gtkutil.FatalErrorCheck(err) view.txListStore = txStore view.TreeViewTransactions.SetModel(txStore.ToTreeModel()) colTxNo := createTextColumn("#", 0) colTxID := createTextColumn("ID", 1) colTxSender := createTextColumn("Sender", 2) colTxReceiver := createTextColumn("Receiver", 3) colTxType := createTextColumn("Type", 4) colTxAmount := createTextColumn("Amount", 5) colTxDir := createTextColumn("Direction", 6) colTxStatus := createTextColumn("Status", 7) colTxComment := createTextColumn("Comment", 8) view.TreeViewTransactions.AppendColumn(colTxNo) view.TreeViewTransactions.AppendColumn(colTxID) view.TreeViewTransactions.AppendColumn(colTxSender) view.TreeViewTransactions.AppendColumn(colTxReceiver) view.TreeViewTransactions.AppendColumn(colTxType) view.TreeViewTransactions.AppendColumn(colTxAmount) view.TreeViewTransactions.AppendColumn(colTxDir) view.TreeViewTransactions.AppendColumn(colTxStatus) view.TreeViewTransactions.AppendColumn(colTxComment) // Context menu (actions are wired by controller). menu, err := gtk.MenuNew() gtkutil.FatalErrorCheck(err) view.ContextMenu = menu item, err := gtk.MenuItemNewWithLabel("Update _Label") gtkutil.FatalErrorCheck(err) item.SetUseUnderline(true) item.Show() menu.Append(item) view.MenuItemUpdateLabel = item item, err = gtk.MenuItemNewWithLabel("_Details") gtkutil.FatalErrorCheck(err) item.SetUseUnderline(true) item.Show() menu.Append(item) view.MenuItemDetails = item item, err = gtk.MenuItemNewWithLabel("_Private key") gtkutil.FatalErrorCheck(err) item.SetUseUnderline(true) item.Show() menu.Append(item) view.MenuItemPrivateKey = item return view } func (view *WalletWidgetView) ClearRows() { view.listStore.Clear() } func (view *WalletWidgetView) AppendRow(cols []int, values []any) { iter := view.listStore.Append() _ = view.listStore.Set(iter, cols, values) } func (view *WalletWidgetView) ClearTxRows() { view.txListStore.Clear() } func (view *WalletWidgetView) AppendTxRow(cols []int, values []any) { iter := view.txListStore.Append() _ = view.txListStore.Set(iter, cols, values) } func (view *WalletWidgetView) SetTxPager(prevEnabled, nextEnabled bool) { view.BtnTxPrev.SetSensitive(prevEnabled) view.BtnTxNext.SetSensitive(nextEnabled) } func (view *WalletWidgetView) SelectionAddress(addressColumn int) (string, bool, error) { selection, err := view.TreeViewWallet.GetSelection() if err != nil { return "", false, err } if selection == nil { return "", false, nil } model, iter, ok := selection.GetSelected() if !ok { return "", false, nil } val, err := model.(*gtk.TreeModel).GetValue(iter, addressColumn) if err != nil { return "", false, err } addr, err := val.GetString() if err != nil { return "", false, err } return addr, true, nil } ================================================ FILE: cmd/helper.go ================================================ package cmd import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" ) func ShortHash(id string) string { h, err := hash.FromString(id) if err != nil { return id } return h.ShortString() } func ShortAddress(addr string) string { a, err := crypto.AddressFromString(addr) if err != nil { return addr } return a.ShortString() } ================================================ FILE: cmd/importer.go ================================================ package cmd import ( "archive/zip" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "path/filepath" "slices" "time" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/downloader" ) const DefaultSnapshotURL = "https://snapshot.pactus.org" const maxDecompressedSize = 10 << 20 // 10 MB type ImporterStateFunc func(fileName string) func(stats downloader.Stats) type Metadata struct { Name string `json:"name"` CreatedAt string `json:"created_at"` Compress string `json:"compress"` Data SnapshotData `json:"data"` } type SnapshotData struct { Name string `json:"name"` Path string `json:"path"` Sha string `json:"sha"` Size uint64 `json:"size"` } func (md *Metadata) CreatedAtTime() time.Time { const layout = "2006-01-02T15:04:05.000000" parsedTime, err := time.Parse(layout, md.CreatedAt) if err != nil { return time.Time{} } return parsedTime } // Importer downloads and imports the pruned data from a centralized server. type Importer struct { snapshotURL string tempDir string storeDir string dataFileName string } func NewImporter(chainType genesis.ChainType, snapshotURL, storeDir string) (*Importer, error) { if util.PathExists(storeDir) { return nil, fmt.Errorf("data directory is not empty: %s", storeDir) } switch chainType { case genesis.Mainnet: snapshotURL += "/mainnet/" case genesis.Testnet: snapshotURL += "/testnet/" case genesis.Localnet: return nil, fmt.Errorf("unsupported chain type: %s", chainType) } tempDir := util.TempDirPath() return &Importer{ snapshotURL: snapshotURL, tempDir: tempDir, storeDir: storeDir, }, nil } func (i *Importer) GetMetadata(ctx context.Context) ([]Metadata, error) { cli := http.DefaultClient metaURL, err := url.JoinPath(i.snapshotURL, "metadata.json") if err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, http.MethodGet, metaURL, http.NoBody) if err != nil { return nil, err } resp, err := cli.Do(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, errors.New(resp.Status) } metadata := make([]Metadata, 0) dec := json.NewDecoder(resp.Body) if err := dec.Decode(&metadata); err != nil { return nil, err } slices.SortStableFunc(metadata, func(a, b Metadata) int { return b.CreatedAtTime().Compare(a.CreatedAtTime()) }) return metadata, nil } func (i *Importer) Download(ctx context.Context, metadata *Metadata, stateFunc ImporterStateFunc, ) error { dlLink, err := url.JoinPath(i.snapshotURL, metadata.Data.Path) if err != nil { return err } fileName := filepath.Base(dlLink) i.dataFileName = fileName filePath := fmt.Sprintf("%s/%s", i.tempDir, fileName) download := downloader.New(dlLink, filePath, metadata.Data.Sha, downloader.WithStatsCallback(stateFunc(fileName))) download.Start(ctx) return nil } func (i *Importer) Cleanup() error { return os.RemoveAll(i.tempDir) } func (i *Importer) ExtractAndStoreFiles() error { zipPath := filepath.Join(i.tempDir, i.dataFileName) reader, err := zip.OpenReader(zipPath) if err != nil { return fmt.Errorf("failed to open zip file: %w", err) } defer func() { _ = reader.Close() }() for _, file := range reader.File { if err := i.extractAndWriteFile(file); err != nil { return err } } return nil } func (i *Importer) extractAndWriteFile(file *zip.File) error { reader, err := file.Open() if err != nil { return fmt.Errorf("failed to open file in zip archive: %w", err) } defer func() { _ = reader.Close() }() fPath, err := util.SanitizeArchivePath(i.tempDir, file.Name) if err != nil { return fmt.Errorf("failed to make archive path: %w", err) } if file.FileInfo().IsDir() { return util.Mkdir(fPath) } if err := util.Mkdir(filepath.Dir(fPath)); err != nil { return fmt.Errorf("failed to create directory: %w", err) } outFile, err := os.Create(fPath) if err != nil { return fmt.Errorf("failed to create file: %w", err) } defer func() { _ = outFile.Close() }() // Use a limited reader to prevent DoS attacks via decompression bomb lr := &io.LimitedReader{R: reader, N: maxDecompressedSize} written, err := io.Copy(outFile, lr) if err != nil { return fmt.Errorf("failed to copy file contents: %w", err) } if written >= maxDecompressedSize { return fmt.Errorf("file exceeds maximum decompressed size limit: %s", fPath) } return nil } func (i *Importer) MoveStore() error { return util.MoveDirectory(filepath.Join(i.tempDir, "data"), i.storeDir) } ================================================ FILE: cmd/shell/main.go ================================================ package main import ( "encoding/base64" "fmt" "github.com/NathanBaulch/protoc-gen-cobra/client" "github.com/NathanBaulch/protoc-gen-cobra/naming" "github.com/c-bata/go-prompt" "github.com/inancgumus/screen" "github.com/pactus-project/pactus/util/shell" "github.com/pactus-project/pactus/util/terminal" pb "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/spf13/cobra" "github.com/spf13/pflag" "google.golang.org/grpc/metadata" ) const ( defaultServerAddr = "localhost:50051" defaultResponseFormat = "prettyjson" ) var _prefix string // createRootCommand creates and configures the root command with all subcommands // This function contains all the logic from main() but is testable. func createRootCommand() *cobra.Command { var ( serverAddr string username string password string ) rootCmd := &cobra.Command{ Use: "interactive", Short: "Pactus Shell", SilenceUsage: true, Long: "pactus-shell is a command line tool for interacting with the Pactus blockchain using gRPC", } interactive := shell.New(rootCmd, nil, prompt.OptionSuggestionBGColor(prompt.Black), prompt.OptionSuggestionTextColor(prompt.Green), prompt.OptionDescriptionBGColor(prompt.Black), prompt.OptionDescriptionTextColor(prompt.White), prompt.OptionLivePrefix(livePrefix), ) client.RegisterFlagBinder(func(fs *pflag.FlagSet, namer naming.Namer) { fs.StringVar(&username, namer("auth-username"), "", "username for gRPC basic authentication") fs.StringVar(&password, namer("auth-password"), "", "password for gRPC basic authentication") }) interactive.Flags().StringVar(&serverAddr, "server-addr", defaultServerAddr, "gRPC server address") interactive.Flags().StringVar(&username, "auth-username", "", "username for gRPC basic authentication") interactive.Flags().StringVar(&password, "auth-password", "", "password for gRPC basic authentication") interactive.PreRun = func(_ *cobra.Command, _ []string) { cls() terminal.PrintInfoMsgf("Welcome to PactusBlockchain interactive mode\n\n- Home: https://pactus.org\n- " + "Docs: https://docs.pactus.org") terminal.PrintLine() _prefix = fmt.Sprintf("pactus@%s > ", serverAddr) } interactive.PersistentPreRun = func(cmd *cobra.Command, _ []string) { setAuthContext(cmd, username, password) } rootCmd.PersistentPreRun = func(cmd *cobra.Command, _ []string) { setAuthContext(cmd, username, password) } changeDefaultParameters := func(cobra *cobra.Command) *cobra.Command { _ = cobra.PersistentFlags().Lookup("server-addr").Value.Set(defaultServerAddr) cobra.PersistentFlags().Lookup("server-addr").DefValue = defaultServerAddr _ = cobra.PersistentFlags().Lookup("response-format").Value.Set(defaultResponseFormat) cobra.PersistentFlags().Lookup("response-format").DefValue = defaultResponseFormat return cobra } rootCmd.AddCommand(changeDefaultParameters(pb.BlockchainClientCommand())) rootCmd.AddCommand(changeDefaultParameters(pb.NetworkClientCommand())) rootCmd.AddCommand(changeDefaultParameters(pb.TransactionClientCommand())) rootCmd.AddCommand(changeDefaultParameters(pb.WalletClientCommand())) rootCmd.AddCommand(changeDefaultParameters(pb.UtilsClientCommand())) rootCmd.AddCommand(clearScreen()) interactive.Use = "interactive" interactive.Short = "Start pactus-shell in interactive mode" rootCmd.AddCommand(interactive) return rootCmd } func main() { rootCmd := createRootCommand() err := rootCmd.Execute() if err != nil { terminal.PrintErrorMsgf(err.Error()) } } func livePrefix() (string, bool) { return _prefix, true } func clearScreen() *cobra.Command { return &cobra.Command{ Use: "clear", Short: "clear screen", Run: func(_ *cobra.Command, _ []string) { cls() }, } } func cls() { screen.MoveTopLeft() screen.Clear() } func setAuthContext(c *cobra.Command, username, password string) { if username != "" && password != "" { auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) md := metadata.Pairs("authorization", "Basic "+auth) ctx := metadata.NewOutgoingContext(c.Context(), md) c.SetContext(ctx) } } ================================================ FILE: cmd/shell/main_test.go ================================================ package main import ( "testing" "github.com/spf13/cobra" "github.com/stretchr/testify/require" ) func TestCreateRootCommand(t *testing.T) { // This executes the ENTIRE main() logic including all changed lines rootCmd := createRootCommand() // Verify the root command properties require.Equal(t, "interactive", rootCmd.Use) require.Equal(t, "Pactus Shell", rootCmd.Short) require.Contains(t, rootCmd.Long, "pactus-shell is a command line tool") require.True(t, rootCmd.SilenceUsage) // Verify interactive command was added var interactiveCmd *cobra.Command for _, cmd := range rootCmd.Commands() { if cmd.Use == "interactive" { interactiveCmd = cmd break } } require.NotNil(t, interactiveCmd, "interactive command should be added") require.Equal(t, "interactive", interactiveCmd.Use) require.Equal(t, "Start pactus-shell in interactive mode", interactiveCmd.Short) // Verify flags were set up serverAddrFlag := interactiveCmd.Flags().Lookup("server-addr") require.NotNil(t, serverAddrFlag) require.Equal(t, defaultServerAddr, serverAddrFlag.DefValue) usernameFlag := interactiveCmd.Flags().Lookup("auth-username") require.NotNil(t, usernameFlag) passwordFlag := interactiveCmd.Flags().Lookup("auth-password") require.NotNil(t, passwordFlag) // Verify PreRun and PersistentPreRun are set require.NotNil(t, interactiveCmd.PreRun) require.NotNil(t, interactiveCmd.PersistentPreRun) // Execute PreRun to hit interactiveCmd.PreRun(nil, nil) // Execute PersistentPreRun testCmd := &cobra.Command{} testCmd.SetContext(t.Context()) interactiveCmd.PersistentPreRun(testCmd, nil) // Verify other commands were added var clearCmd *cobra.Command for _, cmd := range rootCmd.Commands() { if cmd.Use == "clear" { clearCmd = cmd break } } require.NotNil(t, clearCmd) rootCmd.SetArgs([]string{"--help"}) err := rootCmd.Execute() require.NoError(t, err) rootCmd.SetArgs([]string{"interactive", "--help"}) err = rootCmd.Execute() require.NoError(t, err) // Test that main function would work require.NotNil(t, rootCmd) require.Equal(t, "interactive", rootCmd.Use) } // TestLivePrefix tests the livePrefix function. func TestLivePrefix(t *testing.T) { _prefix = "test@localhost > " prefix, ok := livePrefix() require.True(t, ok) require.Equal(t, "test@localhost > ", prefix) } // TestClearScreenCommand tests the clearScreen function. func TestClearScreenCommand(t *testing.T) { clearCmd := clearScreen() require.NotNil(t, clearCmd) require.Equal(t, "clear", clearCmd.Use) require.Equal(t, "clear screen", clearCmd.Short) require.NotNil(t, clearCmd.Run) // Test that the Run function works without error clearCmd.Run(nil, nil) } // TestSetAuthContext tests the setAuthContext function. func TestSetAuthContext(t *testing.T) { rootCmd := &cobra.Command{} rootCmd.SetContext(t.Context()) // Test with empty credentials (should not modify context) originalCtx := rootCmd.Context() setAuthContext(rootCmd, "", "") require.Equal(t, originalCtx, rootCmd.Context()) // Test with valid credentials (should set auth context) setAuthContext(rootCmd, "testuser", "testpass") require.NotNil(t, rootCmd.Context()) require.NotEqual(t, originalCtx, rootCmd.Context()) } // TestConstants tests the defined constants. func TestConstants(t *testing.T) { require.Equal(t, "localhost:50051", defaultServerAddr) require.Equal(t, "prettyjson", defaultResponseFormat) } // TestClsFunction tests the cls function doesn't panic. func TestClsFunction(t *testing.T) { require.NotPanics(t, func() { cls() }, "calling cls() should not panic") } ================================================ FILE: cmd/wallet/address.go ================================================ package main import ( "context" "fmt" "strings" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/types" "github.com/spf13/cobra" ) // buildAddressCmd builds all sub-commands related to addresses. func buildAddressCmd(parentCmd *cobra.Command) { addressCmd := &cobra.Command{ Use: "address", Short: "manage the address book", } parentCmd.AddCommand(addressCmd) buildAddressAllCmd(addressCmd) buildAddressNewCmd(addressCmd) buildAddressBalanceCmd(addressCmd) buildAddressPrivCmd(addressCmd) buildAddressPubCmd(addressCmd) buildAddressImportCmd(addressCmd) buildAddressLabelCmd(addressCmd) } // buildAddressAllCmd builds a command to list all addresses from the wallet. func buildAddressAllCmd(parentCmd *cobra.Command) { allCmd := &cobra.Command{ Use: "all", Short: "displays all stored addresses", } parentCmd.AddCommand(allCmd) balanceOpt := allCmd.Flags().Bool("balance", false, "displays the account balance for each address") stakeOpt := allCmd.Flags().Bool("stake", false, "displays the validator stake for each address") allCmd.Run = func(_ *cobra.Command, _ []string) { wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() terminal.PrintLine() for i, info := range wlt.ListAddresses() { line := fmt.Sprintf("%v- %s\t", i+1, info.Address) if *balanceOpt { balance, _ := wlt.Balance(info.Address) line += fmt.Sprintf("%s\t", balance.String()) } if *stakeOpt { stake, _ := wlt.Stake(info.Address) line += fmt.Sprintf("%s\t", stake.String()) } line += info.Label terminal.PrintInfoMsgf(line) } } } // buildAddressNewCmd builds a command for creating a new wallet address. func buildAddressNewCmd(parentCmd *cobra.Command) { newCmd := &cobra.Command{ Use: "new", Short: "creating a new address", } parentCmd.AddCommand(newCmd) addressType := newCmd.Flags().String("type", crypto.AddressTypeEd25519Account.String(), "the type of address: ed25519_account, bls_account and validator") label := newCmd.Flags().String("label", "", "a label for the address") newCmd.Run = func(_ *cobra.Command, _ []string) { var addressInfo *types.AddressInfo var err error if *label == "" { labelIn := prompt.PromptInput("Label") label = &labelIn } wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() switch *addressType { case crypto.AddressTypeValidator.String(): addressInfo, err = wlt.NewAddress(crypto.AddressTypeValidator, *label) case crypto.AddressTypeBLSAccount.String(): addressInfo, err = wlt.NewAddress(crypto.AddressTypeBLSAccount, *label) case crypto.AddressTypeEd25519Account.String(): password := "" if wlt.IsEncrypted() { password = prompt.PromptPassword("Password", false) } addressInfo, err = wlt.NewAddress(crypto.AddressTypeEd25519Account, *label, wallet.WithPassword(password)) default: err = fmt.Errorf("invalid address type '%s'", *addressType) } terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintInfoMsgf("%s", addressInfo.Address) } } // buildAddressBalanceCmd builds a command to display the balance of a given address. func buildAddressBalanceCmd(parentCmd *cobra.Command) { balanceCmd := &cobra.Command{ Use: "balance [flags]
", Short: "displays the balance of an address", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(balanceCmd) balanceCmd.Run = func(_ *cobra.Command, args []string) { addr := args[0] wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() terminal.PrintLine() balance, _ := wlt.Balance(addr) stake, _ := wlt.Stake(addr) terminal.PrintInfoMsgf("balance: %s\tstake: %s", balance.String(), stake.String()) } } // buildAddressPrivCmd builds a command to show the private key of a given address. func buildAddressPrivCmd(parentCmd *cobra.Command) { privCmd := &cobra.Command{ Use: "priv [flags]
", Short: "displays the private key for a specified address", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(privCmd) passOpt := addPasswordOption(privCmd) privCmd.Run = func(_ *cobra.Command, args []string) { addr := args[0] wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() password := getPassword(wlt, *passOpt) prv, err := wlt.PrivateKey(password, addr) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintWarnMsgf("Private Key: %v", prv) } } // buildAddressPubCmd builds a command to show the public key of a given address. func buildAddressPubCmd(parentCmd *cobra.Command) { pubCmd := &cobra.Command{ Use: "pub [flags]
", Short: "displays the public key for a specified address", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(pubCmd) pubCmd.Run = func(_ *cobra.Command, args []string) { addr := args[0] wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() info, err := wlt.AddressInfo(addr) if err != nil { terminal.PrintErrorMsgf(err.Error()) return } terminal.PrintLine() terminal.PrintInfoMsgf("Public Key: %v", info.PublicKey) if info.Path != "" { terminal.PrintInfoMsgf("Path: %v", info.Path) } } } // buildAddressImportCmd build a command to import a private key into the wallet. func buildAddressImportCmd(parentCmd *cobra.Command) { importCmd := &cobra.Command{ Use: "import", Short: "imports a private key into wallet", } parentCmd.AddCommand(importCmd) passOpt := addPasswordOption(importCmd) importCmd.Run = func(_ *cobra.Command, _ []string) { prvStr := prompt.PromptInput("Private Key") wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() password := getPassword(wlt, *passOpt) maybeBLSPrivateKey := func(str string) bool { // BLS private keys start with "SECRET1P..." or "TSECRET1P...". return strings.Contains(strings.ToLower(str), "secret1p") } maybeEd25519PrivateKey := func(str string) bool { // Ed25519 private keys start with "SECRET1R..." or "TSECRET1R...". return strings.Contains(strings.ToLower(str), "secret1r") } switch { case maybeBLSPrivateKey(prvStr): blsPrv, err := bls.PrivateKeyFromString(prvStr) terminal.FatalErrorCheck(err) err = wlt.ImportBLSPrivateKey(password, blsPrv) terminal.FatalErrorCheck(err) case maybeEd25519PrivateKey(prvStr): ed25519Prv, err := ed25519.PrivateKeyFromString(prvStr) terminal.FatalErrorCheck(err) err = wlt.ImportEd25519PrivateKey(password, ed25519Prv) terminal.FatalErrorCheck(err) default: // The private key cannot be decoded as either BLS or Ed25519. terminal.PrintErrorMsgf("Invalid private key.") return } terminal.PrintLine() terminal.PrintSuccessMsgf("Private Key imported successfully.") } } // buildAddressLabelCmd build a command to set or update the label for an address. func buildAddressLabelCmd(parentCmd *cobra.Command) { labelCmd := &cobra.Command{ Use: "label [flags]
", Short: "assigns or update a label for a specific address", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(labelCmd) labelCmd.Run = func(_ *cobra.Command, args []string) { addr := args[0] wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() oldLabel := wlt.AddressLabel(addr) newLabel := prompt.PromptInputWithSuggestion("Label", oldLabel) err = wlt.SetAddressLabel(addr, newLabel) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintSuccessMsgf("Label set successfully") } } ================================================ FILE: cmd/wallet/create.go ================================================ package main import ( "context" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/spf13/cobra" ) // buildCreateCmd builds a command to create a new wallet. func buildCreateCmd(parentCmd *cobra.Command) { createCmd := &cobra.Command{ Use: "create", Short: "create a new wallet", } parentCmd.AddCommand(createCmd) testnetOpt := createCmd.Flags().Bool("testnet", false, "create a wallet for the testnet environment") entropyOpt := createCmd.Flags().Int("entropy", 128, "specify the entropy bit length") createCmd.Run = func(_ *cobra.Command, _ []string) { password := prompt.PromptPassword("Password", true) mnemonic, err := wallet.GenerateMnemonic(*entropyOpt) terminal.FatalErrorCheck(err) network := genesis.Mainnet if *testnetOpt { network = genesis.Testnet } wlt, err := wallet.Create(context.Background(), *pathOpt, mnemonic, password, network) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Wallet successfully created at: %s", wlt.Path()) terminal.PrintLine() terminal.PrintInfoMsgf("🌱 Your wallet seed phrase:") terminal.PrintInfoMsgBoldf(" %v", mnemonic) terminal.PrintLine() terminal.PrintWarnMsgf("⚠️ CRITICAL: Write down this seed phrase and store it safely!") terminal.PrintWarnMsgf(" This is the ONLY way to recover your wallet if needed.") terminal.PrintWarnMsgf(" Never share it with anyone or store it electronically.") } } ================================================ FILE: cmd/wallet/fee.go ================================================ package main import ( "context" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) // buildFeeCmd builds sub-command to set the default fee for the wallet. func buildFeeCmd(parentCmd *cobra.Command) { feeCmd := &cobra.Command{ Use: "fee [flags] ", Short: "set the default fee for the wallet", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(feeCmd) feeCmd.Run = func(_ *cobra.Command, args []string) { wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() fee, err := amount.FromString(args[0]) terminal.FatalErrorCheck(err) err = wlt.SetDefaultFee(fee) terminal.FatalErrorCheck(err) terminal.PrintInfoMsgf("Default fee is set to %s", fee.String()) } } ================================================ FILE: cmd/wallet/info.go ================================================ package main import ( "context" "time" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) // buildInfoCmd builds all sub-commands related to the wallet information. func buildInfoCmd(parentCmd *cobra.Command) { infoCmd := &cobra.Command{ Use: "info", Short: "retrieving the wallet information", } parentCmd.AddCommand(infoCmd) infoCmd.Run = func(_ *cobra.Command, _ []string) { wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() info := wlt.Info() terminal.PrintInfoMsgf("Version: %d", info.Version) terminal.PrintInfoMsgf("UUID: %s", info.UUID) terminal.PrintInfoMsgf("Driver: %s", info.Driver) terminal.PrintInfoMsgf("Created At: %s", info.CreatedAt.Format(time.RFC1123)) terminal.PrintInfoMsgf("Default Fee: %s", info.DefaultFee.String()) terminal.PrintInfoMsgf("Encrypted: %t", info.Encrypted) terminal.PrintInfoMsgf("Neutered: %t", info.Neutered) terminal.PrintInfoMsgf("Network: %s", info.Network) } } ================================================ FILE: cmd/wallet/main.go ================================================ package main import ( "context" "time" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/provider/offline" "github.com/pactus-project/pactus/wallet/provider/remote" "github.com/spf13/cobra" ) var ( pathOpt *string offlineOpt *bool serverAddrsOpt *[]string timeoutOpt *int ) func addPasswordOption(c *cobra.Command) *string { return c.Flags().StringP("password", "p", "", "the wallet password") } func openWallet(ctx context.Context) (*wallet.Wallet, error) { wlt, err := wallet.Open(ctx, *pathOpt, wallet.WithLockMode(false)) if err != nil { return nil, err } err = setProvider(ctx, wlt) if err != nil { return nil, err } return wlt, err } func setProvider(ctx context.Context, wlt *wallet.Wallet) error { if *offlineOpt { wlt.SetProvider(offline.NewOfflineBlockchainProvider()) return nil } var opts []remote.RemoteProviderOption if *serverAddrsOpt != nil { opts = append(opts, remote.WithCustomServers(*serverAddrsOpt)) } if *timeoutOpt > 0 { opts = append(opts, remote.WithTimeout(time.Duration(*timeoutOpt)*time.Second)) } provider, err := remote.NewRemoteBlockchainProvider(ctx, wlt.Info().Network, opts...) if err != nil { return err } wlt.SetProvider(provider) return nil } func main() { rootCmd := &cobra.Command{ Use: "pactus-wallet", Short: "Pactus wallet", CompletionOptions: cobra.CompletionOptions{HiddenDefaultCmd: true}, } // Hide the "help" sub-command rootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) pathOpt = rootCmd.PersistentFlags().String("path", cmd.PactusDefaultWalletPath(cmd.PactusDefaultHomeDir()), "the path to the wallet file") offlineOpt = rootCmd.PersistentFlags().Bool("offline", false, "offline mode") serverAddrsOpt = rootCmd.PersistentFlags().StringSlice("servers", nil, "servers gRPC address") timeoutOpt = rootCmd.PersistentFlags().Int("timeout", 1, "specifies the timeout duration for the connection in seconds") buildCreateCmd(rootCmd) buildRecoverCmd(rootCmd) buildGetSeedCmd(rootCmd) buildFeeCmd(rootCmd) buildPasswordCmd(rootCmd) buildSendCmd(rootCmd) buildAddressCmd(rootCmd) buildTransactionCmd(rootCmd) buildInfoCmd(rootCmd) buildNeuterCmd(rootCmd) err := rootCmd.Execute() if err != nil { terminal.PrintErrorMsgf(err.Error()) } } ================================================ FILE: cmd/wallet/neuter.go ================================================ package main import ( "context" "fmt" "github.com/ipfs/boxo/util" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) func buildNeuterCmd(parentCmd *cobra.Command) { neuterCmd := &cobra.Command{ Use: "neuter", Short: "convert full wallet to neutered wallet and can only be used to retrieve balances or stakes", } parentCmd.AddCommand(neuterCmd) neuterCmd.Run = func(_ *cobra.Command, _ []string) { wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() path := wlt.Path() + ".neutered" if util.FileExists(path) { terminal.FatalErrorCheck(fmt.Errorf("neutered wallet already exists, at %s", path)) } err = wlt.Neuter(path) terminal.FatalErrorCheck(err) terminal.PrintSuccessMsgf("neutered wallet created at %s", path) } } ================================================ FILE: cmd/wallet/password.go ================================================ package main import ( "context" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/spf13/cobra" ) // buildPasswordCmd builds a command to update the wallet's password. func buildPasswordCmd(parentCmd *cobra.Command) { passwordCmd := &cobra.Command{ Use: "password", Short: "changes the wallet's password", } parentCmd.AddCommand(passwordCmd) passOpt := addPasswordOption(passwordCmd) passwordCmd.Run = func(_ *cobra.Command, _ []string) { wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() oldPassword := getPassword(wlt, *passOpt) newPassword := prompt.PromptPassword("New Password", true) err = wlt.UpdatePassword(oldPassword, newPassword) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintWarnMsgf("Your wallet password successfully updated.") } } ================================================ FILE: cmd/wallet/recover.go ================================================ package main import ( "context" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/spf13/cobra" ) // buildRecoverCmd builds a command to recover a wallet using a mnemonic (seed phrase). func buildRecoverCmd(parentCmd *cobra.Command) { recoverCmd := &cobra.Command{ Use: "recover", Short: "recover wallet from the seed phrase or mnemonic", } parentCmd.AddCommand(recoverCmd) passOpt := addPasswordOption(recoverCmd) testnetOpt := recoverCmd.Flags().Bool("testnet", false, "recover the wallet for the testnet environment") seedOpt := recoverCmd.Flags().StringP("seed", "s", "", "mnemonic or seed phrase used for wallet recovery") recoverCmd.Run = func(_ *cobra.Command, _ []string) { mnemonic := *seedOpt if mnemonic == "" { mnemonic = prompt.PromptInput("Seed") } chainType := genesis.Mainnet if *testnetOpt { chainType = genesis.Testnet } ctx := context.Background() wlt, err := wallet.Create(ctx, *pathOpt, mnemonic, *passOpt, chainType) terminal.FatalErrorCheck(err) err = setProvider(ctx, wlt) terminal.FatalErrorCheck(err) cmd.RecoverWalletAddresses(wlt, *passOpt) // Always save the wallet before exiting terminal.PrintLine() terminal.PrintInfoMsgf("💾 Saving wallet...") terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Wallet successfully recovered and saved at: %s", wlt.Path()) } } // buildGetSeedCmd builds a command to display the wallet's mnemonic (seed phrase). func buildGetSeedCmd(parentCmd *cobra.Command) { getSeedCmd := &cobra.Command{ Use: "seed", Short: "displays the seed phrase that can be used to recover this wallet", } parentCmd.AddCommand(getSeedCmd) passOpt := addPasswordOption(getSeedCmd) getSeedCmd.Run = func(_ *cobra.Command, _ []string) { wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() password := getPassword(wlt, *passOpt) mnemonic, err := wlt.Mnemonic(password) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintInfoMsgf("🌱 Your wallet seed phrase:") terminal.PrintInfoMsgBoldf(" %v", mnemonic) terminal.PrintLine() terminal.PrintWarnMsgf("⚠️ CRITICAL: Write down this seed phrase and store it safely!") terminal.PrintWarnMsgf(" This is the ONLY way to recover your wallet if needed.") terminal.PrintWarnMsgf(" Never share it with anyone or store it electronically.") } } ================================================ FILE: cmd/wallet/send.go ================================================ package main import ( "context" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/prompt" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/spf13/cobra" ) // buildSendCmd builds all sub-commands related to the transactions. func buildSendCmd(parentCmd *cobra.Command) { txCmd := &cobra.Command{ Use: "send", Short: "create, sign and send a transaction", } parentCmd.AddCommand(txCmd) buildSendTransferCmd(txCmd) buildSendBondCmd(txCmd) buildSendUnbondCmd(txCmd) buildSendWithdrawCmd(txCmd) } // buildSendTransferCmd builds a command for create, sign and publish a `Transfer` transaction. func buildSendTransferCmd(parentCmd *cobra.Command) { transferCmd := &cobra.Command{ Use: "transfer [flags] ", Short: "create, sign and publish a `Transfer` transaction", Args: cobra.ExactArgs(3), } parentCmd.AddCommand(transferCmd) lockTimeOpt, feeOpt, memoOpt, noConfirmOpt := addCommonTxOptions(transferCmd) passOpt := addPasswordOption(transferCmd) transferCmd.Run = func(_ *cobra.Command, args []string) { sender := args[0] receiver := args[1] amt, err := amount.FromString(args[2]) terminal.FatalErrorCheck(err) wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() opts := []wallet.TxOption{ wallet.OptionFee(*feeOpt), wallet.OptionLockTime(types.Height(*lockTimeOpt)), wallet.OptionMemo(*memoOpt), } trx, err := wlt.MakeTransferTx(sender, receiver, amt, opts...) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintInfoMsgf("📝 Transaction Details:") terminal.PrintInfoMsgf(" Type : Transfer") terminal.PrintInfoMsgf(" From : %s", sender) terminal.PrintInfoMsgf(" To : %s", receiver) terminal.PrintInfoMsgf(" Amount : %s", amt) terminal.PrintInfoMsgf(" Fee : %s", trx.Fee()) terminal.PrintInfoMsgf(" Memo : %s", trx.Memo()) signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt) } } // buildSendBondCmd builds a command for create, sign and publish a `Bond` transaction. func buildSendBondCmd(parentCmd *cobra.Command) { bondCmd := &cobra.Command{ Use: "bond [flags] ", Short: "create, sign and publish a `Bond` transaction", Args: cobra.ExactArgs(3), } parentCmd.AddCommand(bondCmd) pubKeyOpt := bondCmd.Flags().String("pub", "", "validator's public key") delegateOwnerOpt := bondCmd.Flags().String("delegate-owner", "", "delegation stake owner account address") delegateShareOpt := bondCmd.Flags().String("delegate-share", "", "delegation owner share in PAC (0 to 0.7)") delegateExpiryOpt := bondCmd.Flags().Uint32("delegate-expiry", 0, "delegation expiry block height") lockTime, feeOpt, memoOpt, noConfirmOpt := addCommonTxOptions(bondCmd) passOpt := addPasswordOption(bondCmd) bondCmd.Run = func(_ *cobra.Command, args []string) { sender := args[0] receiver := args[1] amt, err := amount.FromString(args[2]) terminal.FatalErrorCheck(err) wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() opts := []wallet.TxOption{ wallet.OptionFee(*feeOpt), wallet.OptionLockTime(types.Height(*lockTime)), wallet.OptionMemo(*memoOpt), wallet.OptionDelegateOwner(*delegateOwnerOpt), wallet.OptionDelegateShare(*delegateShareOpt), wallet.OptionDelegateExpiry(types.Height(*delegateExpiryOpt)), } trx, err := wlt.MakeBondTx(sender, receiver, *pubKeyOpt, amt, opts...) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintInfoMsgf("📝 Transaction Details:") terminal.PrintInfoMsgf(" Type : Bond") terminal.PrintInfoMsgf(" Account : %s", sender) terminal.PrintInfoMsgf(" Validator: %s", receiver) terminal.PrintInfoMsgf(" Stake : %s", amt) terminal.PrintInfoMsgf(" Fee : %s", trx.Fee()) terminal.PrintInfoMsgf(" Memo : %s", trx.Memo()) signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt) } } // buildSendUnbondCmd builds a command for create, sign and publish a `Unbond` transaction. func buildSendUnbondCmd(parentCmd *cobra.Command) { unbondCmd := &cobra.Command{ Use: "unbond [flags]
", Short: "create, sign and publish an `Unbond` transaction", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(unbondCmd) lockTime, feeOpt, memoOpt, noConfirmOpt := addCommonTxOptions(unbondCmd) delegateOwnerOpt := unbondCmd.Flags().String("delegate-owner", "", "delegation stake owner account address") passOpt := addPasswordOption(unbondCmd) unbondCmd.Run = func(_ *cobra.Command, args []string) { from := args[0] wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() opts := []wallet.TxOption{ wallet.OptionFee(*feeOpt), wallet.OptionLockTime(types.Height(*lockTime)), wallet.OptionMemo(*memoOpt), wallet.OptionDelegateOwner(*delegateOwnerOpt), } trx, err := wlt.MakeUnbondTx(from, opts...) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintInfoMsgf("📝 Transaction Details:") terminal.PrintInfoMsgf(" Type : Unbond") terminal.PrintInfoMsgf(" Validator: %s", from) terminal.PrintInfoMsgf(" Fee : %s", trx.Fee()) terminal.PrintInfoMsgf(" Memo : %s", trx.Memo()) signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt) } } // buildSendWithdrawCmd builds a command for create, sign and publish a `Withdraw` transaction. func buildSendWithdrawCmd(parentCmd *cobra.Command) { withdrawCmd := &cobra.Command{ Use: "withdraw [flags] ", Short: "create, sign and publish a `Withdraw` transaction", Args: cobra.ExactArgs(3), } parentCmd.AddCommand(withdrawCmd) lockTime, feeOpt, memoOpt, noConfirmOpt := addCommonTxOptions(withdrawCmd) passOpt := addPasswordOption(withdrawCmd) withdrawCmd.Run = func(_ *cobra.Command, args []string) { sender := args[0] receiver := args[1] amt, err := amount.FromString(args[2]) terminal.FatalErrorCheck(err) wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() opts := []wallet.TxOption{ wallet.OptionFee(*feeOpt), wallet.OptionLockTime(types.Height(*lockTime)), wallet.OptionMemo(*memoOpt), } trx, err := wlt.MakeWithdrawTx(sender, receiver, amt, opts...) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintInfoMsgf("📝 Transaction Details:") terminal.PrintInfoMsgf(" Type : Withdraw") terminal.PrintInfoMsgf(" Validator: %s", sender) terminal.PrintInfoMsgf(" Account : %s", receiver) terminal.PrintInfoMsgf(" Amount : %s", amt) terminal.PrintInfoMsgf(" Fee : %s", trx.Fee()) terminal.PrintInfoMsgf(" Memo : %s", trx.Memo()) signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt) } } func addCommonTxOptions(cobra *cobra.Command) (lockTimeOpt *int, feeOpt, memoOpt *string, noConfirmOpt *bool) { lockTimeOpt = cobra.Flags().Int("lock-time", 0, "transaction lock-time, if not specified will be the latest height") feeOpt = cobra.Flags().String("fee", "", "transaction fee in PAC, if not specified will set to the estimated value") memoOpt = cobra.Flags().String("memo", "", "transaction memo, maximum should be 64 character") noConfirmOpt = cobra.Flags().Bool("no-confirm", false, "no confirmation question") return lockTimeOpt, feeOpt, memoOpt, noConfirmOpt } func signAndPublishTx(wlt *wallet.Wallet, trx *tx.Tx, noConfirm bool, pass string) { terminal.PrintLine() password := getPassword(wlt, pass) err := wlt.SignTransaction(password, trx) terminal.FatalErrorCheck(err) bs, _ := trx.Bytes() terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Transaction signed successfully") terminal.PrintInfoMsgf(" Signed transaction data: %x", bs) terminal.PrintLine() if !*offlineOpt { if !noConfirm { terminal.PrintWarnMsgf("⚠️ You are going to broadcast the signed transaction") terminal.PrintWarnMsgf(" This action cannot be undone") terminal.PrintLine() confirmed := prompt.PromptConfirm("Do you want to continue") if !confirmed { return } } res, err := wlt.BroadcastTransaction(trx) terminal.FatalErrorCheck(err) terminal.PrintLine() terminal.PrintSuccessMsgf("✅ Transaction broadcast successfully!") terminal.PrintInfoMsgf(" Transaction ID: %s", res) } } func getPassword(wlt *wallet.Wallet, passOpt string) string { password := passOpt if wlt.IsEncrypted() && password == "" { password = prompt.PromptPassword("Wallet password", false) } return password } ================================================ FILE: cmd/wallet/transaction.go ================================================ package main import ( "context" "fmt" "github.com/pactus-project/pactus/cmd" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/util/terminal" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/types" "github.com/spf13/cobra" ) // buildTransactionCmd builds all sub-commands related to the wallet transactions. func buildTransactionCmd(parentCmd *cobra.Command) { transactionCmd := &cobra.Command{ Use: "transaction", Short: "Manage and view wallet transactions", Long: "The 'transactions' command allows you to list existing transactions with optional filtering", } parentCmd.AddCommand(transactionCmd) buildTransactionAddCmd(transactionCmd) buildTransactionListCmd(transactionCmd) } // buildTransactionsAddCmd builds the command for adding a transaction to the wallet. func buildTransactionAddCmd(parentCmd *cobra.Command) { addCmd := &cobra.Command{ Use: "add [flags] ", Short: "Add a transaction to the wallet", Long: "Add a specific transaction to the wallet using its transaction ID", Args: cobra.ExactArgs(1), } parentCmd.AddCommand(addCmd) addCmd.Run = func(_ *cobra.Command, args []string) { txID := args[0] wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() id, err := hash.FromString(txID) terminal.FatalErrorCheck(err) err = wlt.AddTransactionByID(id) terminal.FatalErrorCheck(err) terminal.PrintInfoMsgf("Transaction successfully added to the wallet.") } } // buildTransactionListCmd builds the command for listing wallet transactions. func buildTransactionListCmd(parentCmd *cobra.Command) { listCmd := &cobra.Command{ Use: "list [flags]", Short: "List transactions in the wallet", Long: `List transactions stored in the wallet. Examples: # List last 10 transactions (default) transaction list # List last 20 outgoing transactions transaction list --direction outgoing --count 20 # List transactions for a specific address transaction list --address pc1xyz...`, } parentCmd.AddCommand(listCmd) directionOpt := listCmd.Flags().String("direction", "any", "Filter transactions by direction: 'any', 'incoming', or 'outgoing'. Default is 'any'.") addressOpt := listCmd.Flags().String("address", "*", "Filter transactions by wallet address. Use '*' to include all addresses.") countOpt := listCmd.Flags().Int("count", 10, "Maximum number of transactions to display. Default is 10.") skipOpt := listCmd.Flags().Int("skip", 0, "Number of transactions to skip for pagination. Default is 0.") listCmd.Run = func(_ *cobra.Command, _ []string) { var direction types.TxDirection switch *directionOpt { case "any": direction = types.TxDirectionAny case "incoming": direction = types.TxDirectionIncoming case "outgoing": direction = types.TxDirectionOutgoing default: terminal.PrintErrorMsgf("invalid direction: %s", *directionOpt) return } opts := []wallet.ListTransactionsOption{ wallet.WithAddress(*addressOpt), wallet.WithDirection(direction), wallet.WithCount(*countOpt), wallet.WithSkip(*skipOpt), } wlt, err := openWallet(context.Background()) terminal.FatalErrorCheck(err) defer wlt.Close() transactions := wlt.ListTransactions(opts...) const ( noWidth = 4 timeWidth = 16 idWidth = 65 addressWidth = 16 amountWidth = 12 typeWidth = 10 statusWidth = 10 ) headerFmt := fmt.Sprintf("%%-%dv %%-%dv %%-%dv %%-%dv %%-%dv %%-%dv %%-%dv %%-%dv", noWidth, timeWidth, idWidth, addressWidth, addressWidth, amountWidth, typeWidth, statusWidth) rowFmt := headerFmt terminal.PrintInfoMsgBoldf(headerFmt, "No", "Time", "ID", "Sender", "Receiver", "Amount", "Type", "Status") fit := func(text string, width int) string { if len(text) > width { if width <= 3 { return text[:width] } return fmt.Sprintf("%-*s", width, text[:width-3]+"...") } return fmt.Sprintf("%-*s", width, text) } for i, trx := range transactions { terminal.PrintInfoMsgf(rowFmt, i+1, trx.CreatedAt.Format("2/1/2006 15:04"), fit(trx.TxID, idWidth), fit(cmd.ShortAddress(trx.Sender), addressWidth), fit(cmd.ShortAddress(trx.Receiver), addressWidth), fit(trx.Amount.String(), amountWidth), fit(trx.PayloadType.String(), typeWidth), fit(trx.Status.String(), statusWidth), ) } } } ================================================ FILE: committee/committee.go ================================================ package committee import ( "cmp" "errors" "fmt" "slices" "strings" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/linkedlist" ) var _ Committee = &committee{} type committee struct { committeeSize int validatorList *linkedlist.LinkedList[*validator.Validator] proposerPos *linkedlist.Element[*validator.Validator] } func NewCommittee(validators []*validator.Validator, committeeSize int, proposerAddress crypto.Address, ) (Committee, error) { validatorList := linkedlist.New[*validator.Validator]() var proposerPos *linkedlist.Element[*validator.Validator] for _, val := range validators { el := validatorList.InsertAtTail(val.Clone()) if val.Address() == proposerAddress { proposerPos = el } } if proposerPos == nil { return nil, errors.New("Proposer is not in the list") } return &committee{ committeeSize: committeeSize, validatorList: validatorList, proposerPos: proposerPos, }, nil } func (c *committee) TotalPower() int64 { power := int64(0) c.iterate(func(v *validator.Validator) bool { power += v.Power() return false }) return power } func (c *committee) Update(lastRound types.Round, joined []*validator.Validator) { slices.SortStableFunc(joined, func(a, b *validator.Validator) int { return cmp.Compare(a.Number(), b.Number()) }) // First update the validator list for _, val := range joined { committeeVal := c.find(val.Address()) if committeeVal == nil { c.validatorList.InsertBefore(val.Clone(), c.proposerPos) } else { committeeVal.UpdateLastSortitionHeight(val.LastSortitionHeight()) committeeVal.UpdateProtocolVersion(val.ProtocolVersion()) // Ensure that a validator's stake and bonding properties // remain unchanged while they are part of the committee. // Refer to the Bond executor for additional details. if committeeVal.Stake() != val.Stake() || committeeVal.LastBondingHeight() != val.LastBondingHeight() || committeeVal.UnbondingHeight() != val.UnbondingHeight() { panic("validators within the committee must be consistent") } } } // Now, adjust the list oldestFirst := make([]*linkedlist.Element[*validator.Validator], c.validatorList.Length()) i := 0 for e := c.validatorList.Head; e != nil; e = e.Next { oldestFirst[i] = e i++ } slices.SortStableFunc(oldestFirst, func(a, b *linkedlist.Element[*validator.Validator]) int { return cmp.Compare(a.Data.LastSortitionHeight(), b.Data.LastSortitionHeight()) }) for j := 0; j <= int(lastRound); j++ { c.proposerPos = c.proposerPos.Next if c.proposerPos == nil { c.proposerPos = c.validatorList.Head } } adjust := c.validatorList.Length() - c.committeeSize for j := 0; j < adjust; j++ { if oldestFirst[j] == c.proposerPos { c.proposerPos = c.proposerPos.Next if c.proposerPos == nil { c.proposerPos = c.validatorList.Head } } c.validatorList.Delete(oldestFirst[j]) } } // Validators retrieves a list of all validators in the committee. // A cloned instance of each validator is returned to avoid modification of the original objects. func (c *committee) Validators() []*validator.Validator { vals := make([]*validator.Validator, c.validatorList.Length()) i := 0 c.iterate(func(v *validator.Validator) bool { vals[i] = v.Clone() i++ return false }) return vals } func (c *committee) Contains(addr crypto.Address) bool { return c.find(addr) != nil } func (c *committee) find(addr crypto.Address) *validator.Validator { var found *validator.Validator c.iterate(func(v *validator.Validator) bool { if v.Address() == addr { found = v return true } return false }) return found } // IsProposer checks if the given address is the proposer for the specified round. func (c *committee) IsProposer(addr crypto.Address, round types.Round) bool { p := c.proposer(round) return p.Address() == addr } // Proposer returns an instance of the proposer validator for the specified round. // A cloned instance of the proposer is returned to avoid modification of the original object. func (c *committee) Proposer(round types.Round) *validator.Validator { return c.proposer(round).Clone() } func (c *committee) proposer(round types.Round) *validator.Validator { pos := c.proposerPos for i := 0; i < int(round); i++ { pos = pos.Next if pos == nil { pos = c.validatorList.Head } } return pos.Data } func (c *committee) Committers() []int32 { committers := make([]int32, c.validatorList.Length()) i := 0 c.iterate(func(v *validator.Validator) bool { committers[i] = v.Number() i++ return false }) return committers } func (c *committee) Size() int { return c.validatorList.Length() } func (c *committee) String() string { var builder strings.Builder builder.WriteString("[ ") for _, v := range c.Validators() { fmt.Fprintf(&builder, "%v(%v)", v.Number(), v.LastSortitionHeight()) if c.IsProposer(v.Address(), 0) { builder.WriteString("*") } builder.WriteString(" ") } builder.WriteString("]") str := builder.String() return str } // iterate uses for easy iteration over validators in list. func (c *committee) iterate(consumer func(*validator.Validator) (stop bool)) { for e := c.validatorList.Head; e != nil; e = e.Next { if consumer(e.Data) { return } } } // ProtocolVersions returns a map of protocol version to the percentage of validators // in the committee that have that version. func (c *committee) ProtocolVersions() map[protocol.Version]float64 { powers := make(map[protocol.Version]int64) total := int64(0) c.iterate(func(v *validator.Validator) bool { version := v.ProtocolVersion() powers[version] += v.Power() total += v.Power() return false }) percentages := make(map[protocol.Version]float64) for version, count := range powers { percentages[version] = (float64(count) / float64(total)) * 100 } return percentages } // SupportProtocolVersion checks if more than 70% of committee members // support the given protocol version. func (c *committee) SupportProtocolVersion(version protocol.Version) bool { versions := c.ProtocolVersions() supported := float64(0) for ver, percent := range versions { if ver >= version { supported += percent } } return supported > 70.0 } ================================================ FILE: committee/committee_test.go ================================================ package committee_test import ( "fmt" "testing" "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestContains(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, valKeys := ts.GenerateTestCommittee(21) nonExist := ts.RandAccAddress() assert.True(t, cmt.Contains(valKeys[0].Address())) assert.False(t, cmt.Contains(nonExist)) } func TestProposer(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, _ := ts.GenerateTestCommittee(4) assert.Equal(t, int32(0), cmt.Proposer(0).Number()) assert.Equal(t, int32(3), cmt.Proposer(3).Number()) assert.Equal(t, int32(0), cmt.Proposer(4).Number()) cmt.Update(0, nil) assert.Equal(t, int32(1), cmt.Proposer(0).Number()) } func TestInvalidProposerJoinAndLeave(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(0)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) val5 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(4)) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val5.Address()) require.Error(t, err) assert.Nil(t, cmt) } func TestProposerMove(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(4)) val5 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(5)) val6 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(6)) val7 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(7)) cmt, err := committee.NewCommittee( []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, 7, val1.Address()) require.NoError(t, err) // // +*+-+-+-+-+-+-+ +-+*+-+-+-+-+-+ +-+-+-+-+-+*+-+ +*+-+-+-+-+-+-+ // |1|2|3|4|5|6|7| => |1|2|3|4|5|6|7| => |1|2|3|4|5|6|7| => |1|2|3|4|5|6|7| // +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ // assert.Equal(t, int32(1), cmt.Proposer(0).Number()) assert.Equal(t, int32(1), cmt.Proposer(7).Number()) assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) // Height 1001 cmt.Update(0, nil) assert.Equal(t, int32(2), cmt.Proposer(0).Number()) assert.Equal(t, int32(3), cmt.Proposer(1).Number()) assert.Equal(t, int32(2), cmt.Proposer(7).Number()) assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) // Height 1002 cmt.Update(3, nil) assert.Equal(t, int32(6), cmt.Proposer(0).Number()) assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) // Height 1003 cmt.Update(1, nil) assert.Equal(t, int32(1), cmt.Proposer(0).Number()) assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) } func TestValidatorConsistency(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(4)) cmt, _ := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val1.Address()) t.Run("Updating validators' stake, Should panic", func(t *testing.T) { assert.Panics(t, func() { val1.AddToStake(1) cmt.Update(0, []*validator.Validator{val1}) }, "The code did not panic") }) } func TestProposerJoin(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(4)) val5 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(5)) val6 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(6)) val7 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(7)) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 7, val1.Address()) require.NoError(t, err) assert.Equal(t, 4, cmt.Size()) // // h=1000, r=0 h=1001, r=0 h=1002, r=1 h=1003, r=1 h=1004, r=0 // +-+*+-+-+ +-+$+-+*+-+ +*+-+-+!+-+ +$+$+-+!+*+-+-+ +-+-+-+-+-+*+-+ // |1|2|3|4| => |1|5|2|3|4| => |1|5|2|3|4| => |6|7|1|5|2|3|4| => |6|7|1|5|2|3|4| // +-+-+-+-+ +-+-+-+-+-+ +-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ // // Height 1000 // Val2 is in the committee val2.UpdateLastSortitionHeight(1000) cmt.Update(0, []*validator.Validator{val2}) assert.Equal(t, int32(2), cmt.Proposer(0).Number()) assert.Equal(t, []int32{1, 2, 3, 4}, cmt.Committers()) assert.Equal(t, 4, cmt.Size()) fmt.Println(cmt.String()) // Height 1001 val5.UpdateLastSortitionHeight(1001) cmt.Update(0, []*validator.Validator{val5}) assert.Equal(t, int32(3), cmt.Proposer(0).Number()) assert.Equal(t, int32(4), cmt.Proposer(1).Number()) assert.Equal(t, []int32{1, 5, 2, 3, 4}, cmt.Committers()) assert.Equal(t, 5, cmt.Size()) fmt.Println(cmt.String()) // Height 1002 cmt.Update(1, nil) assert.Equal(t, int32(1), cmt.Proposer(0).Number()) assert.Equal(t, int32(5), cmt.Proposer(1).Number()) fmt.Println(cmt.String()) // Height 1003 val3.UpdateLastSortitionHeight(1003) val6.UpdateLastSortitionHeight(1003) val7.UpdateLastSortitionHeight(1003) cmt.Update(1, []*validator.Validator{val7, val3, val6}) assert.Equal(t, int32(2), cmt.Proposer(0).Number()) assert.Equal(t, []int32{6, 7, 1, 5, 2, 3, 4}, cmt.Committers()) assert.Equal(t, 7, cmt.Size()) fmt.Println(cmt.String()) // Height 1004 cmt.Update(0, nil) assert.Equal(t, int32(3), cmt.Proposer(0).Number()) fmt.Println(cmt.String()) } func TestProposerJoinAndLeave(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() pub3, _ := ts.RandBLSKeyPair() pub4, _ := ts.RandBLSKeyPair() pub5, _ := ts.RandBLSKeyPair() pub6, _ := ts.RandBLSKeyPair() pub7, _ := ts.RandBLSKeyPair() pub8, _ := ts.RandBLSKeyPair() pub9, _ := ts.RandBLSKeyPair() pubA, _ := ts.RandBLSKeyPair() pubB, _ := ts.RandBLSKeyPair() pubC, _ := ts.RandBLSKeyPair() val1 := validator.NewValidator(pub1, 1) val2 := validator.NewValidator(pub2, 2) val3 := validator.NewValidator(pub3, 3) val4 := validator.NewValidator(pub4, 4) val5 := validator.NewValidator(pub5, 5) val6 := validator.NewValidator(pub6, 6) val7 := validator.NewValidator(pub7, 7) val8 := validator.NewValidator(pub8, 8) val9 := validator.NewValidator(pub9, 9) valA := validator.NewValidator(pubA, 10) valB := validator.NewValidator(pubB, 11) valC := validator.NewValidator(pubC, 12) cmt, err := committee.NewCommittee( []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, 7, val1.Address()) require.NoError(t, err) fmt.Println(cmt.String()) // This code comment explains how the committee changes when new validators join. // // The symbols used in the explanation are as follows: // * represents the current proposer // ! represents a failed proposer // $ represents a joined validator // h is height and r is round number // // Initially, the committee consists of validators numbered from 1 to 7. // Validator 1 is the oldest and the current proposer. // The committee configuration is represented as: // +*+-+-+-+-+-+-+ // |1|2|3|4|5|6|7| // +-+-+-+-+-+-+-+ // // When new validators join, they are inserted before the current proposer. // For example, validator 8 joins the committee: // +$+*+-+-+-+-+-+-+ // |8|1|2|3|4|5|6|7| // +-+-+-+-+-+-+-+-+ // // After the addition of a new validator, the committee needs to be adjusted, // and the oldest validator should leave: // +$+-+-+-+-+-+-+ // |8|2|3|4|5|6|7| // +-+-+-+-+-+-+-+ // // Next, we move to the next proposer. // +-+*+-+-+-+-+-+ // |8|2|3|4|5|6|7| // +-+-+-+-+-+-+-+ // // ------------------------------------- // In this test, we cover the following movements: // // h=1000, r=0 h=1001, r=0 h=1002, r=3 h=1003, r=0 // +*+-+-+-+-+-+-+ +$+*+-+-+-+-+-+ +-+-+!+!+!+*+-+ +-+$+-+-+$+-+*+ // |1|2|3|4|5|6|7| => |8|2|3|4|5|6|7| => |8|2|3|4|5|6|7| => |8|2|3|5|9|6|7| => // +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+$+-+-+-+-+ +-+-+-+-+-+-+-+ // // h=1004, r=1 h=1005, r=0 h=1006, r=2 h=1007, r=4 // +!+*+-+-+-+$+-+ +-+$+$+-+*+-+-+ +*+-+-+$+-+!+!+ +*+$+-+!+!+!+!+ // |8|2|3|9|6|A|7| => |8|B|C|2|3|9|A| => |B|C|2|1|3|9|A| => |5|6|B|C|2|1|3| // +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +$+-+-+-+$+-+$+ // Height 1001 val8.UpdateLastSortitionHeight(1001) cmt.Update(0, []*validator.Validator{val8}) assert.Equal(t, int32(2), cmt.Proposer(0).Number()) assert.Equal(t, int32(3), cmt.Proposer(1).Number()) assert.Equal(t, int32(4), cmt.Proposer(2).Number()) assert.Equal(t, []int32{8, 2, 3, 4, 5, 6, 7}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1002 val3.UpdateLastSortitionHeight(1002) cmt.Update(3, []*validator.Validator{val3}) assert.Equal(t, int32(6), cmt.Proposer(0).Number()) fmt.Println(cmt.String()) // Height 1003 val2.UpdateLastSortitionHeight(1003) val9.UpdateLastSortitionHeight(1003) cmt.Update(0, []*validator.Validator{val9, val2}) assert.Equal(t, int32(7), cmt.Proposer(0).Number()) assert.Equal(t, int32(8), cmt.Proposer(1).Number()) assert.Equal(t, []int32{8, 2, 3, 5, 9, 6, 7}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1004 valA.UpdateLastSortitionHeight(1004) cmt.Update(1, []*validator.Validator{valA}) assert.Equal(t, int32(2), cmt.Proposer(0).Number()) assert.Equal(t, []int32{8, 2, 3, 9, 6, 10, 7}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1005 valB.UpdateLastSortitionHeight(1005) valC.UpdateLastSortitionHeight(1005) cmt.Update(0, []*validator.Validator{valC, valB}) assert.Equal(t, int32(3), cmt.Proposer(0).Number()) assert.Equal(t, int32(9), cmt.Proposer(1).Number()) assert.Equal(t, int32(10), cmt.Proposer(2).Number()) assert.Equal(t, []int32{8, 11, 12, 2, 3, 9, 10}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1006 val1.UpdateLastSortitionHeight(1006) cmt.Update(2, []*validator.Validator{val1}) assert.Equal(t, int32(11), cmt.Proposer(0).Number()) assert.Equal(t, []int32{11, 12, 2, 1, 3, 9, 10}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1007 val2.UpdateLastSortitionHeight(1007) val3.UpdateLastSortitionHeight(1007) val5.UpdateLastSortitionHeight(1007) val6.UpdateLastSortitionHeight(1007) cmt.Update(4, []*validator.Validator{val2, val3, val5, val6}) assert.Equal(t, int32(5), cmt.Proposer(0).Number()) assert.Equal(t, []int32{5, 6, 11, 12, 2, 1, 3}, cmt.Committers()) fmt.Println(cmt.String()) } func TestIsProposer(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(0)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val1.Address()) require.NoError(t, err) assert.Equal(t, int32(0), cmt.Proposer(0).Number()) assert.Equal(t, int32(1), cmt.Proposer(1).Number()) assert.True(t, cmt.IsProposer(val3.Address(), 2)) assert.False(t, cmt.IsProposer(val4.Address(), 2)) assert.False(t, cmt.IsProposer(ts.RandAccAddress(), 2)) assert.Equal(t, []*validator.Validator{val1, val2, val3, val4}, cmt.Validators()) } func TestCommitters(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(0)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val1.Address()) require.NoError(t, err) assert.Equal(t, []int32{0, 1, 2, 3}, cmt.Committers()) } func TestSortJoined(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(0)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) val5 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(4)) val6 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(5)) val7 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(6)) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 17, val1.Address()) require.NoError(t, err) committee2, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 17, val1.Address()) require.NoError(t, err) cmt.Update(0, []*validator.Validator{val5, val6, val7}) committee2.Update(0, []*validator.Validator{val7, val5, val6}) } func TestTotalPower(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandBLSKeyPair() val0 := validator.NewValidator(pub, 0) // Bootstrap validator val1 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(0)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(1)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(2)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithNumber(3)) cmt, err := committee.NewCommittee([]*validator.Validator{val0, val1, val2, val3, val4}, 4, val1.Address()) require.NoError(t, err) totalPower := val0.Power() + val1.Power() + val2.Power() + val3.Power() + val4.Power() totalStake := val0.Stake() + val1.Stake() + val2.Stake() + val3.Stake() + val4.Stake() assert.Equal(t, totalPower, cmt.TotalPower()) assert.Equal(t, int64(totalStake+1), cmt.TotalPower()) } func TestProtocolVersionPercentages(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(1000)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(1000)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(500)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(500)) val5 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(1000)) val2.UpdateProtocolVersion(protocol.ProtocolVersion1) val3.UpdateProtocolVersion(protocol.ProtocolVersion2) val4.UpdateProtocolVersion(protocol.ProtocolVersion2) val5.UpdateProtocolVersion(protocol.ProtocolVersion2) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4, val5}, 5, val1.Address()) require.NoError(t, err) percentages := cmt.ProtocolVersions() assert.InDelta(t, float64(25), percentages[protocol.ProtocolVersionUnknown], 0.01) assert.InDelta(t, float64(25), percentages[protocol.ProtocolVersion1], 0.01) assert.InDelta(t, float64(50), percentages[protocol.ProtocolVersion2], 0.01) } func TestSupportProtocolVersion(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(1000)) val2 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(1000)) val3 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(500)) val4 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(500)) val5 := ts.GenerateTestValidator(testsuite.ValidatorWithStake(1000)) val2.UpdateProtocolVersion(protocol.ProtocolVersion1) val3.UpdateProtocolVersion(protocol.ProtocolVersion2) val4.UpdateProtocolVersion(protocol.ProtocolVersion2) val5.UpdateProtocolVersion(protocol.ProtocolVersion2) cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4, val5}, 5, val1.Address()) require.NoError(t, err) supportVer1 := cmt.SupportProtocolVersion(protocol.ProtocolVersion1) supportVer2 := cmt.SupportProtocolVersion(protocol.ProtocolVersion2) assert.True(t, supportVer1) assert.False(t, supportVer2) } ================================================ FILE: committee/interface.go ================================================ package committee import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" ) type Reader interface { Validators() []*validator.Validator Committers() []int32 Contains(addr crypto.Address) bool Proposer(round types.Round) *validator.Validator IsProposer(addr crypto.Address, round types.Round) bool ProtocolVersions() map[protocol.Version]float64 SupportProtocolVersion(version protocol.Version) bool Size() int TotalPower() int64 String() string } type Committee interface { Reader Update(lastRound types.Round, joined []*validator.Validator) } ================================================ FILE: config/banned_addrs.json ================================================ [ "pc1p8slveave2zm9tgj7q260fgrdfu2ph8n7ezxhtt", "pc1prqnrscsgtcp25sqvwk6d2zj9p9m37wexu0x8z5", "pc1pd5mytehyrrgtcvhzjqnl7tkq2q0693w5raqjuz", "pc1pg69yuccgflmh8fm4pffgwtrxtvvmz96vzjuvev", "pc1p23yw39cz2k3epaudrpc3fy47xwmlt3y7padg6k", "pc1pu5y7tprtgve6wf27chhcx2clrp3rxr78yjn2w6", "pc1p2qvmcx49d0l30vclh5cra7zaudc5ptl05e6pme", "pc1pqp67ea35yu4pvchgps4rv0qh0xq2pjty6h00hv", "pc1pggmhgvykakkm65wma06r9ehmeg57qq6rdze9ac", "pc1pdtmavngjg6uxexmyre5ulzxdm0273qtsmegw5p", "pc1pyl42x03hvdee29jz5t40ak25ykmsv7lz2zde5t", "pc1p4updh8l9vzzuz0sl82vyk68st59mzqwwcy968c", "pc1ppcula9c5xspaumhr9uf7fz3k6r3g96v0kw70w2", "pc1pjcfn6n3ah38rxymyyay4wyeexhv80t6ll7exf4", "pc1pvdkeuwyg8t6aadzq6qey7hr6rx7pegaf645x0h", "pc1pr23lgtpqk4jejyjymtvhcewdhhcsn3pcg6pnpe", "pc1p6hyq0q9ska6d69e0mh4wtjehg59nd6m0jd5sgg", "pc1p3p2975j823dtg9ykrex5ldtvzan37n05ujs5yp", "pc1pu7lu603kklmaztpedjfped0l76vv9t2g0kfekr", "pc1p60wcs73wsayw392xavevfpcw74n27skyxzt22k", "pc1ppx792krldzc5te6w9dsud0tg68kea4qjtgl9zz", "pc1ppepknw0sw7l28mqk2s9x3lhrc4m6q2kxn7zq65", "pc1p42m2tuh4de5uk0x6t4c9vlp03k90300aclzytd", "pc1prsvye97z3ghe3z8nkvlsexl8jq4cuuryvj5wse", "pc1p4zv86e9r648muzxgacftxt0mpqv3hk7yj7ckg2", "pc1pdsg4a9llhwwjd895a6p9832ql7ujwp6w5eafkp", "pc1ppwd8cartlsf59pet6fv7epw54wxfkw8sh03vn9", "pc1p06x3tdrputewwrl3jjln0t3rmwew4lq83hvvmr", "pc1pgemv3f5jfpwqseaq0zrcre2kctxdrtygr4v38g", "pc1pcjt9v92rjz67whedeapcg4j7vmg5fkmpu8w5pk", "pc1pq7c9r9g6hq2xuhyuxgw7p9aw28ct5l5xjs4rcr", "pc1pjnjga6kp995d7ryjhfmpfhypzhc5t842ej4wkn", "pc1psmxxv869ktd854u9xugdzc95ctd8gxm0j606yu", "pc1pxw82yfrtqvawx0fy2q2jv7fn5ldcv3f9x0cpxq", "pc1pwyhe94d0h0nmevz9hj2p3e4gxx6akgcatljpzk", "pc1p6pxk2qvkvv9czn4m9y6vt28umxjrg2ysjrc739", "pc1pjxef7h7phx2rtjl7xyrqtuch2v7x54jqd5xz08", "pc1p9zm2uxeuf0r674ymm94m7tn9trdpvv7xwytr63", "pc1p6zrr0almnw4rcd4e8a35yjsvr3nzn34jx5anmf", "pc1phx0ztmscj8n99tf2jje4r8zn6szlh2aw3segkl", "pc1z2wtq43p8fnueya9qufq9hkutyr899npk2suleu", "pc1rjssvgmfd702dt66x9rjakumh2ry3x85s22spz8" ] ================================================ FILE: config/bootstrap.json ================================================ [ { "name": "Pactus", "email": "info@pactus.org", "website": "https://pactus.org", "address": "/dns/bootstrap1.pactus.org/tcp/21888/p2p/12D3KooWMnDsu8TDTk2VV8uD8zsNSB6eUkqtQs6ttg4bHq9zNaBe" }, { "name": "Pactus", "email": "info@pactus.org", "website": "https://pactus.org", "address": "/dns/bootstrap2.pactus.org/tcp/21888/p2p/12D3KooWM39ag7ghta49qybf7McADgT8FLakTYkCsiBvwdnjuG5q" }, { "name": "Pactus", "email": "info@pactus.org", "website": "https://pactus.org", "address": "/dns/bootstrap3.pactus.org/tcp/21888/p2p/12D3KooWBCPSZWheet6tMoHbVBCDfBwQm4yzCwcQ8hJ6NMCN97sj" }, { "name": "Pactus", "email": "info@pactus.org", "website": "https://pactus.org", "address": "/dns/bootstrap4.pactus.org/tcp/21888/p2p/12D3KooWKg6aLa77yAaqMCb45aH5iQuTr5GzRUWUCJ1sZYB5vnoL" }, { "name": "MrHodl", "email": "hodl@pactus.org", "website": "n/a", "address": "/ip4/65.108.211.187/tcp/21888/p2p/12D3KooWGLrSiE5KWoc9GpXfryvKqheHj6j78ryMDDC17SY4YoCi" }, { "name": "Fabryprog", "email": "fabryprog@gmail.com", "website": "n/a", "address": "/ip4/84.247.165.249/tcp/21888/p2p/12D3KooWQmv2FcNQfh1EhA98twt8ePdkQaxEPeYfinEYyVS16juY" }, { "name": "JohnVNBnode", "email": "quynhgiangtranle@gmail.com", "website": "docs.vnbnode.com", "address": "/ip4/62.171.130.196/tcp/21888/p2p/12D3KooWSkwB8AiWz3VGyG5cgC3ry5dmCw3TthQNc1jvRNe9EEKH" }, { "name": "NodeSync_Top", "email": "lthuan2011@gmail.com", "website": "https://nodesync.top/", "address": "/ip4/135.181.42.222/tcp/21888/p2p/12D3KooWN46UYQNoZvzd9GiJPQC7LByj6RAg8rRxdUTiQ24vHsN1" }, { "name": "Stakers", "email": "danile_z@outlook.com", "website": "", "address": "/dns/pactus-bootstrap.stakers.world/tcp/21888/p2p/12D3KooWK1DAcxf8RJA2PVkwr9ehk1zgXcnjLyPCsYCpvw1NSfhc" }, { "name": "Karma Nodes", "email": "karma.nodes@proton.me", "website": "http://karmanodes.xyz", "address": "/ip4/158.220.91.129/tcp/21888/p2p/12D3KooWGfehwyZJBu6WUMLyzJ8sDJachvhxhqw5Wh4uU3H99GLq" }, { "name": "IONode", "email": "orochi@ionode.online", "website": "https://IONode.Online", "address": "/dns/pactus-bootstrap.ionode.online/tcp/21888/p2p/12D3KooWG5tvvfS8PRd2Bgyxxqrok7QfohkHSprFPxmT3HTh8dVD" }, { "name": "SGTstake", "email": "adorid@sgtstake.com", "website": "https://sgtstake.com", "address": "/ip4/159.148.146.149/tcp/21888/p2p/12D3KooWKCokWtpdudxgsLRoFcnrW35vhn6w632iGWCga7E5e68Q" }, { "name": "Stake.Works", "email": "support@stake.works", "website": "https://stake.works", "address": "/dns/pactus-bootnode.stake.works/tcp/21888/p2p/12D3KooWJPuhW7Ejmb8KprpVNRzn1eUQXDHU3n5eTo2vodgvVxoJ" }, { "name": "KenZ", "email": "quangtuyen88@hotmail.com", "website": "https://www.pr1sm.com/", "address": "/ip4/65.108.68.214/tcp/21888/p2p/12D3KooWD7X8BDqV9r6zGmoo2dpMYo4Z6YoyDQp6j4UnB2Bj3Fq2" }, { "name": "Validator247", "email": "Validator247@gmail.com", "website": "https://validator247.com/", "address": "/ip4/65.21.180.80/tcp/21888/p2p/12D3KooWANqay6T1xCrK3imfAEr3GpiGzxT6SWCEsRapo8tJWAZN" }, { "name": "BearValidator", "email": "validator.wiki@gmail.com", "website": "https://validator.wiki/", "address": "/ip4/37.27.26.40/tcp/21888/p2p/12D3KooWPehhWgfdZG6x9zE7QdQxuAcfbQPAyBPjcXLfVYfU9FAd" }, { "name": "MoneyLow-VNBnode", "email": "mfl@vnbnode.com", "website": "https://VNBnode.com", "address": "/dns/pactus-bootstrap.mflow.tech/tcp/21888/p2p/12D3KooWJD2PBAur6kXjX31dyrPzjSV947ppZ885QDKCXEvLm9Vb" }, { "name": "alishiaplowden", "email": "pleasurement7777@gmail.com", "website": "n/a", "address": "/ip4/5.161.222.154/tcp/21888/p2p/12D3KooWQN2VN1RWQ5eWq8rVexpBnwVSy7k34Rpep4R6V57XWYau" }, { "name": "CherryValidator", "email": "mommeus@gmail.com", "website": "https://cherryvalidator.us", "address": "/ip4/65.21.155.128/tcp/21888/p2p/12D3KooWPykSnzWpEasRijCgQ99vxAxWKL32zY24MmvtaXsHapSf" }, { "name": "TeoViTeoVi", "email": "listening2009@gmail.com", "website": "https://teoviteovi.com", "address": "/dns/pactus-bootstrap.teoviteovi.com/tcp/21888/p2p/12D3KooWMP5qWNHF1RfzhpAkBmQZzBfbaSJZCo3QF1fxs5CFXkv8" }, { "name": "p10node", "email": "pierre@p10node.com", "website": "https://p10node.com/", "address": "/ip4/37.60.233.235/tcp/21888/p2p/12D3KooWNzbuBESYzbKGm7UyLkD22cHSgjRMUx4rjEKLBfVSZuY1" }, { "name": "tiantsi", "email": "xuhaizhu@gmail.com", "website": "n/a", "address": "/ip4/43.135.166.197/tcp/21888/p2p/12D3KooWEqyjMNzFe92HFZMZQd3YZ6zvztuPaC3a4wAUvPf4moyP" }, { "name": "vinhhathacha", "email": "vinhhathacha@gmail.com", "website": "https://github.com/vinhhathacha", "address": "/ip4/46.250.233.5/tcp/21888/p2p/12D3KooWH1kam9g1QFWmtWMLzP2MDY4ptpLTMPU8wSq3Q4k3rvnn" }, { "name": "CodeBlockLabs", "email": "emailbuatcariduit@gmail.com", "website": "https://codeblocklabs.com", "address": "/dns/pactus-bootstrap.codeblocklabs.com/tcp/21888/p2p/12D3KooWSdmPLqWbmv5x5pBiL5nHwKN5S2jhP96oXCKmoEmAhV4Z" }, { "name": "0xSown", "email": "vtson2707@gmail.com", "website": "n/a", "address": "/ip4/84.247.184.95/tcp/21888/p2p/12D3KooWSjp5GFmCCsYkKcqicrghyHqfjdDCfLfgfqWmG5JTQSDu" }, { "name": "Adora", "email": "adoratran21@gmail.com", "website": "", "address": "/dns/pactus-bootstrap.thd.io.vn/tcp/21888/p2p/12D3KooWDgsSSGJzihBJxqNJFqbGwbTEDXRoUBph1BCfwm11R6KY" }, { "name": "Node39", "email": "contact@node39.top", "website": "https://node39.top", "address": "/dns/bootstrap-pactus.node39.top/tcp/21888/p2p/12D3KooWDhWitNS2nNYMUHnTvdGXeQXd5aYBAGppaBTE1VMiyH4B" }, { "name": "sebus", "email": "john.chatterton@protonmail.com", "website": "https://linktr.ee/john.chatterton", "address": "/ip4/173.212.254.120/tcp/21888/p2p/12D3KooWJR19vjuBzuJTceCoy3LG8jggkHCBGb9j5SzdKtoPL7Yb" }, { "name": "Stilucky", "email": "Stiluckyy@gmail.com", "website": "n/a", "address": "/ip4/62.171.134.3/tcp/21888/p2p/12D3KooWSv5jsXMg1b4PBd2SCcPLj3Mc5KzzBYnpPkiS7JjuqhHF" }, { "name": "Toncatuyvu", "email": "Toncatuyvu@gmail.com", "website": "n/a", "address": "/ip4/109.123.240.5/tcp/21888/p2p/12D3KooWCT92yaS4JgrHHzeRPsJxaLzRdSEknGEN4HxQFfscoY8k" }, { "name": "TPES", "email": "duongbo8648@gmail.com", "website": "https://tpes.com.vn", "address": "/ip4/75.119.159.113/tcp/21888/p2p/12D3KooWL7nUsmd7JNrhrfbBjg6JxPFiZA5LXbdCDPnw5Xpdp4a9" }, { "name": "toanbm", "email": "buiminhtoan1985@gmail.com", "website": "", "address": "/ip4/161.97.145.100/tcp/21888/p2p/12D3KooWCjZ35Hu8Mt5GjZ6fJzJBZuUSsAppAzXcbMcXkswR4HrU" }, { "name": "Wanderersg2014", "email": "wanderersg2014@gmail.com", "website": "n/a", "address": "/ip4/109.123.253.88/tcp/21888/p2p/12D3KooWFUJhDjYcAXgEnW1pTLRDWnH9CLgBPcezgU7pCpxMngt8" }, { "name": "node-life", "email": "vminairdrop1@gmail.com", "website": "", "address": "/ip4/167.86.80.169/tcp/21888/p2p/12D3KooWDqAPjeRR41GYoQw9RQaSZdFx59k3SpkR29yAycpJUhfF" }, { "name": "DRAGON", "email": "kiritovn14788@gmail.com", "website": "", "address": "/ip4/65.21.69.53/tcp/21888/p2p/12D3KooWQ1izUE5jcmMyjmxRdb2CmASe8Nfn81UL2G5rYjptC2RV" }, { "name": "VALIDATOR.WIKI", "email": "admin@validator.wiki", "website": "https://www.validator.wiki/", "address": "/dns/pactus-bootstrap.validator.wiki/tcp/21888/p2p/12D3KooWBC5YQJdRAvupSXUPNYHiSctzZeTPNzen1JsRwj9aEyYZ" }, { "name": "SumNode", "email": "thanhsum@gmail.com", "website": "", "address": "/ip4/157.90.22.45/tcp/21888/p2p/12D3KooWLUYJ55DyJjSZvwPJDQNVYSBYqiMxJ9bFzRcVBgvSkN9L" }, { "name": "bettevinup", "email": "neitheryounorme1@gmail.com", "website": "n/a", "address": "/ip4/65.21.152.153/tcp/21888/p2p/12D3KooWCirKBMmhmL6a4Ng5TVHQ4Leb6Wfj4M8s9raUzdFQn5aP" }, { "name": "BlockSync", "email": "topwelder2015@gmail.com", "website": "", "address": "/ip4/128.140.103.90/tcp/21888/p2p/12D3KooWN4eypkp61j12SMSkmrEfQv4RjnggmRfcEfom4mcKUpsR" }, { "name": "hainguyen0094_22439", "email": "nth1686@hotmail.com", "website": "", "address": "/ip4/185.216.75.142/tcp/21888/p2p/12D3KooWNjYFZpq5YwdUC6JgHfkZhUY7SyxTAQCHrdNwf2t1FXSn" }, { "name": "duyenhtm", "email": "myduyenht1501@gmail.com", "website": "", "address": "/ip4/85.190.246.251/tcp/21888/p2p/12D3KooWMTPKpr6EHMmZ2NSXkup4NaqwKnYmScHEsN3HpcqYgBZL" }, { "name": "minhtoanbui135", "email": "toanbm.test02@gmail.com", "website": "n/a", "address": "/ip4/45.134.226.48/tcp/21888/p2p/12D3KooWBSP8AdiHkkvPunpbhfZE96YTY6om4hw35Xpe3bJFBUjh" }, { "name": "NodeOps", "email": "admin@nodeops.dev", "website": "https://nodeops.dev/", "address": "/ip4/154.38.187.40/tcp/21888/p2p/12D3KooWQyt7JCyhhnZ8jyT1vso4GGYVbpJhoXJy5KRpnqa8DmPg" }, { "name": "hope3387", "email": "phuocchunginvestor@gmail.com", "website": "n/a", "address": "/ip4/194.163.164.10/tcp/21888/p2p/12D3KooWDRFCW5ksbnn6Uq7kx3HZt3EnrKjujqqs8QBQmA7TK5o6" }, { "name": "5t0q6pr", "email": "nth1686@gmail.com", "website": "n/a", "address": "/ip4/167.86.116.61/tcp/21888/p2p/12D3KooWAmc69XaFh6T76BQQaFmSakYFgDyvzDLfVBgTzqmNtyXM" }, { "name": "00PactucValidator32", "email": "evpc77@gmail.com", "website": "n/a", "address": "/ip4/46.196.214.35/tcp/21888/p2p/12D3KooWJ3H7YAyemqxtToG6yRRzTfLdZD3eJk2xsQRaKxfdNhKf" }, { "name": "anpjwq", "email": "hain64341@gmail.com", "website": "n/a", "address": "/ip4/42.117.247.180/tcp/21888/p2p/12D3KooWLVZSkgkFgrRNMfkCtULqtErYcNgjqgueeH944vDpDCPv" }, { "name": "Vozer", "email": "airdropdata7@gmail.com", "website": "voz.vn", "address": "/ip4/38.242.225.172/tcp/21888/p2p/12D3KooWDTP7CKGvbcg5WiuKB2Bt4acf2LWMdbUjMqU63dKKCVMB" }, { "name": "Khacbao", "email": "khacbao114@gmail.com", "website": "n/a", "address": "/ip4/167.86.121.11/tcp/21888/p2p/12D3KooWMpVXMQkr26ff3y8gC5z1h9RZNxTvW4WzZBML8GHHUoL5" }, { "name": "Thomas Jr", "email": "catsmile91@gmail.com", "website": "catsmile.tech", "address": "/ip4/194.163.189.255/tcp/21888/p2p/12D3KooWExbN79BrgDWjdLUd8TZaP2LvCDN8zJkMuPhRHkjKDcJS" }, { "name": "Winnode", "email": "maladarsih@gmail.com", "website": "winnode.site", "address": "/ip4/37.60.245.47/tcp/21888/p2p/12D3KooWBH27VEPdGBYzq1vYciRgnDn3ozStRaUYd2vJWGgaKEUZ" }, { "name": "F2Node", "email": "lochua3989@gmail.com", "website": "n/a", "address": "/ip4/84.247.172.23/tcp/21888/p2p/12D3KooWFJYk55mUD6FR9Gx2YGQ34PYziwTQhY1kZ3TMS6fGUz6g" }, { "name": "SumNode", "email": "thanhsum@gmail.com", "website": "", "address": "/ip4/95.216.222.135/tcp/21888/p2p/12D3KooWHicbZ3dBnR7JaVKr4U7WNUWyhDnUn2TwMVmPqW8Ftqop" }, { "name": "Sipannachi", "email": "sipannachi@gmail.com", "website": "", "address": "/ip4/65.109.143.78/tcp/21888/p2p/12D3KooWPnWgEFV32cvpfuv98oioZQJJKvRM46BEsFaoXYijvgvc" }, { "name": "JackieLuong135", "email": "jackieluong135@gmail.com", "website": "", "address": "/ip4/116.203.238.65/tcp/21888/p2p/12D3KooWANYW76iXWpFXPQ85mDamWbfRdkyo8KcvxxQMJdfQW33G" }, { "name": "Lisachoake", "email": "mohamed.solamina@gmail.com", "website": "", "address": "/ip4/49.13.27.37/tcp/21888/p2p/12D3KooWPSh9KMa6tRfSewK3sUC4BDSPnXseVDGJxWqNZxKcXnGM" }, { "name": "Sury", "email": "lyminhhai102@gmail.com", "website": "", "address": "/ip4/37.60.241.89/tcp/21888/p2p/12D3KooWMZtkk5HS69ukYYdfxD3CgBgTtKZg7kv43mCz1HMrDnQw" }, { "name": "Razizi", "email": "sumtran.dev@gmail.com", "website": "", "address": "/ip4/195.201.112.164/tcp/21888/p2p/12D3KooWKiYGT4mCapgcqLPSwbkJY1KgZMW5hdC8XJMQSU23tiSL" }, { "name": "hainguyen0094_22439", "email": "nth1686@hotmail.com", "website": "", "address": "/ip4/94.72.120.50/tcp/21888/p2p/12D3KooWCJX9aLnzmEFtEasvbbaFqHLTboFVFptZxeFnbnSxpb2m" }, { "name": "anpjwq", "email": "hain64341@gmail.com", "website": "n/a", "address": "/ip4/95.111.242.225/tcp/21888/p2p/12D3KooWRNTZpo1XNWKQx2Z5HEu5RnqKeNDV5y4qMKX5f4aLtbv9" }, { "name": "Dezh Technologies", "email": "hi@dezh.tech", "website": "https://dezh.tech", "address": "/dns/pactus-bootstrap1.dezh.tech/tcp/21888/p2p/12D3KooWK1z7QAskVrQd98r98UMSPwTLr4out8B9NkQTrCdZPCZx" }, { "name": "korcano", "email": "korcan@yaani.com", "website": "", "address": "/ip4/5.75.183.248/tcp/21888/p2p/12D3KooWNMfSbFx4RvakvBXrZrsqi9gdqzg6P9PWgpB3wT6uwV8t" } ] ================================================ FILE: config/config.go ================================================ package config import ( "bytes" _ "embed" "encoding/json" "fmt" "os" "github.com/pactus-project/pactus/consensus" "github.com/pactus-project/pactus/consensusv2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/sync" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" wltmgr "github.com/pactus-project/pactus/wallet/manager" "github.com/pactus-project/pactus/www/grpc" "github.com/pactus-project/pactus/www/html" "github.com/pactus-project/pactus/www/http" "github.com/pactus-project/pactus/www/jsonrpc" "github.com/pactus-project/pactus/www/zmq" "github.com/pelletier/go-toml/v2" ) var ( //go:embed example_config.toml exampleConfigBytes []byte //go:embed bootstrap.json bootstrapInfoBytes []byte //go:embed banned_addrs.json bannedAddrBytes []byte ) // Config defines parameters for the root application configuration. type Config struct { Node *NodeConfig `toml:"node"` Store *store.Config `toml:"store"` Network *network.Config `toml:"network"` Sync *sync.Config `toml:"sync"` TxPool *txpool.Config `toml:"tx_pool"` Logger *logger.Config `toml:"logger"` GRPC *grpc.Config `toml:"grpc"` JSONRPC *jsonrpc.Config `toml:"jsonrpc"` HTTP *http.Config `toml:"http"` HTML *html.Config `toml:"html"` ZeroMq *zmq.Config `toml:"zeromq"` WalletManager *wltmgr.Config `toml:"wallet"` Consensus *consensus.Config `toml:"-"` // Deprecated: replaced by new consensus algorithm ConsensusV2 *consensusv2.Config `toml:"-"` } type BootstrapInfo struct { Name string `json:"name"` Email string `json:"email"` Website string `json:"website"` Address string `json:"address"` } type NodeConfig struct { RewardAddresses []string `toml:"reward_addresses"` } func DefaultNodeConfig() *NodeConfig { return &NodeConfig{ RewardAddresses: []string{}, } } // BasicCheck performs basic checks on the configuration. func (conf *NodeConfig) BasicCheck() error { for _, addrStr := range conf.RewardAddresses { addr, err := crypto.AddressFromString(addrStr) if err != nil { return NodeConfigError{ Reason: fmt.Sprintf("invalid reward address: %v", err.Error()), } } if !addr.IsAccountAddress() { return NodeConfigError{ Reason: fmt.Sprintf("reward address is not an account address: %s", addrStr), } } } return nil } func defaultConfig() *Config { conf := &Config{ Node: DefaultNodeConfig(), Store: store.DefaultConfig(), Network: network.DefaultConfig(), Sync: sync.DefaultConfig(), TxPool: txpool.DefaultConfig(), Consensus: consensus.DefaultConfig(), ConsensusV2: consensusv2.DefaultConfig(), Logger: logger.DefaultConfig(), GRPC: grpc.DefaultConfig(), HTML: html.DefaultConfig(), HTTP: http.DefaultConfig(), JSONRPC: jsonrpc.DefaultConfig(), ZeroMq: zmq.DefaultConfig(), WalletManager: wltmgr.DefaultConfig(), } return conf } func DefaultConfigMainnet() *Config { conf := defaultConfig() bootstrapNodes := make([]BootstrapInfo, 0) if err := json.Unmarshal(bootstrapInfoBytes, &bootstrapNodes); err != nil { panic(err) } bootstrapAddrs := make([]string, 0, len(bootstrapNodes)) for _, node := range bootstrapNodes { bootstrapAddrs = append(bootstrapAddrs, node.Address) } // The first item in the banned list is for testing. // The address is: "pc1p8slveave2zm9tgj7q260fgrdfu2ph8n7ezxhtt" // The associated private key: "SECRET1PP8SYQAH8JH8QLGEEX7L7T8WTU69K6T9AVSNMVCZ8DP6PPLWVYE3SVTHFR8" bannedList := make([]string, 0) if err := json.Unmarshal(bannedAddrBytes, &bannedList); err != nil { panic(err) } bannedAddrs := make(map[crypto.Address]bool) for _, str := range bannedList { addr, err := crypto.AddressFromString(str) if err != nil { panic(err) } bannedAddrs[addr] = true } conf.Store.BannedAddrs = bannedAddrs conf.Network.MaxConns = 64 conf.Network.EnableNATService = false conf.Network.EnableUPnP = false conf.Network.EnableRelay = true conf.Network.NetworkName = "pactus" conf.Network.DefaultPort = 21888 conf.Network.DefaultBootstrapAddrStrings = bootstrapAddrs conf.GRPC.Enable = true conf.GRPC.Listen = "127.0.0.1:50051" conf.GRPC.BasicAuth = "" conf.HTML.Enable = false conf.HTML.Listen = "127.0.0.1:80" conf.HTTP.Enable = false conf.HTTP.Listen = "127.0.0.1:8080" conf.HTTP.BasePath = "/http" conf.JSONRPC.Enable = false conf.JSONRPC.Listen = "127.0.0.1:8545" conf.JSONRPC.Origins = []string{} conf.HTML.EnablePprof = false return conf } func DefaultConfigTestnet() *Config { conf := defaultConfig() conf.Network.DefaultBootstrapAddrStrings = []string{ "/dns/testnet1.pactus.org/tcp/21777/p2p/12D3KooWR7ZB3nGih1Fz7Yg83Zap8Cpxr73T6PPihBsEpTG5BZyk", "/dns/testnet2.pactus.org/tcp/21777/p2p/12D3KooWQcDuFDMGsw6gG7oNFw7C4x7ozoMu69J7WEAojKCaNzji", "/dns/testnet3.pactus.org/tcp/21777/p2p/12D3KooWLsAPSJ4xowd9thGbPmbweBT6sg3nEiPjDJccaWZacsUR", "/dns/testnet4.pactus.org/tcp/21777/p2p/12D3KooWJKYdHzWZGibnj74NSSgKRu4Ez6MijDWMfLfXxeL4un6v", "/ip4/65.108.211.187/tcp/21777/p2p/12D3KooWB42BLfzxSF5SMhSTSEyfJ6yhSM8togLfExrRWFMJeb5u", "/ip4/103.27.206.208/tcp/21777/p2p/12D3KooWMTDwDTBMaf2Sem5tWRe1dB6PFY8LeqkZ2e5drrbbPTDn", // andrut.pactus.testnet "/ip4/65.108.142.81/tcp/21777/p2p/12D3KooWAdRga2NCbaPfVgSEzAAZW2psfJmPi3PFJzF81qbccJsR", // CherryValidator "/ip4/95.217.89.202/tcp/21777/p2p/12D3KooWH3S9gMYybr1pd4K5o3CBLbZLQ1REKBsPWt6NWPi4bgPn", // CodeBlockLab "/ip4/188.213.198.83/tcp/21777/p2p/12D3KooWJ5kSyD3VQb1ewhgRcmAPPg2zus1rYPbgnBMMGBtC9pr5", } conf.Network.MaxConns = 64 conf.Network.EnableNATService = false conf.Network.EnableUPnP = false conf.Network.EnableRelay = true conf.Network.NetworkName = "pactus-testnet" conf.Network.DefaultPort = 21777 conf.GRPC.Enable = true conf.GRPC.Listen = "[::]:50052" conf.HTML.Enable = false conf.HTML.Listen = "[::]:80" conf.HTTP.Enable = true conf.HTTP.Listen = "[::]:8080" conf.HTTP.BasePath = "/http" conf.JSONRPC.Enable = true conf.JSONRPC.Listen = "[::]:8545" conf.JSONRPC.Origins = []string{} conf.HTML.EnablePprof = false return conf } func DefaultConfigLocalnet() *Config { conf := defaultConfig() conf.Network.EnableRelay = false conf.Network.EnableNATService = false conf.Network.EnableUPnP = false conf.Network.BootstrapAddrStrings = []string{} conf.Network.MaxConns = 16 conf.Network.NetworkName = "pactus-localnet" conf.Network.DefaultPort = 0 conf.Network.ForcePrivateNetwork = true conf.Network.EnableMdns = true conf.Sync.Moniker = "localnet-1" conf.GRPC.Enable = true conf.GRPC.EnableWallet = true conf.GRPC.Listen = "[::]:50052" conf.HTML.Enable = true conf.HTML.Listen = "[::]:0" conf.HTML.EnablePprof = true conf.HTTP.Enable = true conf.HTTP.Listen = "[::]:8080" conf.JSONRPC.Enable = true conf.JSONRPC.Listen = "[::]:8545" conf.JSONRPC.Origins = []string{"*"} conf.ZeroMq.ZmqPubBlockInfo = "tcp://127.0.0.1:28332" conf.ZeroMq.ZmqPubTxInfo = "tcp://127.0.0.1:28333" conf.ZeroMq.ZmqPubRawBlock = "tcp://127.0.0.1:28334" conf.ZeroMq.ZmqPubRawTx = "tcp://127.0.0.1:28335" conf.ZeroMq.ZmqPubHWM = 1000 return conf } func SaveMainnetConfig(path string) error { conf := string(exampleConfigBytes) return util.WriteFile(path, []byte(conf)) } func (conf *Config) Save(path string) error { return util.WriteFile(path, conf.toTOML()) } func (conf *Config) toTOML() []byte { buf := new(bytes.Buffer) encoder := toml.NewEncoder(buf) encoder.SetIndentTables(true) err := encoder.Encode(conf) if err != nil { panic(err) } return buf.Bytes() } func LoadFromFile(file string, strict bool, defaultConfig *Config) (*Config, error) { data, err := os.ReadFile(file) if err != nil { return nil, err } conf := defaultConfig buf := bytes.NewBuffer(data) decoder := toml.NewDecoder(buf) if strict { decoder.DisallowUnknownFields() } if err := decoder.Decode(conf); err != nil { return nil, err } return conf, nil } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { if err := conf.Node.BasicCheck(); err != nil { return err } if err := conf.Store.BasicCheck(); err != nil { return err } if err := conf.TxPool.BasicCheck(); err != nil { return err } if err := conf.Consensus.BasicCheck(); err != nil { return err } if err := conf.ConsensusV2.BasicCheck(); err != nil { return err } if err := conf.Network.BasicCheck(); err != nil { return err } if err := conf.Logger.BasicCheck(); err != nil { return err } if err := conf.Sync.BasicCheck(); err != nil { return err } if err := conf.JSONRPC.BasicCheck(); err != nil { return err } if err := conf.HTTP.BasicCheck(); err != nil { return err } if err := conf.GRPC.BasicCheck(); err != nil { return err } if err := conf.ZeroMq.BasicCheck(); err != nil { return err } if err := conf.WalletManager.BasicCheck(); err != nil { return err } return conf.HTTP.BasicCheck() } func GetBootstrapNodes() ([]BootstrapInfo, error) { bootstrapNodes := make([]BootstrapInfo, 0) if err := json.Unmarshal(bootstrapInfoBytes, &bootstrapNodes); err != nil { return nil, err } return bootstrapNodes, nil } ================================================ FILE: config/config_test.go ================================================ package config import ( "strings" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSaveMainnetConfig(t *testing.T) { path := util.TempFilePath() require.NoError(t, SaveMainnetConfig(path)) defConf := DefaultConfigMainnet() conf, err := LoadFromFile(path, true, defConf) require.NoError(t, err) require.NoError(t, conf.BasicCheck()) assert.Equal(t, conf, DefaultConfigMainnet()) confData, _ := util.ReadFile(path) exampleData, _ := util.ReadFile("example_config.toml") assert.Equal(t, exampleData, confData) } func TestSaveTestnetConfig(t *testing.T) { crypto.ToTestnetHRP() defer crypto.ToMainnetHRP() path := util.TempFilePath() defConf := DefaultConfigTestnet() require.NoError(t, defConf.Save(path)) conf, err := LoadFromFile(path, true, defConf) require.NoError(t, err) assert.Equal(t, conf, DefaultConfigTestnet()) require.NoError(t, conf.BasicCheck()) } func TestDefaultConfig(t *testing.T) { conf := defaultConfig() require.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) assert.Empty(t, conf.Network.NetworkName) assert.Empty(t, conf.Network.DefaultPort) assert.False(t, conf.GRPC.Enable) assert.False(t, conf.HTML.Enable) assert.False(t, conf.HTTP.Enable) assert.False(t, conf.JSONRPC.Enable) assert.Empty(t, conf.GRPC.Listen) assert.Empty(t, conf.HTML.Listen) assert.Empty(t, conf.HTTP.Listen) assert.Empty(t, conf.JSONRPC.Listen) } func TestMainnetConfig(t *testing.T) { conf := DefaultConfigMainnet() require.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) assert.Equal(t, "pactus", conf.Network.NetworkName) assert.Equal(t, 21888, conf.Network.DefaultPort) assert.True(t, conf.GRPC.Enable) assert.False(t, conf.HTML.Enable) assert.False(t, conf.HTTP.Enable) assert.False(t, conf.JSONRPC.Enable) assert.Equal(t, "127.0.0.1:50051", conf.GRPC.Listen) assert.Equal(t, "127.0.0.1:80", conf.HTML.Listen) assert.Equal(t, "127.0.0.1:8080", conf.HTTP.Listen) assert.Equal(t, "127.0.0.1:8545", conf.JSONRPC.Listen) } func TestTestnetConfig(t *testing.T) { crypto.ToTestnetHRP() defer crypto.ToMainnetHRP() conf := DefaultConfigTestnet() require.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) assert.Equal(t, "pactus-testnet", conf.Network.NetworkName) assert.Equal(t, 21777, conf.Network.DefaultPort) assert.True(t, conf.GRPC.Enable) assert.False(t, conf.HTML.Enable) assert.True(t, conf.HTTP.Enable) assert.True(t, conf.JSONRPC.Enable) assert.Equal(t, "[::]:50052", conf.GRPC.Listen) assert.Equal(t, "[::]:80", conf.HTML.Listen) assert.Equal(t, "[::]:8080", conf.HTTP.Listen) assert.Equal(t, "[::]:8545", conf.JSONRPC.Listen) } func TestLocalnetConfig(t *testing.T) { conf := DefaultConfigLocalnet() require.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) assert.Equal(t, "pactus-localnet", conf.Network.NetworkName) assert.Equal(t, 0, conf.Network.DefaultPort) assert.True(t, conf.GRPC.Enable) assert.True(t, conf.HTML.Enable) assert.True(t, conf.HTTP.Enable) assert.True(t, conf.JSONRPC.Enable) assert.Equal(t, "[::]:50052", conf.GRPC.Listen) assert.Equal(t, "[::]:0", conf.HTML.Listen) assert.Equal(t, "[::]:8080", conf.HTTP.Listen) assert.Equal(t, "[::]:8545", conf.JSONRPC.Listen) } func TestLoadFromFile(t *testing.T) { path := util.TempFilePath() defConf := DefaultConfigMainnet() _, err := LoadFromFile(path, true, defConf) require.Error(t, err, "not exists") require.NoError(t, util.WriteFile(path, []byte(`foo = "bar"`))) _, err = LoadFromFile(path, true, defConf) require.Error(t, err, "unknown field") conf, err := LoadFromFile(path, false, defConf) require.NoError(t, err) assert.Equal(t, defConf, conf) } func TestExampleConfig(t *testing.T) { lines := strings.Split(string(exampleConfigBytes), "\n") exampleToml := "" for _, line := range lines { //lint:ignore QF1001 Reason for ignoring (e.g., readability) if !strings.HasPrefix(line, "# ") && !strings.HasPrefix(line, "###") && !strings.HasPrefix(line, " # ") && !strings.HasPrefix(line, " # ") && !strings.HasPrefix(line, " # ") { exampleToml += line exampleToml += "\n" } } defaultConf := DefaultConfigMainnet() defaultToml := string(defaultConf.toTOML()) exampleToml = strings.ReplaceAll(exampleToml, "\r\n", "\n") // For Windows exampleToml = strings.ReplaceAll(exampleToml, "\n\n", "\n") defaultToml = strings.ReplaceAll(defaultToml, "\n\n", "\n") defaultToml = strings.TrimSpace(defaultToml) exampleToml = strings.TrimSpace(exampleToml) assert.Equal(t, defaultToml, exampleToml) } func TestNodeConfigBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) randValAddr := ts.RandValAddress() tests := []struct { name string expectedErr error updateFn func(c *NodeConfig) }{ { name: "Invalid reward addresses", expectedErr: NodeConfigError{ Reason: "invalid reward address: invalid bech32 string length 4", }, updateFn: func(c *NodeConfig) { c.RewardAddresses = []string{ "abcd", } }, }, { name: "Validator address as reward address", expectedErr: NodeConfigError{ Reason: "reward address is not an account address: " + randValAddr.String(), }, updateFn: func(c *NodeConfig) { c.RewardAddresses = []string{ randValAddr.String(), } }, }, { name: "Two rewards addresses", updateFn: func(c *NodeConfig) { c.RewardAddresses = []string{ ts.RandAccAddress().String(), ts.RandAccAddress().String(), } }, }, { name: "No reward address", updateFn: func(c *NodeConfig) { c.RewardAddresses = []string{} }, }, { name: "DefaultConfig", updateFn: func(*NodeConfig) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultNodeConfig() tt.updateFn(conf) if tt.expectedErr != nil { err := conf.BasicCheck() require.ErrorIs(t, tt.expectedErr, err, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } func TestGetBootstrapNodes(t *testing.T) { nodes, err := GetBootstrapNodes() require.NoError(t, err) assert.NotEmpty(t, nodes, "Bootstrap nodes list should not be empty") // Verify structure of bootstrap nodes for _, node := range nodes { assert.NotEmpty(t, node.Address, "Bootstrap node address should not be empty") // Name, Email, Website might be empty for some nodes, but Address must exist // Verify address format (should be multiaddr format) assert.True(t, strings.HasPrefix(node.Address, "/dns/") || strings.HasPrefix(node.Address, "/ip4/") || strings.HasPrefix(node.Address, "/ip6/"), "Address should be in multiaddr format: %s", node.Address) } // Check that official Pactus bootstrap nodes exist foundPactusBootstrap := false for _, node := range nodes { if node.Name == "Pactus" && strings.Contains(node.Address, "bootstrap") { foundPactusBootstrap = true assert.Equal(t, "info@pactus.org", node.Email) assert.Equal(t, "https://pactus.org", node.Website) break } } assert.True(t, foundPactusBootstrap, "Should contain at least one official Pactus bootstrap node") } func TestBootstrapInfoStructure(t *testing.T) { nodes, err := GetBootstrapNodes() require.NoError(t, err) require.NotEmpty(t, nodes) // Verify that the first node has the expected field types firstNode := nodes[0] assert.IsType(t, "", firstNode.Name) assert.IsType(t, "", firstNode.Email) assert.IsType(t, "", firstNode.Website) assert.IsType(t, "", firstNode.Address) } ================================================ FILE: config/errors.go ================================================ package config // NodeConfigError is returned when the config configuration is invalid. type NodeConfigError struct { Reason string } func (e NodeConfigError) Error() string { return e.Reason } ================================================ FILE: config/example_config.toml ================================================ ### This configuration file specifies configurations for running a Pactus node. # `node` contains configuration options for the Pactus node. [node] # `reward_addresses` specifies the addresses for collecting rewards. # If empty, reward addresses will be obtained from the wallet. # If it has only one address, it is used for all validators. # Otherwise, the number of reward addresses should be the same as the number of validators. reward_addresses = [] # `store` contains configuration options for the store module, which manages storage and retrieval of blockchain data. [store] # `path` specifies the directory where blockchain data will be stored. # Default is 'data'. path = 'data' # `retention_days` this parameter indicates the number of days for which the node should keep or retain the blocks # before pruning them. It is only applicable if the node is in Prune Mode. # Default is `10` days. retention_days = 10 # `network` contains configuration options for the network module, which manages communication between nodes. [network] # `network_key` specifies the private key filename to use for node authentication and encryption in the p2p protocol. # Default is `'network_key'`. network_key = 'network_key' # `public_addr` is the address that is public and accessible to other nodes. public_addr = '' # `listen_addrs` specifies the addresses and ports where the node will listen for incoming connections from other nodes. listen_addrs = [] # `bootstrap_addrs` is a list of peer addresses needed for peer discovery. # These addresses are used by the Pactus node to discover and connect to other peers on the network. bootstrap_addrs = [] # `max_connections` is the maximum number of connections that the Pactus node maintains. # Default is `64`. max_connections = 64 # `enable_udp` indicates whether the UDP transport protocol should be enabled or not. # Enabling UDP can improve the network connectivity of the node, but it might also lead to many packet losses. # Default is `false`. enable_udp = false # `enable_nat_service` provides a service to other peers for determining their reachability status. # Default is `false`. enable_nat_service = false # `enable_upnp` will attempt to open a port in your network's firewall using UPnP. # Default is `false`. enable_upnp = false # `enable_relay` indicates whether relay service should be enabled or not. # Relay service is a transport protocol that routes traffic between two peers over a third-party “relay” peer. # Default is `true`. enable_relay = true # `enable_relay_service` indicates whether relay service should be enabled or not. # Relay service is a transport protocol that enables peers to discover each other on the peer-to-peer network. # Default is `false`. enable_relay_service = false # `enable_mdns` indicates whether MDNS should be enabled or not. # MDNS is a protocol to discover local peers quickly and efficiently. # Default is `false`. enable_mdns = false # `enable_metrics` provides the network metrics for the Prometheus software. # Default is `false`. enable_metrics = false # `force_private_network` forces the connection to nodes within a private network. # A private network is a computer network that uses private addresses. # Read more about private networks here: https://en.wikipedia.org/wiki/Private_network # Default is `false`. force_private_network = false # `sync` contains configuration of sync module. [sync] # `moniker` is a custom human-readable name for this node. moniker = '' # `session_timeout` is a timeout for a download session to remain open. # When a block download request is sent, this timer starts. If there is no activity from the target Node, # the session will be closed after the timeout and try to get the block from another peer. # Default is `'10s'`. session_timeout = '10s' # `sync.firewall` contains configuration options for the sync firewall. [sync.firewall] # `banned_nets` contains the list of IPs and subnets that should be banned. # Any incoming and outgoing connections to banned addresses will be terminated. banned_nets = [] # `rate_limit` contains the rate limit configurations for network topics. # The rate limit specifies the number of messages per second that are allowed. # If set to zero, it allows all requests without any limit. [sync.firewall.rate_limit] # `block_topic` specifies the rate limit for the block topic. block_topic = 1 # `transaction_topic` specifies the rate limit for the transaction topic. transaction_topic = 5 # `consensus_topic` specifies the rate limit for the consensus topic. consensus_topic = 0 # `tx_pool` contains configuration options for the transaction pool module. [tx_pool] # `max_size` indicates the maximum number of unconfirmed transactions inside the pool. # Default is `1000`. max_size = 1000 # `tx_pool.fee` contains configuration to calculate the transaction fee. [tx_pool.fee] # The `fixed_fee` is a constant fee in PAC that applies to each transaction, regardless of its size or type. # Default is `0.01` PAC. fixed_fee = 0.01 # The `daily_limit` is the number of bytes an account can send each day without paying a fee. # The `daily_limit` is part of the consumptional fee model. # To understand how the consumptional fee model works, you can refer to # PIP-31: Consumptional Fee Mode (https://pips.pactus.org/PIPs/pip-31) # Default is `360` bytes. daily_limit = 360 # The `unit_price` defines the fee per byte in PAC. # The `unit_price` is part of the consumptional fee model. # If it is zero, the consumptional fee will be ignored. # To understand how the consumptional fee model works, you can refer to # PIP-31: Consumptional Fee Mode (https://pips.pactus.org/PIPs/pip-31) # Default is `0.0` PAC. unit_price = 0.0 # `logger` contains configuration options for the logger. [logger] # `colorful` indicates whether log can be colorful or not. # Default is `true`. colorful = true # `max_backups` is the maximum number of old log files to retain. # Default is `0`. max_backups = 0 # `rotate_log_after_days` is the maximum number of days to retain old log files. # Default is `1`. rotate_log_after_days = 1 # `compress` determines if the rotated log files should be compressed. # Default is `true`. compress = true # `targets` determines where the logs will be shown, saved, or sent. # Default is `['console', 'file']`. targets = ['console', 'file'] # `logger.levels` contains the level of logger per module. # Available log levels are: # 'trace', 'debug', 'info', 'warn', and 'error'. [logger.levels] _consensus = 'warn' _firewall = 'warn' _grpc = 'info' _html = 'info' _http = 'info' _jsonrpc = 'info' _network = 'error' _pool = 'error' _state = 'info' _sync = 'error' _zmq = 'info' default = 'info' # `grpc` contains configuration for the gRPC server. [grpc] # `enable` indicates whether the gRPC service should be enabled. # Default is `true`. enable = true # `enable_wallet` indicates whether the Wallet service should be enabled. # Default is `false`. enable_wallet = false # `listen` is the address the gRPC server will listen on for incoming connections. listen = '127.0.0.1:50051' # `basic_auth` is the Basic Auth credential used to enhance gRPC security. basic_auth = '' # `jsonrpc` contains configuration for the JSON-RPC server. [jsonrpc] # `enable` indicates whether the JSON-RPC service should be enabled. # Default is `false`. enable = false # `listen` is the address the JSON-RPC server will listen on for incoming connections. listen = '127.0.0.1:8545' # `origins` specifies the allowed CORS origins for the JSON-RPC server. # This controls which domains can make requests to the JSON-RPC API from a browser. # Only the specified origins will be allowed. If not set or left empty, CORS is disabled by default. # Example: origins = ["wallet.pactus.org"] origins = [] # `http` contains configuration for the HTTP-API server. [http] # `enable` indicates whether the HTTP-API should be enabled. # Default is `false`. enable = false # `listen` is the address the HTTP-API server will listen on for incoming connections. listen = '127.0.0.1:8080' # `base_path` sets the URL prefix for all HTTP-API endpoints. base_path = '/http' # `enable_cors` indicates whether Cross-Origin Resource Sharing (CORS) # should be enabled. # Default is `false`. enable_cors = false # `html` contains configuration for the HTML server. # HTML server is mostly used for debugging and testing purposes. [html] # `enable` indicates whether HTML service should be enabled or not. # Default is `false`. enable = false # `listen` is the address to listen for incoming connections for HTML server. listen = '127.0.0.1:80' # `enable_pprof` Enables Golang's pprof debugger for profiling CPU, memory, and goroutines, # providing key performance insights. Be cautious as it exposes sensitive # data, so enable only in secure environments with restricted access. enable_pprof = false # ZeroMQ configuration. [zeromq] # `zmqpubblockinfo` specifies the address for publishing block info notifications. # Example: 'tcp://127.0.0.1:28332' # Default is '', meaning the topic is disabled zmqpubblockinfo = '' # `zmqpubtxinfo` specifies the address for publishing transaction info notifications. # Example: 'tcp://127.0.0.1:28332' # Default is '', meaning the topic is disabled zmqpubtxinfo = '' # `zmqpubrawblock` specifies the address for publishing raw block notifications. # Example: 'tcp://127.0.0.1:28332' # Default is '', meaning the topic is disabled zmqpubrawblock = '' # `zmqpubrawtx` specifies the address for publishing raw transaction notifications. # Example: 'tcp://127.0.0.1:28332' # Default is '', meaning the topic is disabled zmqpubrawtx = '' # `zmqpubhwm` defines the High Watermark (HWM) for ZeroMQ message pipes. # This parameter determines the maximum number of messages ZeroMQ can buffer before blocking the publishing of further messages. # The watermark is applied uniformly to all active topics. # Default is 1000 zmqpubhwm = 1000 # `wallet` contains wallet storage options. [wallet] # `lock_mode` controls how wallets behave when it opens. # If true, wallets will be locked when it opens and won't allow other instances to open the same wallet. # If false, wallets will not be locked when it opens and other instances can open the same wallet. lock_mode = true ================================================ FILE: consensus/commit.go ================================================ package consensus import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type commitState struct { *consensus } func (s *commitState) enter() { s.decide() } func (s *commitState) decide() { roundProposal := s.log.RoundProposal(s.round) certBlock := roundProposal.Block() precommits := s.log.PrecommitVoteSet(s.round) votes := precommits.BlockVotes(certBlock.Hash()) cert := s.makeCertificate(votes) err := s.bcState.CommitBlock(certBlock, cert) if err != nil { s.logger.Error("committing block failed", "block", certBlock, "error", err) } else { s.logger.Info("block committed, schedule new height", "hash", certBlock.Hash()) } // Now we can announce the committed block and certificate s.announceNewBlock(certBlock, cert, nil) s.enterNewState(s.newHeightState) } func (*commitState) onAddVote(_ *vote.Vote) { panic("Unreachable") } func (*commitState) onSetProposal(_ *proposal.Proposal) { panic("Unreachable") } func (*commitState) onTimeout(_ *ticker) { panic("Unreachable") } func (*commitState) name() string { return "commit" } ================================================ FILE: consensus/config.go ================================================ package consensus import ( "time" "github.com/pactus-project/pactus/types" ) // Config defines parameters for the legacy consensus algorithm. type Config struct { ChangeProposerTimeout time.Duration `toml:"-"` ChangeProposerDelta time.Duration `toml:"-"` QueryVoteTimeout time.Duration `toml:"-"` MinimumAvailabilityScore float64 `toml:"-"` } func DefaultConfig() *Config { return &Config{ ChangeProposerTimeout: 5 * time.Second, ChangeProposerDelta: 5 * time.Second, QueryVoteTimeout: 5 * time.Second, MinimumAvailabilityScore: 0.666667, } } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { if conf.ChangeProposerTimeout <= 0 { return ConfigError{ Reason: "change proposer timeout must be greater than zero", } } if conf.ChangeProposerDelta <= 0 { return ConfigError{ Reason: "change proposer delta must be greater than zero", } } if conf.MinimumAvailabilityScore < 0 || conf.MinimumAvailabilityScore > 1 { return ConfigError{ Reason: "minimum availability score can't be negative or more than 1", } } return nil } func (conf *Config) CalculateChangeProposerTimeout(round types.Round) time.Duration { return conf.ChangeProposerTimeout + conf.ChangeProposerDelta*time.Duration(round) } ================================================ FILE: consensus/config_test.go ================================================ package consensus import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConfigBasicCheck(t *testing.T) { tests := []struct { name string expectedErr error updateFn func(c *Config) }{ { name: "Invalid ChangeProposerDelta", expectedErr: ConfigError{ Reason: "change proposer delta must be greater than zero", }, updateFn: func(c *Config) { c.ChangeProposerDelta = 0 }, }, { name: "Invalid ChangeProposerTimeout", expectedErr: ConfigError{ Reason: "change proposer timeout must be greater than zero", }, updateFn: func(c *Config) { c.ChangeProposerTimeout = -1 * time.Second }, }, { name: "Invalid MinimumAvailabilityScore", expectedErr: ConfigError{ Reason: "minimum availability score can't be negative or more than 1", }, updateFn: func(c *Config) { c.MinimumAvailabilityScore = 1.5 }, }, { name: "Invalid MinimumAvailabilityScore - Negative", expectedErr: ConfigError{ Reason: "minimum availability score can't be negative or more than 1", }, updateFn: func(c *Config) { c.MinimumAvailabilityScore = -0.8 }, }, { name: "DefaultConfig", updateFn: func(*Config) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() tt.updateFn(conf) if tt.expectedErr != nil { err := conf.BasicCheck() require.ErrorIs(t, tt.expectedErr, err, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } func TestCalculateChangeProposerTimeout(t *testing.T) { c := DefaultConfig() assert.Equal(t, c.ChangeProposerTimeout, c.CalculateChangeProposerTimeout(0)) assert.Equal(t, c.ChangeProposerTimeout+c.ChangeProposerDelta, c.CalculateChangeProposerTimeout(1)) assert.Equal(t, c.ChangeProposerTimeout+(4*c.ChangeProposerDelta), c.CalculateChangeProposerTimeout(4)) } ================================================ FILE: consensus/consensus.go ================================================ package consensus import ( "context" "fmt" "sync" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/ezex-io/gopkg/scheduler" "github.com/pactus-project/pactus/consensus/log" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" ) type broadcaster func(crypto.Address, message.Message) type consensus struct { lk sync.RWMutex ctx context.Context config *Config logger *logger.SubLogger log *log.Log validators []*validator.Validator cpWeakValidity *hash.Hash // The change proposer's weak validity that is a prepared block hash cpDecided int height types.Height round types.Round cpRound int16 valKey *bls.ValidatorKey rewardAddr crypto.Address bcState state.Facade // Blockchain state changeProposer *changeProposer newHeightState consState proposeState consState prepareState consState precommitState consState commitState consState cpPreVoteState consState cpMainVoteState consState cpDecideState consState currentState consState broadcaster broadcaster mediator mediator active bool } func NewConsensus( ctx context.Context, conf *Config, bcState state.Facade, valKey *bls.ValidatorKey, rewardAddr crypto.Address, broadcastPipe pipeline.Pipeline[message.Message], mediator mediator, ) Consensus { broadcaster := func(_ crypto.Address, msg message.Message) { broadcastPipe.Send(msg) } return makeConsensus(ctx, conf, bcState, valKey, rewardAddr, broadcaster, mediator) } func makeConsensus( ctx context.Context, conf *Config, bcState state.Facade, valKey *bls.ValidatorKey, rewardAddr crypto.Address, broadcaster broadcaster, mediator mediator, ) *consensus { cons := &consensus{ ctx: ctx, config: conf, bcState: bcState, broadcaster: broadcaster, valKey: valKey, } // Update height later, See enterNewHeight. cons.log = log.NewLog() cons.logger = logger.NewSubLogger("_consensus", cons) cons.rewardAddr = rewardAddr cons.changeProposer = &changeProposer{cons} cons.newHeightState = &newHeightState{cons} cons.proposeState = &proposeState{cons} cons.prepareState = &prepareState{cons, false} cons.precommitState = &precommitState{cons, false} cons.commitState = &commitState{cons} cons.cpPreVoteState = &cpPreVoteState{cons.changeProposer} cons.cpMainVoteState = &cpMainVoteState{cons.changeProposer} cons.cpDecideState = &cpDecideState{cons.changeProposer} cons.currentState = cons.newHeightState cons.mediator = mediator cons.height = 0 cons.round = 0 cons.active = false cons.mediator = mediator mediator.Register(cons) logger.Info("consensus instance created (Legacy)", "validator address", valKey.Address().String(), "reward address", rewardAddr.String()) return cons } // LogString returns a concise string representation intended for use in logs. func (cs *consensus) LogString() string { return fmt.Sprintf("{%s %d/%d/%s/%d}", cs.valKey.Address(), cs.height, cs.round, cs.currentState.name(), cs.cpRound) } func (cs *consensus) ConsensusKey() *bls.PublicKey { cs.lk.RLock() defer cs.lk.RUnlock() return cs.valKey.PublicKey() } func (cs *consensus) HeightRound() (types.Height, types.Round) { cs.lk.RLock() defer cs.lk.RUnlock() return cs.height, cs.round } func (cs *consensus) HasVote(h hash.Hash) bool { cs.lk.RLock() defer cs.lk.RUnlock() return cs.log.HasVote(h) } // AllVotes returns all valid votes inside the consensus log up to and including // the current consensus round. // Valid votes from subsequent rounds are not included. func (cs *consensus) AllVotes() []*vote.Vote { cs.lk.RLock() defer cs.lk.RUnlock() votes := []*vote.Vote{} for r := types.Round(0); r <= cs.round; r++ { m := cs.log.RoundMessages(r) votes = append(votes, m.AllVotes()...) } return votes } func (cs *consensus) enterNewState(s consState) { cs.currentState = s cs.currentState.enter() } func (cs *consensus) MoveToNewHeight() { cs.lk.Lock() defer cs.lk.Unlock() if cs.IsDeprecated() { return } stateHeight := cs.bcState.LastBlockHeight() if cs.height != stateHeight+1 { cs.enterNewState(cs.newHeightState) } } func (cs *consensus) scheduleTimeout(duration time.Duration, height types.Height, round types.Round, target tickerTarget, ) { cs.logger.Trace("new timer scheduled ⏱️", "duration", duration, "height", height, "round", round, "target", target) ticker := &ticker{duration, height, round, target} scheduler.After(duration).Do(cs.ctx, func(context.Context) { cs.handleTimeout(ticker) }) } func (cs *consensus) handleTimeout(ticker *ticker) { cs.lk.Lock() defer cs.lk.Unlock() cs.logger.Trace("handle ticker", "ticker", ticker) // Old tickers might be triggered now. Ignore them. if cs.height != ticker.Height || cs.round != ticker.Round { cs.logger.Trace("stale ticker", "ticker", ticker) return } cs.logger.Debug("timer expired", "ticker", ticker) cs.currentState.onTimeout(ticker) } func (cs *consensus) SetProposal(prop *proposal.Proposal) { cs.lk.Lock() defer cs.lk.Unlock() if !cs.active { return } if prop.Height() != cs.height { return } if prop.Round() < cs.round { cs.logger.Debug("proposal for expired round", "proposal", prop) return } if err := prop.BasicCheck(); err != nil { cs.logger.Warn("invalid proposal", "proposal", prop, "error", err) return } roundProposal := cs.log.RoundProposal(prop.Round()) if roundProposal != nil { cs.logger.Trace("this round has proposal", "proposal", prop) return } if prop.Height() == cs.bcState.LastBlockHeight() { // A slow node might receive a proposal after committing the proposed block. // In this case, we accept the proposal and allow nodes to continue. // By doing so, we enable the validator to broadcast its votes and // prevent it from being marked as absent in the block certificate. cs.logger.Warn("block committed before receiving proposal", "proposal", prop) if prop.Block().Hash() != cs.bcState.LastBlockHash() { cs.logger.Warn("proposal is not for the committed block", "proposal", prop) return } } else { proposer := cs.proposer(prop.Round()) if err := prop.Verify(proposer.PublicKey()); err != nil { cs.logger.Warn("proposal is invalid", "proposal", prop, "error", err) return } if err := cs.bcState.ValidateBlock(prop.Block(), prop.Round()); err != nil { cs.logger.Warn("invalid block", "proposal", prop, "error", err) return } } cs.logger.Info("proposal set", "proposal", prop) cs.log.SetRoundProposal(prop.Round(), prop) cs.currentState.onSetProposal(prop) } func (cs *consensus) AddVote(vte *vote.Vote) { cs.lk.Lock() defer cs.lk.Unlock() if !cs.active { return } if vte.Height() != cs.height { return } if vte.Round() < cs.round { cs.logger.Debug("vote for expired round", "vote", vte) return } if vte.Type() == vote.VoteTypeCPPreVote || vte.Type() == vote.VoteTypeCPMainVote || vte.Type() == vote.VoteTypeCPDecided { err := cs.changeProposer.checkJust(vte) if err != nil { cs.logger.Error("error on adding a cp vote", "vote", vte, "error", err) return } } added, err := cs.log.AddVote(vte) if err != nil { cs.logger.Error("error on adding a vote", "vote", vte, "error", err) } if added { cs.logger.Info("new vote added", "vote", vte) cs.currentState.onAddVote(vte) } } func (cs *consensus) proposer(round types.Round) *validator.Validator { return cs.bcState.Proposer(round) } func (cs *consensus) IsProposer() bool { cs.lk.RLock() defer cs.lk.RUnlock() return cs.isProposer() } func (cs *consensus) isProposer() bool { return cs.proposer(cs.round).Address() == cs.valKey.Address() } func (cs *consensus) signAddCPPreVote(h hash.Hash, cpRound int16, cpValue vote.CPValue, just vote.Just, ) { v := vote.NewCPPreVote(h, cs.height, cs.round, cpRound, cpValue, just, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensus) signAddCPMainVote(h hash.Hash, cpRound int16, cpValue vote.CPValue, just vote.Just, ) { v := vote.NewCPMainVote(h, cs.height, cs.round, cpRound, cpValue, just, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensus) signAddCPDecidedVote(h hash.Hash, cpRound int16, cpValue vote.CPValue, just vote.Just, ) { v := vote.NewCPDecidedVote(h, cs.height, cs.round, cpRound, cpValue, just, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensus) signAddPrepareVote(h hash.Hash) { v := vote.NewPrepareVote(h, cs.height, cs.round, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensus) signAddPrecommitVote(h hash.Hash) { v := vote.NewPrecommitVote(h, cs.height, cs.round, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensus) signAddVote(vte *vote.Vote) { sig := cs.valKey.Sign(vte.SignBytes()) vte.SetSignature(sig) cs.logger.Info("our vote signed and broadcasted", "vote", vte) _, err := cs.log.AddVote(vte) if err != nil { cs.logger.Warn("error on adding our vote", "error", err, "vote", vte) } cs.broadcastVote(vte) } // queryProposal requests any missing proposal from other validators. func (cs *consensus) queryProposal() { cs.broadcaster(cs.valKey.Address(), message.NewQueryProposalMessage(cs.height, cs.round, cs.valKey.Address())) } // queryVote requests any missing votes from other validators. func (cs *consensus) queryVote() { cs.broadcaster(cs.valKey.Address(), message.NewQueryVoteMessage(cs.height, cs.round, cs.valKey.Address())) } func (cs *consensus) broadcastProposal(p *proposal.Proposal) { go cs.mediator.OnPublishProposal(cs, p) cs.broadcaster(cs.valKey.Address(), message.NewProposalMessage(p)) } func (cs *consensus) broadcastVote(v *vote.Vote) { go cs.mediator.OnPublishVote(cs, v) cs.broadcaster(cs.valKey.Address(), message.NewVoteMessage(v)) } func (cs *consensus) announceNewBlock(blk *block.Block, cert *certificate.Certificate, proof *certificate.Certificate, ) { go cs.mediator.OnBlockAnnounce(cs) cs.broadcaster(cs.valKey.Address(), message.NewBlockAnnounceMessage(blk, cert, proof)) } func (cs *consensus) makeCertificate(votes map[crypto.Address]*vote.Vote, ) *certificate.Certificate { cert := certificate.NewCertificate(cs.height, cs.round) cert.SetSignature(cs.signersInfo(votes)) return cert } // signersInfo processes a map of votes from validators and provides these information: // - A list of all validators' numbers eligible to vote in this step. // - A list of absentee validators' numbers who did not vote in this step. // - An aggregated signature generated from the signatures of participating validators. func (cs *consensus) signersInfo(votes map[crypto.Address]*vote.Vote) ( committers, absentees []int32, aggSig *bls.Signature, ) { vals := cs.validators committers = make([]int32, len(vals)) absentees = make([]int32, 0) sigs := make([]*bls.Signature, 0) for i, val := range vals { vote := votes[val.Address()] if vote != nil { sigs = append(sigs, vote.Signature()) } else { absentees = append(absentees, val.Number()) } committers[i] = val.Number() } aggSig, _ = bls.SignatureAggregate(sigs...) return committers, absentees, aggSig } // IsActive checks if the consensus is in an active state and participating in the consensus algorithm. func (cs *consensus) IsActive() bool { cs.lk.RLock() defer cs.lk.RUnlock() if cs.IsDeprecated() { return false } return cs.active } func (cs *consensus) Proposal() *proposal.Proposal { cs.lk.RLock() defer cs.lk.RUnlock() return cs.log.RoundProposal(cs.round) } func (cs *consensus) HandleQueryProposal(height types.Height, round types.Round) *proposal.Proposal { cs.lk.RLock() defer cs.lk.RUnlock() if !cs.active { return nil } if height != cs.height { return nil } if round != cs.round { return nil } if cs.isProposer() { return cs.log.RoundProposal(cs.round) } if cs.cpDecided == 0 { // It is decided not to change the proposer and the proposal is locked. // Locked proposals can be sent by all validators. // This helps prevent a situation where the proposer goes offline after proposing the block. return cs.log.RoundProposal(cs.round) } return nil } // TODO: Improve the performance? func (cs *consensus) HandleQueryVote(height types.Height, round types.Round) *vote.Vote { cs.lk.RLock() defer cs.lk.RUnlock() if !cs.active { return nil } if height != cs.height { return nil } votes := []*vote.Vote{} switch { case round < cs.round: // Past round: Only broadcast cp:decided votes vs := cs.log.CPDecidedVoteSet(round) votes = append(votes, vs.AllVotes()...) case round == cs.round: // Current round m := cs.log.RoundMessages(round) votes = append(votes, m.AllVotes()...) case round > cs.round: // Future round } if len(votes) == 0 { return nil } return votes[util.RandInt32(int32(len(votes)))] } func (cs *consensus) startChangingProposer() { // If it is not decided yet. // TODO: can we remove this condition in new consensus model? if cs.cpDecided == -1 { cs.logger.Info("changing proposer started", "cpRound", cs.cpRound, "proposer", cs.proposer(cs.round).Address()) cs.enterNewState(cs.cpPreVoteState) } } func (*consensus) IsDeprecated() bool { return false } ================================================ FILE: consensus/consensus_test.go ================================================ package consensus import ( "fmt" "testing" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "golang.org/x/exp/slices" ) const ( tIndexX = 0 tIndexY = 1 tIndexB = 2 tIndexP = 3 ) type consMessage struct { sender crypto.Address message message.Message } type testData struct { *testsuite.TestSuite valKeys []*bls.ValidatorKey mockTxPool *txpool.MockTxPool genDoc *genesis.Genesis consX *consensus // Good peer consY *consensus // Good peer consB *consensus // Byzantine or offline peer consP *consensus // Partitioned peer consMessages []consMessage } func testConfig() *Config { return &Config{ ChangeProposerTimeout: 1 * time.Hour, // Disabling timers ChangeProposerDelta: 1 * time.Hour, // Disabling timers QueryVoteTimeout: 1 * time.Hour, // Disabling timers } } func setup(t *testing.T) *testData { t.Helper() return setupWithSeed(t, testsuite.GenerateSeed()) } func setupWithSeed(t *testing.T, seed int64) *testData { t.Helper() fmt.Printf("=== test %s, seed: %d\n", t.Name(), seed) ts := testsuite.NewTestSuiteFromSeed(t, seed) _, valKeys := ts.GenerateTestCommittee(4) mockTxPool := txpool.NewMockTxPool(ts.Ctrl) mockTxPool.EXPECT().SetNewSandboxAndRecheck(gomock.Any()).Return().AnyTimes() mockTxPool.EXPECT().PrepareBlockTransactions().Return(nil).AnyTimes() mockTxPool.EXPECT().HandleCommittedBlock(gomock.Any()).Return().AnyTimes() vals := make([]*validator.Validator, 4) for i, key := range valKeys { val := validator.NewValidator(key.PublicKey(), int32(i)) vals[i] = val } acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) accs := map[crypto.Address]*account.Account{crypto.TreasuryAddress: acc} params := genesis.DefaultGenesisParams() params.CommitteeSize = 4 // To prevent triggering timers before starting the tests and // avoid double entries for new heights in some tests. getTime := util.RoundNow(params.BlockIntervalInSecond). Add(time.Duration(params.BlockIntervalInSecond) * time.Second) genDoc := genesis.MakeGenesis(getTime, accs, vals, params) eventPipe := pipeline.New[any](t.Context()) stateX, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexX]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) stateY, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexY]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) stateB, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexB]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) stateP, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexP]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) consMessages := make([]consMessage, 0) td := &testData{ TestSuite: ts, valKeys: valKeys, mockTxPool: mockTxPool, genDoc: genDoc, consMessages: consMessages, } broadcasterFunc := func(sender crypto.Address, msg message.Message) { td.consMessages = append(td.consMessages, consMessage{ sender: sender, message: msg, }) } td.consX = makeConsensus(t.Context(), testConfig(), stateX, valKeys[tIndexX], valKeys[tIndexX].PublicKey().AccountAddress(), broadcasterFunc, NewConcreteMediator()) td.consY = makeConsensus(t.Context(), testConfig(), stateY, valKeys[tIndexY], valKeys[tIndexY].PublicKey().AccountAddress(), broadcasterFunc, NewConcreteMediator()) td.consB = makeConsensus(t.Context(), testConfig(), stateB, valKeys[tIndexB], valKeys[tIndexB].PublicKey().AccountAddress(), broadcasterFunc, NewConcreteMediator()) td.consP = makeConsensus(t.Context(), testConfig(), stateP, valKeys[tIndexP], valKeys[tIndexP].PublicKey().AccountAddress(), broadcasterFunc, NewConcreteMediator()) // ------------------------------- // Better logging during testing overrideLogger := func(cons *consensus, name string) { cons.logger = logger.NewSubLogger("_consensus", testsuite.NewOverrideLogStringer(fmt.Sprintf("%s - %s: ", name, t.Name()), cons)) } overrideLogger(td.consX, "consX") overrideLogger(td.consY, "consY") overrideLogger(td.consB, "consB") overrideLogger(td.consP, "consP") // ------------------------------- logger.Info("setup finished, start running the test", "name", t.Name()) return td } func (td *testData) shouldPublishBlockAnnounce(t *testing.T, cons *consensus, hash hash.Hash) { t.Helper() for _, consMsg := range td.consMessages { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeBlockAnnounce { m := consMsg.message.(*message.BlockAnnounceMessage) assert.Equal(t, hash, m.Block.Hash()) return } } require.Fail(t, fmt.Sprintf("should publish block announce for block hash %s", hash)) } func (td *testData) shouldPublishProposal(t *testing.T, cons *consensus, height types.Height, round types.Round, ) *proposal.Proposal { t.Helper() for _, consMsg := range td.consMessages { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeProposal { m := consMsg.message.(*message.ProposalMessage) require.Equal(t, height, m.Proposal.Height()) require.Equal(t, round, m.Proposal.Round()) return m.Proposal } } require.Fail(t, fmt.Sprintf("should publish proposal for height %d and round %d", height, round)) return nil } func (td *testData) shouldNotPublish(t *testing.T, cons *consensus, msgType message.Type) { t.Helper() for _, consMsg := range td.consMessages { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == msgType { require.Fail(t, fmt.Sprintf("should not publish %s", msgType)) } } } func (td *testData) shouldPublishQueryProposal(t *testing.T, cons *consensus, height types.Height) { t.Helper() for _, consMsg := range td.consMessages { if consMsg.sender != cons.valKey.Address() || consMsg.message.Type() != message.TypeQueryProposal { continue } m := consMsg.message.(*message.QueryProposalMessage) assert.Equal(t, m.Height, height) assert.Equal(t, m.Querier, cons.valKey.Address()) return } require.Fail(t, fmt.Sprintf("should publish query proposal message for height %d", height)) } func (td *testData) shouldPublishQueryVote(t *testing.T, cons *consensus, height types.Height, round types.Round) { t.Helper() for _, consMsg := range td.consMessages { if consMsg.sender != cons.valKey.Address() || consMsg.message.Type() != message.TypeQueryVote { continue } m := consMsg.message.(*message.QueryVoteMessage) assert.Equal(t, m.Height, height) assert.Equal(t, m.Round, round) assert.Equal(t, m.Querier, cons.valKey.Address()) return } require.Fail(t, fmt.Sprintf("should publish query vote message for height %d and round %d", height, round)) } func (td *testData) shouldPublishVote(t *testing.T, cons *consensus, voteType vote.Type, hash hash.Hash) *vote.Vote { t.Helper() for i := len(td.consMessages) - 1; i >= 0; i-- { consMsg := td.consMessages[i] if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeVote { m := consMsg.message.(*message.VoteMessage) if m.Vote.Type() == voteType && m.Vote.BlockHash() == hash { return m.Vote } } } require.Fail(t, fmt.Sprintf("should publish %s vote for block hash %s", voteType, hash)) return nil } func (*testData) checkHeightRound(t *testing.T, cons *consensus, height types.Height, round types.Round) { t.Helper() h, r := cons.HeightRound() assert.Equal(t, h, height) assert.Equal(t, r, round) } func (td *testData) addPrepareVote(cons *consensus, blockHash hash.Hash, height types.Height, round types.Round, valID int, ) *vote.Vote { v := vote.NewPrepareVote(blockHash, height, round, td.valKeys[valID].Address()) return td.addVote(cons, v, valID) } func (td *testData) addPrecommitVote(cons *consensus, blockHash hash.Hash, height types.Height, round types.Round, valID int, ) *vote.Vote { v := vote.NewPrecommitVote(blockHash, height, round, td.valKeys[valID].Address()) return td.addVote(cons, v, valID) } func (td *testData) addCPPreVote(cons *consensus, blockHash hash.Hash, height types.Height, round types.Round, cpVal vote.CPValue, just vote.Just, valID int, ) { v := vote.NewCPPreVote(blockHash, height, round, 0, cpVal, just, td.valKeys[valID].Address()) td.addVote(cons, v, valID) } func (td *testData) addCPMainVote(cons *consensus, blockHash hash.Hash, height types.Height, round types.Round, cpVal vote.CPValue, just vote.Just, valID int, ) { v := vote.NewCPMainVote(blockHash, height, round, 0, cpVal, just, td.valKeys[valID].Address()) td.addVote(cons, v, valID) } func (td *testData) addCPDecidedVote(cons *consensus, blockHash hash.Hash, height types.Height, round types.Round, cpVal vote.CPValue, just vote.Just, valID int, ) { v := vote.NewCPDecidedVote(blockHash, height, round, 0, cpVal, just, td.valKeys[valID].Address()) td.addVote(cons, v, valID) } func (td *testData) addVote(cons *consensus, v *vote.Vote, valID int) *vote.Vote { td.HelperSignVote(td.valKeys[valID], v) cons.AddVote(v) return v } func (*testData) newHeightTimeout(cons *consensus) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetNewHeight}) cons.lk.Unlock() } func (*testData) queryProposalTimeout(cons *consensus) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetQueryProposal}) cons.lk.Unlock() } func (*testData) changeProposerTimeout(cons *consensus) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetChangeProposer}) cons.lk.Unlock() } // enterNewHeight helps tests to enter new height safely // without scheduling new height. It boosts the test speed. func (td *testData) enterNewHeight(cons *consensus) { cons.lk.Lock() cons.enterNewState(cons.newHeightState) cons.lk.Unlock() td.newHeightTimeout(cons) } // enterNextRound helps tests to enter next round safely. func (*testData) enterNextRound(cons *consensus) { cons.lk.Lock() cons.round++ cons.enterNewState(cons.proposeState) cons.lk.Unlock() } func (td *testData) commitBlockForAllStates(t *testing.T) (*block.Block, *certificate.Certificate) { t.Helper() height := td.consX.bcState.LastBlockHeight() var err error prop := td.makeProposal(t, height+1, 0) cert := certificate.NewCertificate(height+1, 0) signBytes := cert.SignBytesPrecommit(prop.Block().Hash()) sig1 := td.consX.valKey.Sign(signBytes) sig2 := td.consY.valKey.Sign(signBytes) sig3 := td.consB.valKey.Sign(signBytes) sig4 := td.consP.valKey.Sign(signBytes) sig, _ := bls.SignatureAggregate(sig1, sig2, sig3, sig4) cert.SetSignature([]int32{tIndexX, tIndexY, tIndexB, tIndexP}, []int32{}, sig) blk := prop.Block() err = td.consX.bcState.CommitBlock(blk, cert) require.NoError(t, err) err = td.consY.bcState.CommitBlock(blk, cert) require.NoError(t, err) err = td.consB.bcState.CommitBlock(blk, cert) require.NoError(t, err) err = td.consP.bcState.CommitBlock(blk, cert) require.NoError(t, err) return blk, cert } // makeProposal generates a signed and valid proposal for the given height and round. // If rewardAddr is provided, it will be used instead of the consensus instance's default reward address. func (td *testData) makeProposal(t *testing.T, height types.Height, round types.Round, rewardAddr ...crypto.Address, ) *proposal.Proposal { t.Helper() var cons *consensus switch uint32(height%4) + uint32(round%4) { case 1: cons = td.consX case 2: cons = td.consY case 3: cons = td.consB case 4, 0: cons = td.consP } // Use provided reward address or fall back to consensus instance's default addr := cons.rewardAddr if len(rewardAddr) > 0 { addr = rewardAddr[0] } blk, err := cons.bcState.ProposeBlock(cons.valKey, addr) require.NoError(t, err) p := proposal.NewProposal(height, round, blk) td.HelperSignProposal(cons.valKey, p) return p } func (td *testData) makeMainCertificate(t *testing.T, height types.Height, round types.Round, cpRound int16, ) *certificate.Certificate { t.Helper() // === make valid certificate preVoteCommitters := make([]int32, 0, len(td.consP.validators)) preVoteSigs := make([]*bls.Signature, 0, len(td.consP.validators)) for i, val := range td.consP.validators { preVoteJust := &vote.JustInitYes{} preVote := vote.NewCPPreVote(hash.UndefHash, height, round, cpRound, vote.CPValueYes, preVoteJust, val.Address()) sbPreVote := preVote.SignBytes() preVoteCommitters = append(preVoteCommitters, val.Number()) preVoteSigs = append(preVoteSigs, td.valKeys[i].Sign(sbPreVote)) } preVoteAggSig, _ := bls.SignatureAggregate(preVoteSigs...) certPreVote := certificate.NewCertificate(height, round) certPreVote.SetSignature(preVoteCommitters, []int32{}, preVoteAggSig) mainVoteCommitters := make([]int32, 0, len(td.consP.validators)) mainVoteSigs := make([]*bls.Signature, 0, len(td.consP.validators)) for i, val := range td.consP.validators { mainVoteJust := &vote.JustMainVoteNoConflict{ QCert: certPreVote, } mainVote := vote.NewCPMainVote(hash.UndefHash, height, round, cpRound, vote.CPValueYes, mainVoteJust, val.Address()) sbMainVote := mainVote.SignBytes() mainVoteCommitters = append(mainVoteCommitters, val.Number()) mainVoteSigs = append(mainVoteSigs, td.valKeys[i].Sign(sbMainVote)) } mainVoteAggSig, _ := bls.SignatureAggregate(mainVoteSigs...) certMainVote := certificate.NewCertificate(height, round) certMainVote.SetSignature(mainVoteCommitters, []int32{}, mainVoteAggSig) return certMainVote } func TestStart(t *testing.T) { td := setup(t) td.consX.MoveToNewHeight() td.checkHeightRound(t, td.consX, 1, 0) } func TestNotInCommittee(t *testing.T) { td := setup(t) valKey := td.RandValKey() state := state.MockingState(td.TestSuite) pipe := pipeline.New[message.Message](t.Context()) consInt := NewConsensus(t.Context(), testConfig(), state, valKey, valKey.Address(), pipe, NewConcreteMediator()) cons := consInt.(*consensus) td.enterNewHeight(cons) td.newHeightTimeout(cons) assert.Equal(t, "new-height", cons.currentState.name()) } func TestIsProposer(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) assert.False(t, td.consX.IsProposer()) assert.True(t, td.consY.IsProposer()) } func TestVoteWithInvalidHeight(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) v1 := td.addPrepareVote(td.consP, td.RandHash(), 1, 0, tIndexX) v2 := td.addPrepareVote(td.consP, td.RandHash(), 2, 0, tIndexX) v3 := td.addPrepareVote(td.consP, td.RandHash(), 2, 0, tIndexY) v4 := td.addPrepareVote(td.consP, td.RandHash(), 3, 0, tIndexX) require.False(t, td.consP.HasVote(v1.Hash())) require.True(t, td.consP.HasVote(v2.Hash())) require.True(t, td.consP.HasVote(v3.Hash())) require.False(t, td.consP.HasVote(v4.Hash())) } func TestConsensusNormalCase(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consX) td.checkHeightRound(t, td.consX, 2, 0) prop := td.makeProposal(t, 2, 0) td.consX.SetProposal(prop) td.addPrepareVote(td.consX, prop.Block().Hash(), 2, 0, tIndexY) td.addPrepareVote(td.consX, prop.Block().Hash(), 2, 0, tIndexP) td.shouldPublishVote(t, td.consX, vote.VoteTypePrepare, prop.Block().Hash()) td.addPrecommitVote(td.consX, prop.Block().Hash(), 2, 0, tIndexY) td.addPrecommitVote(td.consX, prop.Block().Hash(), 2, 0, tIndexP) td.shouldPublishVote(t, td.consX, vote.VoteTypePrecommit, prop.Block().Hash()) td.shouldPublishBlockAnnounce(t, td.consX, prop.Block().Hash()) } func TestConsensusAddVote(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) vote1 := td.addPrepareVote(td.consP, td.RandHash(), 1, 0, tIndexX) vote2 := td.addPrepareVote(td.consP, td.RandHash(), 1, 2, tIndexX) vote3 := td.addPrepareVote(td.consP, td.RandHash(), 1, 1, tIndexX) vote4 := td.addPrecommitVote(td.consP, td.RandHash(), 1, 1, tIndexX) vote5 := td.addPrepareVote(td.consP, td.RandHash(), 2, 0, tIndexX) vote6, _ := td.GenerateTestPrepareVote(1, 0) td.consP.AddVote(vote6) assert.False(t, td.consP.HasVote(vote1.Hash())) // previous round assert.True(t, td.consP.HasVote(vote2.Hash())) // next round assert.True(t, td.consP.HasVote(vote3.Hash())) assert.True(t, td.consP.HasVote(vote4.Hash())) assert.False(t, td.consP.HasVote(vote5.Hash())) // valid votes for the next height assert.False(t, td.consP.HasVote(vote6.Hash())) // invalid votes assert.Equal(t, []*vote.Vote{vote3, vote4}, td.consP.AllVotes()) assert.NotContains(t, td.consP.AllVotes(), vote2) } // TestConsensusLateProposal tests the scenario where a slow node receives a proposal // after committing the block. func TestConsensusLateProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) require.NotNil(t, prop) td.commitBlockForAllStates(t) // height 2 // Partitioned node receives proposal now td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop.Block().Hash()) } // TestSetProposalOnPrepare tests the scenario where a slow node receives a proposal // in prepare phase. func TestSetProposalOnPrepare(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) require.NotNil(t, prop) // The partitioned node receives all the votes first td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) // Partitioned node receives proposal now td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } // TestSetProposalOnPrecommit tests the scenario where a slow node receives a proposal // in precommit phase. func TestSetProposalOnPrecommit(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) require.NotNil(t, prop) // The partitioned node receives all the votes first td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexB) // Partitioned node receives proposal now td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) td.shouldPublishBlockAnnounce(t, td.consP, prop.Block().Hash()) } // update me from TestHandleQueryVote: consensus:v1. func TestHandleQueryVote(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) cpRound := int16(0) height := types.Height(1) assert.Nil(t, td.consP.HandleQueryVote(height, 0)) // Add some votes for Round 0 td.addCPDecidedVote(td.consP, hash.UndefHash, height, 0, vote.CPValueYes, &vote.JustDecided{QCert: td.makeMainCertificate(t, height, 0, cpRound)}, tIndexY) // Add some votes for Round 1 td.enterNextRound(td.consP) td.addPrepareVote(td.consP, td.RandHash(), height, 1, tIndexX) td.addCPPreVote(td.consP, hash.UndefHash, height, 1, vote.CPValueYes, &vote.JustInitYes{}, tIndexY) td.addCPDecidedVote(td.consP, hash.UndefHash, height, 1, vote.CPValueYes, &vote.JustDecided{QCert: td.makeMainCertificate(t, height, 1, cpRound)}, tIndexY) // Add some votes for Round 2 td.enterNextRound(td.consP) td.addPrepareVote(td.consP, td.RandHash(), height, 2, tIndexY) t.Run("Query vote for round 0: should send the decided vote for the round 0", func(t *testing.T) { rndVote := td.consP.HandleQueryVote(height, 0) assert.Equal(t, vote.VoteTypeCPDecided, rndVote.Type()) assert.Equal(t, height, rndVote.Height()) assert.Equal(t, types.Round(0), rndVote.Round()) }) t.Run("Query vote for round 1: should send the decided vote for the round 1", func(t *testing.T) { rndVote := td.consP.HandleQueryVote(height, 1) assert.Equal(t, vote.VoteTypeCPDecided, rndVote.Type()) assert.Equal(t, height, rndVote.Height()) assert.Equal(t, types.Round(1), rndVote.Round()) }) t.Run("Query vote for round 2: should send the prepare vote for the round 2", func(t *testing.T) { rndVote := td.consP.HandleQueryVote(height, 2) assert.Equal(t, vote.VoteTypePrepare, rndVote.Type()) assert.Equal(t, height, rndVote.Height()) assert.Equal(t, types.Round(2), rndVote.Round()) }) t.Run("Query vote for round 3: should not send a vote for the next round", func(t *testing.T) { rndVote := td.consP.HandleQueryVote(height, 3) assert.Nil(t, rndVote) }) t.Run("Query vote for height 2: should not send a vote for the next height", func(t *testing.T) { rndVote := td.consP.HandleQueryVote(height+1, 0) assert.Nil(t, rndVote) }) } func TestHandleQueryProposal(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) // Round 1 td.enterNextRound(td.consX) td.enterNextRound(td.consY) // consY is the proposer prop0 := td.consY.HandleQueryProposal(1, 0) assert.Nil(t, prop0, "proposer should not send a proposal for the previous round") prop1 := td.consX.HandleQueryProposal(1, 1) assert.Nil(t, prop1, "non-proposer should not send a proposal") prop2 := td.consY.HandleQueryProposal(1, 1) assert.NotNil(t, prop2, "proposer should send a proposal") td.consX.cpDecided = 0 td.consX.SetProposal(td.consY.Proposal()) prop3 := td.consX.HandleQueryProposal(1, 1) assert.NotNil(t, prop3, "non-proposer should send a proposal on decided proposal") prop4 := td.consX.HandleQueryProposal(2, 0) assert.Nil(t, prop4, "should not have a proposal for the next height") } func TestSetProposalFromPreviousRound(t *testing.T) { td := setup(t) p := td.makeProposal(t, 1, 0) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) // It should ignore proposal for previous rounds td.consP.SetProposal(p) assert.Nil(t, td.consP.Proposal()) td.checkHeightRound(t, td.consP, 1, 1) } func TestSetProposalFromPreviousHeight(t *testing.T) { td := setup(t) p := td.makeProposal(t, 1, 0) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) td.consP.SetProposal(p) assert.Nil(t, td.consP.Proposal()) td.checkHeightRound(t, td.consP, 2, 0) } func TestDuplicateProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) height := types.Height(4) round := types.Round(0) prop1 := td.makeProposal(t, height, round) prop2 := td.makeProposal(t, height, round, td.RandAccAddress()) assert.NotEqual(t, prop1.Hash(), prop2.Hash()) td.consX.SetProposal(prop1) td.consX.SetProposal(prop2) assert.Equal(t, prop1.Hash(), td.consX.Proposal().Hash()) } func TestNonActiveValidator(t *testing.T) { td := setup(t) valKey := td.RandValKey() pipe := pipeline.New[message.Message](t.Context()) consInt := NewConsensus(t.Context(), testConfig(), state.MockingState(td.TestSuite), valKey, valKey.Address(), pipe, NewConcreteMediator()) nonActiveCons := consInt.(*consensus) t.Run("non-active instances should be in new-height state", func(t *testing.T) { nonActiveCons.MoveToNewHeight() td.newHeightTimeout(nonActiveCons) td.checkHeightRound(t, nonActiveCons, 1, 0) // Double entry nonActiveCons.MoveToNewHeight() td.newHeightTimeout(nonActiveCons) td.checkHeightRound(t, nonActiveCons, 1, 0) assert.False(t, nonActiveCons.IsActive()) assert.Equal(t, "new-height", nonActiveCons.currentState.name()) }) t.Run("non-active instances should ignore proposals", func(t *testing.T) { p := td.makeProposal(t, 1, 0) nonActiveCons.SetProposal(p) assert.Nil(t, nonActiveCons.Proposal()) }) t.Run("non-active instances should ignore votes", func(t *testing.T) { v := td.addPrepareVote(nonActiveCons, td.RandHash(), 1, 0, tIndexX) assert.False(t, nonActiveCons.HasVote(v.Hash())) }) t.Run("non-active instances should move to new height", func(t *testing.T) { b1, cert1 := td.commitBlockForAllStates(t) nonActiveCons.MoveToNewHeight() td.checkHeightRound(t, nonActiveCons, 1, 0) require.NoError(t, nonActiveCons.bcState.CommitBlock(b1, cert1)) nonActiveCons.MoveToNewHeight() td.newHeightTimeout(nonActiveCons) td.checkHeightRound(t, nonActiveCons, 2, 0) }) } func TestVoteWithBigRound(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) v := td.addPrepareVote(td.consX, td.RandHash(), 1, types.Round(util.MaxInt16), tIndexB) assert.True(t, td.consX.HasVote(v.Hash())) } func TestProposalWithBigRound(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) p := td.makeProposal(t, 1, types.Round(util.MaxInt16)) td.consP.SetProposal(p) assert.Nil(t, td.consP.Proposal()) } func TestInvalidProposal(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) prop := td.makeProposal(t, 1, 0) prop.SetSignature(nil) // Make proposal invalid td.consP.SetProposal(prop) assert.Nil(t, td.consP.Proposal()) } func TestCases(t *testing.T) { tests := []struct { seed int64 round types.Round description string }{ {1697898884837384019, 2, "1/3+ cp:PRE-VOTE in Prepare step"}, {1734526933123806220, 1, "1/3+ cp:PRE-VOTE in Precommit step"}, {1734526832618973590, 1, "Conflicting cp:PRE-VOTE in cp_round=0"}, {1734527064850322674, 2, "Conflicting cp:PRE-VOTE in cp_round=1"}, {1734526579569939721, 1, "consP & consB: Change Proposer, consX & consY: Commit (2 block announces)"}, } for no, tt := range tests { td := setupWithSeed(t, tt.seed) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) td.enterNewHeight(td.consB) td.enterNewHeight(td.consP) cert, err := checkConsensus(td, 2, nil) require.NoError(t, err, "test %v failed: %s", no+1, err) require.Equal(t, tt.round, cert.Round(), "test %v failed. round not matched (expected %d, got %d)", no+1, tt.round, cert.Round()) } } func TestFaulty(t *testing.T) { for i := 0; i < 10; i++ { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) td.enterNewHeight(td.consB) td.enterNewHeight(td.consP) _, err := checkConsensus(td, 2, nil) require.NoError(t, err) } } // We have four nodes: X, Y, B, and P, which: // - B is a Byzantine node // - X, Y, and P are honest nodes // - However, P is partitioned and perceives the network through B. // // At height H, B acts maliciously by double proposing: // sending one proposal to X and Y, and another proposal to P. // // Once the partition is healed, honest nodes should either reach consensus // on the first proposal or change the proposer. // This is due to the randomness of the binary agreement. func TestByzantine(t *testing.T) { td := setup(t) for i := 0; i < 6; i++ { td.commitBlockForAllStates(t) } height := types.Height(7) round := types.Round(0) prop1 := td.makeProposal(t, height, round) // ================================= // X, Y votes td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) td.consX.SetProposal(prop1) td.consY.SetProposal(prop1) voteX := td.shouldPublishVote(t, td.consX, vote.VoteTypePrepare, prop1.Block().Hash()) voteY := td.shouldPublishVote(t, td.consY, vote.VoteTypePrepare, prop1.Block().Hash()) // Byzantine node doesn't broadcast the prepare vote // X and Y request to change proposer td.changeProposerTimeout(td.consX) td.changeProposerTimeout(td.consY) td.shouldPublishVote(t, td.consX, vote.VoteTypeCPPreVote, hash.UndefHash) td.shouldPublishVote(t, td.consY, vote.VoteTypeCPPreVote, hash.UndefHash) // X and Y are unable to progress // ================================= // B votes td.enterNewHeight(td.consB) td.consB.SetProposal(prop1) td.consB.AddVote(voteX) td.consB.AddVote(voteY) td.shouldPublishVote(t, td.consB, vote.VoteTypePrepare, prop1.Block().Hash()) td.shouldPublishVote(t, td.consB, vote.VoteTypePrecommit, prop1.Block().Hash()) td.changeProposerTimeout(td.consB) // B requests to NOT change the proposer byzVote1 := td.shouldPublishVote(t, td.consB, vote.VoteTypeCPPreVote, prop1.Block().Hash()) // ================================= // P votes // Byzantine node create the second proposal and send it to the partitioned node P prop2 := td.makeProposal(t, height, round, td.RandAccAddress()) require.NotEqual(t, prop1.Block().Hash(), prop2.Block().Hash()) require.Equal(t, td.consB.valKey.Address(), prop1.Block().Header().ProposerAddress()) require.Equal(t, td.consB.valKey.Address(), prop2.Block().Header().ProposerAddress()) td.enterNewHeight(td.consP) // P receives the Seconds proposal td.consP.SetProposal(prop2) td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop2.Block().Hash()) byzVote2 := td.addPrepareVote(td.consP, prop2.Block().Hash(), height, round, tIndexB) // Request to change proposer td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) // P is unable to progress // ================================= td.checkHeightRound(t, td.consX, height, round) td.checkHeightRound(t, td.consY, height, round) td.checkHeightRound(t, td.consP, height, round) // Let's make Byzantine node happy by removing his votes from the log for j := len(td.consMessages) - 1; j >= 0; j-- { if td.consMessages[j].sender == td.consB.valKey.Address() { td.consMessages = slices.Delete(td.consMessages, j, j+1) } } // ================================= // Now, Partition heals fmt.Println("== Partition heals") cert, err := checkConsensus(td, height, []*vote.Vote{byzVote1, byzVote2}) require.NoError(t, err) require.Equal(t, height, cert.Height()) require.Contains(t, cert.Absentees(), int32(tIndexB)) } func checkConsensus(td *testData, height types.Height, byzVotes []*vote.Vote) ( *certificate.Certificate, error, ) { instances := []*consensus{td.consX, td.consY, td.consB, td.consP} if len(byzVotes) > 0 { for _, v := range byzVotes { td.consB.broadcastVote(v) } // remove byzantine node (Byzantine node goes offline) instances = []*consensus{td.consX, td.consY, td.consP} } // 70% chance for the first block to be lost changeProposerChance := 70 blockAnnounces := map[crypto.Address]*message.BlockAnnounceMessage{} for len(td.consMessages) > 0 { rndIndex := td.RandIntMax(len(td.consMessages)) rndMsg := td.consMessages[rndIndex] td.consMessages = slices.Delete(td.consMessages, rndIndex, rndIndex+1) switch rndMsg.message.Type() { case message.TypeVote: m := rndMsg.message.(*message.VoteMessage) if m.Vote.Height() == height { for _, cons := range instances { cons.AddVote(m.Vote) } } case message.TypeProposal: m := rndMsg.message.(*message.ProposalMessage) if m.Proposal.Height() == height { for _, cons := range instances { cons.SetProposal(m.Proposal) } } case message.TypeQueryProposal: m := rndMsg.message.(*message.QueryProposalMessage) if m.Height == height { for _, cons := range instances { p := cons.Proposal() if p != nil { td.consMessages = append(td.consMessages, consMessage{ sender: cons.valKey.Address(), message: message.NewProposalMessage(p), }) } } } case message.TypeBlockAnnounce: m := rndMsg.message.(*message.BlockAnnounceMessage) blockAnnounces[rndMsg.sender] = m case message.TypeHello, message.TypeHelloAck, message.TypeTransaction, message.TypeQueryVote, message.TypeBlocksRequest, message.TypeBlocksResponse: // } for _, cons := range instances { rnd := td.RandIntMax(100) if rnd < changeProposerChance || len(td.consMessages) == 0 { td.changeProposerTimeout(cons) } } changeProposerChance -= 5 } // Check if more than 1/3 of nodes has committed the same block if len(blockAnnounces) >= 2 { var firstAnnounce *message.BlockAnnounceMessage for _, msg := range blockAnnounces { if firstAnnounce == nil { firstAnnounce = msg } else if msg.Block.Hash() != firstAnnounce.Block.Hash() { return nil, fmt.Errorf("consensus violated, seed %v", td.TestSuite.Seed) } } // everything is ok return firstAnnounce.Certificate, nil } return nil, fmt.Errorf("unable to reach consensus, seed %v", td.TestSuite.Seed) } ================================================ FILE: consensus/cp.go ================================================ package consensus import ( "fmt" "slices" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type changeProposer struct { *consensus } func (*changeProposer) onSetProposal(_ *proposal.Proposal) { // Ignore proposal } func (cp *changeProposer) onTimeout(t *ticker) { if t.Target == tickerTargetQueryVote { cp.queryVote() cp.scheduleTimeout(t.Duration*2, cp.height, cp.round, tickerTargetQueryVote) } } func (*changeProposer) checkCPValue(vote *vote.Vote, allowedValues ...vote.CPValue) error { if slices.Contains(allowedValues, vote.CPValue()) { return nil } return InvalidJustificationError{ JustType: vote.CPJust().Type(), Reason: fmt.Sprintf("invalid value: %v", vote.CPValue()), } } func (cp *changeProposer) checkJustInitNo(just vote.Just, blockHash hash.Hash) error { j, ok := just.(*vote.JustInitNo) if !ok { return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid just data", } } err := j.QCert.ValidatePrepare(cp.validators, blockHash) if err != nil { return InvalidJustificationError{ JustType: j.Type(), Reason: err.Error(), } } return nil } func (*changeProposer) checkJustInitYes(just vote.Just) error { _, ok := just.(*vote.JustInitYes) if !ok { return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid just data", } } return nil } func (cp *changeProposer) checkJustPreVoteHard(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustPreVoteHard) if !ok { return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid just data", } } err := j.QCert.ValidateCPPreVote(cp.validators, blockHash, cpRound-1, byte(cpValue)) if err != nil { return InvalidJustificationError{ JustType: just.Type(), Reason: err.Error(), } } return nil } func (cp *changeProposer) checkJustPreVoteSoft(just vote.Just, blockHash hash.Hash, cpRound int16, ) error { j, ok := just.(*vote.JustPreVoteSoft) if !ok { return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid just data", } } err := j.QCert.ValidateCPMainVote(cp.validators, blockHash, cpRound-1, byte(vote.CPValueAbstain)) if err != nil { return InvalidJustificationError{ JustType: just.Type(), Reason: err.Error(), } } return nil } func (cp *changeProposer) checkJustMainVoteNoConflict(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustMainVoteNoConflict) if !ok { return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid just data", } } err := j.QCert.ValidateCPPreVote(cp.validators, blockHash, cpRound, byte(cpValue)) if err != nil { return InvalidJustificationError{ JustType: j.Type(), Reason: err.Error(), } } return nil } //nolint:exhaustive // refactor me; check just by just_type, not vote_type func (cp *changeProposer) checkJustMainVoteConflict(just vote.Just, blockHash hash.Hash, cpRound int16, ) error { j, ok := just.(*vote.JustMainVoteConflict) if !ok { return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid just data", } } if cpRound == 0 { err := cp.checkJustInitNo(j.JustNo, blockHash) if err != nil { return err } err = cp.checkJustInitYes(j.JustYes) if err != nil { return err } return nil } // Just0 can be for Zero or Abstain values. switch j.JustNo.Type() { case vote.JustTypePreVoteSoft: err := cp.checkJustPreVoteSoft(j.JustNo, blockHash, cpRound) if err != nil { return err } case vote.JustTypePreVoteHard: err := cp.checkJustPreVoteHard(j.JustNo, blockHash, cpRound, vote.CPValueNo) if err != nil { return err } default: return InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("unexpected justification: %s", j.JustNo.Type()), } } err := cp.checkJustPreVoteHard(j.JustYes, hash.UndefHash, cpRound, vote.CPValueYes) if err != nil { return err } return nil } //nolint:exhaustive // refactor me; check just by just_type, not vote_type func (cp *changeProposer) checkJustPreVote(vte *vote.Vote) error { just := vte.CPJust() if vte.CPRound() == 0 { switch just.Type() { case vote.JustTypeInitNo: err := cp.checkCPValue(vte, vote.CPValueNo) if err != nil { return err } return cp.checkJustInitNo(just, vte.BlockHash()) case vote.JustTypeInitYes: err := cp.checkCPValue(vte, vote.CPValueYes) if err != nil { return err } return cp.checkJustInitYes(just) default: return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", } } } else { switch just.Type() { case vote.JustTypePreVoteSoft: err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } return cp.checkJustPreVoteSoft(just, vte.BlockHash(), vte.CPRound()) case vote.JustTypePreVoteHard: err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } return cp.checkJustPreVoteHard(just, vte.BlockHash(), vte.CPRound(), vte.CPValue()) default: return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", } } } } //nolint:exhaustive // refactor me; check just by just_type, not vote_type func (cp *changeProposer) checkJustMainVote(vte *vote.Vote) error { just := vte.CPJust() switch just.Type() { case vote.JustTypeMainVoteNoConflict: err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } return cp.checkJustMainVoteNoConflict(just, vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypeMainVoteConflict: err := cp.checkCPValue(vte, vote.CPValueAbstain) if err != nil { return err } return cp.checkJustMainVoteConflict(just, vte.BlockHash(), vte.CPRound()) default: return InvalidJustificationError{ JustType: just.Type(), Reason: "invalid main-vote justification", } } } func (cp *changeProposer) checkJustDecide(vte *vote.Vote) error { err := cp.checkCPValue(vte, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } j, ok := vte.CPJust().(*vote.JustDecided) if !ok { return InvalidJustificationError{ JustType: j.Type(), Reason: "invalid just data", } } err = j.QCert.ValidateCPMainVote(cp.validators, vte.BlockHash(), vte.CPRound(), byte(vte.CPValue())) if err != nil { return InvalidJustificationError{ JustType: j.Type(), Reason: err.Error(), } } return nil } //nolint:exhaustive // refactor me; check just by just_type, not vote_type func (cp *changeProposer) checkJust(vte *vote.Vote) error { switch vte.Type() { case vote.VoteTypeCPPreVote: return cp.checkJustPreVote(vte) case vote.VoteTypeCPMainVote: return cp.checkJustMainVote(vte) case vote.VoteTypeCPDecided: return cp.checkJustDecide(vte) default: panic("unreachable") } } func (cp *changeProposer) cpStrongTermination(round types.Round, cpRound int16) { cpDecided := cp.log.CPDecidedVoteSet(round) if cpDecided.HasAnyVoteFor(cpRound, vote.CPValueNo) { cp.round = round cp.cpDecided = 0 roundProposal := cp.log.RoundProposal(round) if roundProposal == nil { cp.queryProposal() } cp.enterNewState(cp.prepareState) } else if cpDecided.HasAnyVoteFor(cpRound, vote.CPValueYes) { cp.round = round + 1 cp.cpDecided = 1 cp.enterNewState(cp.proposeState) } } ================================================ FILE: consensus/cp_decide.go ================================================ package consensus import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/vote" ) type cpDecideState struct { *changeProposer } func (s *cpDecideState) enter() { s.decide() s.cpStrongTermination(s.round, s.cpRound) } func (s *cpDecideState) decide() { cpMainVotes := s.log.CPMainVoteVoteSet(s.round) if cpMainVotes.HasTwoThirdOfTotalPower(s.cpRound) { if cpMainVotes.HasQuorumVotesFor(s.cpRound, vote.CPValueYes) { // decided for yes, and proceeds to the next round s.logger.Info("binary agreement decided", "value", 1, "round", s.cpRound) votes := cpMainVotes.BinaryVotes(s.cpRound, vote.CPValueYes) cert := s.makeCertificate(votes) just := &vote.JustDecided{ QCert: cert, } s.signAddCPDecidedVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just) s.cpStrongTermination(s.round, s.cpRound) } else if cpMainVotes.HasQuorumVotesFor(s.cpRound, vote.CPValueNo) { // decided for no and proceeds to the next round s.logger.Info("binary agreement decided", "value", 0, "round", s.cpRound) votes := cpMainVotes.BinaryVotes(s.cpRound, vote.CPValueNo) cert := s.makeCertificate(votes) just := &vote.JustDecided{ QCert: cert, } s.signAddCPDecidedVote(*s.cpWeakValidity, s.cpRound, vote.CPValueNo, just) s.cpStrongTermination(s.round, s.cpRound) } else { // conflicting votes s.logger.Debug("conflicting main votes", "round", s.cpRound) s.cpRound++ s.enterNewState(s.cpPreVoteState) } } } func (s *cpDecideState) onAddVote(vte *vote.Vote) { if vte.Type() == vote.VoteTypeCPMainVote { s.decide() } if vte.IsCPVote() { s.cpStrongTermination(vte.Round(), vte.CPRound()) } } func (*cpDecideState) name() string { return "cp:decide" } ================================================ FILE: consensus/cp_mainvote.go ================================================ package consensus import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/vote" ) type cpMainVoteState struct { *changeProposer } func (s *cpMainVoteState) enter() { s.decide() s.cpStrongTermination(s.round, s.cpRound) } func (s *cpMainVoteState) decide() { s.checkForWeakValidity() s.detectByzantineProposal() cpPreVotes := s.log.CPPreVoteVoteSet(s.round) if cpPreVotes.HasTwoThirdOfTotalPower(s.cpRound) { if cpPreVotes.HasQuorumVotesFor(s.cpRound, vote.CPValueYes) { s.logger.Debug("cp: quorum for pre-votes", "v", "1") votes := cpPreVotes.BinaryVotes(s.cpRound, vote.CPValueYes) cert := s.makeCertificate(votes) just := &vote.JustMainVoteNoConflict{ QCert: cert, } s.signAddCPMainVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just) s.enterNewState(s.cpDecideState) } else if cpPreVotes.HasQuorumVotesFor(s.cpRound, vote.CPValueNo) { s.logger.Debug("cp: quorum for pre-votes", "v", "0") votes := cpPreVotes.BinaryVotes(s.cpRound, vote.CPValueNo) cert := s.makeCertificate(votes) just := &vote.JustMainVoteNoConflict{ QCert: cert, } s.signAddCPMainVote(*s.cpWeakValidity, s.cpRound, vote.CPValueNo, just) s.enterNewState(s.cpDecideState) } else { s.logger.Debug("cp: no-quorum for pre-votes", "v", "abstain") vote0 := cpPreVotes.GetRandomVote(s.cpRound, vote.CPValueNo) vote1 := cpPreVotes.GetRandomVote(s.cpRound, vote.CPValueYes) just := &vote.JustMainVoteConflict{ JustNo: vote0.CPJust(), JustYes: vote1.CPJust(), } s.signAddCPMainVote(*s.cpWeakValidity, s.cpRound, vote.CPValueAbstain, just) s.enterNewState(s.cpDecideState) } } } func (s *cpMainVoteState) checkForWeakValidity() { if s.cpWeakValidity == nil { preVotes := s.log.CPPreVoteVoteSet(s.round) preVotesZero := preVotes.BinaryVotes(s.cpRound, vote.CPValueNo) for _, v := range preVotesZero { bh := v.BlockHash() s.cpWeakValidity = &bh break } } } func (s *cpMainVoteState) detectByzantineProposal() { if s.cpWeakValidity != nil { roundProposal := s.log.RoundProposal(s.round) if roundProposal != nil && roundProposal.Block().Hash() != *s.cpWeakValidity { s.logger.Warn("double proposal detected", "prepared", s.cpWeakValidity, "roundProposal", roundProposal.Block().Hash()) s.log.SetRoundProposal(s.round, nil) s.queryProposal() } } } func (s *cpMainVoteState) onAddVote(vte *vote.Vote) { if vte.Type() == vote.VoteTypeCPPreVote { s.decide() } if vte.IsCPVote() { s.cpStrongTermination(vte.Round(), vte.CPRound()) } } func (*cpMainVoteState) name() string { return "cp:main-vote" } ================================================ FILE: consensus/cp_prevote.go ================================================ package consensus import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/vote" ) type cpPreVoteState struct { *changeProposer } func (s *cpPreVoteState) enter() { s.decide() } func (s *cpPreVoteState) decide() { if s.cpRound == 0 { // broadcast the initial value prepares := s.log.PrepareVoteSet(s.round) preparesQH := prepares.QuorumHash() if preparesQH != nil { s.cpWeakValidity = preparesQH cert := s.makeCertificate(prepares.BlockVotes(*preparesQH)) just := &vote.JustInitNo{ QCert: cert, } s.signAddCPPreVote(*s.cpWeakValidity, s.cpRound, 0, just) } else { just := &vote.JustInitYes{} s.signAddCPPreVote(hash.UndefHash, s.cpRound, 1, just) } s.scheduleTimeout(s.config.QueryVoteTimeout, s.height, s.round, tickerTargetQueryVote) } else { cpMainVotes := s.log.CPMainVoteVoteSet(s.round) switch { case cpMainVotes.HasAnyVoteFor(s.cpRound-1, vote.CPValueYes): s.logger.Debug("cp: one main-vote for one", "b", "1") vote1 := cpMainVotes.GetRandomVote(s.cpRound-1, vote.CPValueYes) just1 := &vote.JustPreVoteHard{ QCert: vote1.CPJust().(*vote.JustMainVoteNoConflict).QCert, } s.signAddCPPreVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just1) case cpMainVotes.HasAnyVoteFor(s.cpRound-1, vote.CPValueNo): s.logger.Debug("cp: one main-vote for zero", "b", "0") vote0 := cpMainVotes.GetRandomVote(s.cpRound-1, vote.CPValueNo) just0 := &vote.JustPreVoteHard{ QCert: vote0.CPJust().(*vote.JustMainVoteNoConflict).QCert, } s.signAddCPPreVote(*s.cpWeakValidity, s.cpRound, vote.CPValueNo, just0) case cpMainVotes.HasAllVotesFor(s.cpRound-1, vote.CPValueAbstain): s.logger.Debug("cp: all main-votes are abstain", "b", "0 (biased)") votes := cpMainVotes.BinaryVotes(s.cpRound-1, vote.CPValueAbstain) cert := s.makeCertificate(votes) just := &vote.JustPreVoteSoft{ QCert: cert, } s.signAddCPPreVote(*s.cpWeakValidity, s.cpRound, vote.CPValueNo, just) default: s.logger.Panic("protocol violated. We have combination of votes for one and zero") } } s.enterNewState(s.cpMainVoteState) } func (*cpPreVoteState) onAddVote(_ *vote.Vote) { panic("Unreachable") } func (*cpPreVoteState) name() string { return "cp:pre-vote" } ================================================ FILE: consensus/cp_test.go ================================================ package consensus import ( "fmt" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestChangeProposer(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) } func TestSetProposalAfterChangeProposer(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) p := td.makeProposal(t, 2, 0) td.consP.SetProposal(p) assert.NotNil(t, td.consP.Proposal()) } func TestChangeProposerAgreementYes(t *testing.T) { td := setup(t) height := types.Height(1) round := types.Round(0) td.enterNewHeight(td.consP) td.checkHeightRound(t, td.consP, height, round) td.changeProposerTimeout(td.consP) preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, preVote0.CPJust(), tIndexX) td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, preVote0.CPJust(), tIndexY) mainVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, hash.UndefHash) td.addCPMainVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, mainVote0.CPJust(), tIndexX) td.addCPMainVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, mainVote0.CPJust(), tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPDecided, hash.UndefHash) td.checkHeightRound(t, td.consP, height, round+1) } func TestChangeProposerAgreementNo(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 height := types.Height(2) round := types.Round(1) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) td.checkHeightRound(t, td.consP, height, round) prop := td.makeProposal(t, height, round) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) td.changeProposerTimeout(td.consP) preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, prop.Block().Hash()) td.addCPPreVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, preVote0.CPJust(), tIndexX) td.addCPPreVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, preVote0.CPJust(), tIndexY) mainVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, prop.Block().Hash()) td.addCPMainVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, mainVote0.CPJust(), tIndexX) td.addCPMainVote(td.consP, prop.Block().Hash(), height, round, vote.CPValueNo, mainVote0.CPJust(), tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPDecided, prop.Block().Hash()) td.shouldPublishQueryProposal(t, td.consP, height) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.checkHeightRound(t, td.consP, height, round) } // ConsP receives all `PRE-VOTE:no` votes before receiving a proposal or prepare votes. // It should vote `PRE-VOTES:yes` and `MAIN-VOTE:no`. func TestCrashOnTestnet(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 height := types.Height(2) round := types.Round(0) td.consP.MoveToNewHeight() blockHash := td.RandHash() vote1 := vote.NewPrepareVote(blockHash, height, round, td.consX.valKey.Address()) vote2 := vote.NewPrepareVote(blockHash, height, round, td.consY.valKey.Address()) vote3 := vote.NewPrepareVote(blockHash, height, round, td.consB.valKey.Address()) td.HelperSignVote(td.consX.valKey, vote1) td.HelperSignVote(td.consY.valKey, vote2) td.HelperSignVote(td.consB.valKey, vote3) votes := map[crypto.Address]*vote.Vote{} votes[vote1.Signer()] = vote1 votes[vote2.Signer()] = vote2 votes[vote3.Signer()] = vote3 qCert := td.consP.makeCertificate(votes) just0 := &vote.JustInitNo{QCert: qCert} td.addCPPreVote(td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexX) td.addCPPreVote(td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexY) td.addCPPreVote(td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexB) td.newHeightTimeout(td.consP) td.changeProposerTimeout(td.consP) preVote := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) mainVote := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, blockHash) assert.Equal(t, vote.CPValueYes, preVote.CPValue()) assert.Equal(t, vote.CPValueNo, mainVote.CPValue()) } func TestInvalidJustInitOne(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) just := &vote.JustInitYes{} t.Run("invalid value: no", func(t *testing.T) { cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: no", }) }) t.Run("invalid block hash", func(t *testing.T) { cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 1, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", }) }) t.Run("with main-vote justification", func(t *testing.T) { invJust := &vote.JustMainVoteNoConflict{} cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueYes, invJust, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: invJust.Type(), Reason: "invalid pre-vote justification", }) }) } func TestInvalidJustInitZero(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) just := &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: yes", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: yes", }) }) t.Run("cp-round should be zero", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", }) }) t.Run("invalid certificate", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestInvalidJustPreVoteHard(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) just := &vote.JustPreVoteHard{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: abstain", }) }) t.Run("cp-round should not be zero", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", }) }) t.Run("invalid certificate", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestInvalidJustPreVoteSoft(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) just := &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: abstain", }) }) t.Run("cp-round should not be zero", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid pre-vote justification", }) }) t.Run("invalid certificate", func(t *testing.T) { cpVote := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestInvalidJustMainVoteNoConflict(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) just := &vote.JustMainVoteNoConflict{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { v := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: abstain", }) }) t.Run("invalid certificate", func(t *testing.T) { cpVote := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestInvalidJustMainVoteConflict(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) t.Run("invalid value: no", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), }, JustYes: &vote.JustInitYes{}, } v := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: no", }) }) t.Run("invalid value: yes", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), }, JustYes: &vote.JustInitYes{}, } v := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: yes", }) }) t.Run("invalid value: unexpected justification (just0)", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), }, JustYes: &vote.JustInitYes{}, } v := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: vote.JustTypePreVoteSoft, Reason: "invalid just data", }) }) t.Run("invalid value: unexpected justification", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), }, JustYes: &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), }, } v := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "unexpected justification: JustInitNo", }) }) t.Run("invalid certificate", func(t *testing.T) { just0 := &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), } just := &vote.JustMainVoteConflict{ JustNo: just0, JustYes: &vote.JustInitYes{}, } cpVote := vote.NewCPMainVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just0.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just0.QCert.Committers()), }) }) t.Run("invalid certificate", func(t *testing.T) { just0 := &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), } just := &vote.JustMainVoteConflict{ JustNo: just0, JustYes: &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), }, } cpVote := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(cpVote) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just0.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just0.QCert.Committers()), }) }) } func TestInvalidJustDecided(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) height := types.Height(1) round := types.Round(0) just := &vote.JustDecided{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { v := vote.NewCPDecidedVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: "invalid value: abstain", }) }) t.Run("invalid certificate", func(t *testing.T) { v := vote.NewCPDecidedVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consX.changeProposer.checkJust(v) require.ErrorIs(t, err, InvalidJustificationError{ JustType: just.Type(), Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } ================================================ FILE: consensus/errors.go ================================================ package consensus import ( "fmt" "github.com/pactus-project/pactus/types/vote" ) // InvalidJustificationError is returned when the justification for a change-proposer // vote is invalid. type InvalidJustificationError struct { JustType vote.JustType Reason string } func (e InvalidJustificationError) Error() string { return fmt.Sprintf("invalid justification: %s, reason: %s", e.JustType.String(), e.Reason) } // ConfigError is returned when the config is not valid with a descriptive Reason message. type ConfigError struct { Reason string } func (e ConfigError) Error() string { return e.Reason } ================================================ FILE: consensus/height.go ================================================ package consensus import ( "time" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type newHeightState struct { *consensus } func (s *newHeightState) enter() { s.decide() } func (s *newHeightState) decide() { sateHeight := s.bcState.LastBlockHeight() validators := s.bcState.CommitteeValidators() s.log.MoveToNewHeight(validators) s.validators = validators s.height = sateHeight + 1 s.round = 0 s.active = s.bcState.IsInCommittee(s.valKey.Address()) s.logger.Info("entering new height", "height", s.height, "active", s.active) sleep := time.Until(s.bcState.LastBlockTime().Add(s.bcState.Params().BlockInterval())) s.scheduleTimeout(sleep, s.height, s.round, tickerTargetNewHeight) } func (s *newHeightState) onAddVote(_ *vote.Vote) { prepares := s.log.PrepareVoteSet(s.round) if prepares.HasQuorumHash() { // Add logic to detect when the network majority has voted for a block, // but the new height timer has not yet started. This situation can occur if the system // time is lagging behind the network time. s.logger.Warn("detected network majority voting for a block, but the new height timer has not started yet. " + "system time may be behind the network.") s.enterNewState(s.proposeState) } } func (*newHeightState) onSetProposal(_ *proposal.Proposal) { // Ignore proposal } func (s *newHeightState) onTimeout(t *ticker) { if t.Target == tickerTargetNewHeight { if s.active { s.enterNewState(s.proposeState) } } } func (*newHeightState) name() string { return "new-height" } ================================================ FILE: consensus/height_test.go ================================================ package consensus import ( "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" "github.com/stretchr/testify/assert" ) func TestNewHeightTimeout(t *testing.T) { td := setup(t) td.enterNewHeight(td.consY) td.commitBlockForAllStates(t) consState := &newHeightState{td.consY} consState.enter() // Invalid target consState.onTimeout(&ticker{Height: 2, Target: -1}) td.checkHeightRound(t, td.consY, 2, 0) consState.onTimeout(&ticker{Height: 2, Target: tickerTargetNewHeight}) td.checkHeightRound(t, td.consY, 2, 0) td.shouldPublishProposal(t, td.consY, 2, 0) } func TestNewHeightDoubleEntry(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.consX.MoveToNewHeight() td.newHeightTimeout(td.consX) // double entry and timeout td.consX.MoveToNewHeight() td.checkHeightRound(t, td.consX, 2, 0) assert.True(t, td.consX.active) assert.NotEqual(t, "new-height", td.consX.currentState.name()) } func TestNewHeightTimeBehindNetwork(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.consP.MoveToNewHeight() height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) td.consP.SetProposal(prop) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop.Block().Hash()) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } ================================================ FILE: consensus/interface.go ================================================ package consensus import ( "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type Reader interface { ConsensusKey() *bls.PublicKey AllVotes() []*vote.Vote HandleQueryVote(height types.Height, round types.Round) *vote.Vote HandleQueryProposal(height types.Height, round types.Round) *proposal.Proposal Proposal() *proposal.Proposal HasVote(h hash.Hash) bool HeightRound() (types.Height, types.Round) IsActive() bool IsProposer() bool } type Consensus interface { Reader MoveToNewHeight() AddVote(vote *vote.Vote) SetProposal(prop *proposal.Proposal) IsDeprecated() bool } ================================================ FILE: consensus/log/log.go ================================================ package log import ( "github.com/pactus-project/pactus/consensus/voteset" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type Log struct { validators map[crypto.Address]*validator.Validator totalPower int64 roundMessages map[types.Round]*Messages } func NewLog() *Log { return &Log{ roundMessages: make(map[types.Round]*Messages, 0), } } func (log *Log) RoundMessages(round types.Round) *Messages { return log.mustGetRoundMessages(round) } func (log *Log) HasVote(h hash.Hash) bool { for _, m := range log.roundMessages { if m.HasVote(h) { return true } } return false } func (log *Log) mustGetRoundMessages(round types.Round) *Messages { msgs, ok := log.roundMessages[round] if !ok { msgs = &Messages{ prepareVotes: voteset.NewPrepareVoteSet(round, log.totalPower, log.validators), precommitVotes: voteset.NewPrecommitVoteSet(round, log.totalPower, log.validators), cpPreVotes: voteset.NewCPPreVoteVoteSet(round, log.totalPower, log.validators), cpMainVotes: voteset.NewCPMainVoteVoteSet(round, log.totalPower, log.validators), cpDecidedVotes: voteset.NewCPDecidedVoteSet(round, log.totalPower, log.validators), } log.roundMessages[round] = msgs } return msgs } func (log *Log) AddVote(v *vote.Vote) (bool, error) { msgs := log.mustGetRoundMessages(v.Round()) return msgs.addVote(v) } func (log *Log) PrepareVoteSet(round types.Round) *voteset.BlockVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.prepareVotes } func (log *Log) PrecommitVoteSet(round types.Round) *voteset.BlockVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.precommitVotes } func (log *Log) CPPreVoteVoteSet(round types.Round) *voteset.BinaryVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.cpPreVotes } func (log *Log) CPMainVoteVoteSet(round types.Round) *voteset.BinaryVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.cpMainVotes } func (log *Log) CPDecidedVoteSet(round types.Round) *voteset.BinaryVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.cpDecidedVotes } func (log *Log) HasRoundProposal(round types.Round) bool { return log.RoundProposal(round) != nil } func (log *Log) RoundProposal(round types.Round) *proposal.Proposal { m := log.RoundMessages(round) if m == nil { return nil } return m.proposal } func (log *Log) SetRoundProposal(round types.Round, prop *proposal.Proposal) { msgs := log.mustGetRoundMessages(round) msgs.proposal = prop } func (log *Log) MoveToNewHeight(validators []*validator.Validator) { log.roundMessages = make(map[types.Round]*Messages) log.validators = make(map[crypto.Address]*validator.Validator) log.totalPower = 0 for _, val := range validators { log.totalPower += val.Power() log.validators[val.Address()] = val } } func (log *Log) CanVote(addr crypto.Address) bool { for _, val := range log.validators { if val.Address() == addr { return true } } return false } ================================================ FILE: consensus/log/log_test.go ================================================ package log import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMustGetRound(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, _ := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) assert.NotNil(t, log.RoundMessages(ts.RandRound())) } func TestAddValidVote(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, valKeys := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) height := ts.RandHeight() round := ts.RandRound() prepares := log.PrepareVoteSet(round) precommits := log.PrecommitVoteSet(round) preVotes := log.CPPreVoteVoteSet(round) mainVotes := log.CPMainVoteVoteSet(round) vote1 := vote.NewPrepareVote(ts.RandHash(), height, round, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(ts.RandHash(), height, round, valKeys[0].Address()) vote3 := vote.NewCPPreVote(ts.RandHash(), height, round, 0, vote.CPValueYes, &vote.JustInitYes{}, valKeys[0].Address()) vote4 := vote.NewCPMainVote(ts.RandHash(), height, round, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) for _, v := range []*vote.Vote{vote1, vote2, vote3, vote4} { ts.HelperSignVote(valKeys[0], v) added, err := log.AddVote(v) require.NoError(t, err) assert.True(t, added) } assert.True(t, log.HasVote(vote1.Hash())) assert.True(t, log.HasVote(vote2.Hash())) assert.True(t, log.HasVote(vote3.Hash())) assert.True(t, log.HasVote(vote4.Hash())) assert.False(t, log.HasVote(ts.RandHash())) assert.Contains(t, prepares.AllVotes(), vote1) assert.Contains(t, precommits.AllVotes(), vote2) assert.Contains(t, preVotes.AllVotes(), vote3) assert.Contains(t, mainVotes.AllVotes(), vote4) } func TestAddInvalidVoteType(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, _ := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) data, _ := hex.DecodeString("A7010F0218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") invVote := new(vote.Vote) err := invVote.UnmarshalCBOR(data) require.NoError(t, err) added, err := log.AddVote(invVote) require.ErrorContains(t, err, "unexpected vote type: 15") assert.False(t, added) assert.False(t, log.HasVote(invVote.Hash())) } func TestSetRoundProposal(t *testing.T) { ts := testsuite.NewTestSuite(t) height := ts.RandHeight() round := ts.RandRound() cmt, _ := ts.GenerateTestCommittee(7) prop := ts.GenerateTestProposal(height, round) log := NewLog() log.MoveToNewHeight(cmt.Validators()) log.SetRoundProposal(round, prop) assert.False(t, log.HasRoundProposal(round+1)) assert.True(t, log.HasRoundProposal(round)) assert.Nil(t, log.RoundProposal(round+1)) assert.Equal(t, prop.Hash(), log.RoundProposal(round).Hash()) } func TestCanVote(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, valKeys := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) addr := ts.RandAccAddress() assert.True(t, log.CanVote(valKeys[0].Address())) assert.False(t, log.CanVote(addr)) } ================================================ FILE: consensus/log/messages.go ================================================ package log import ( "fmt" "github.com/pactus-project/pactus/consensus/voteset" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type Messages struct { prepareVotes *voteset.BlockVoteSet // Prepare votes precommitVotes *voteset.BlockVoteSet // Precommit votes cpPreVotes *voteset.BinaryVoteSet // Change proposer Pre-votes cpMainVotes *voteset.BinaryVoteSet // Change proposer Main-votes cpDecidedVotes *voteset.BinaryVoteSet // Change proposer Decided-votes proposal *proposal.Proposal } func (m *Messages) addVote(vte *vote.Vote) (bool, error) { switch vte.Type() { case vote.VoteTypePrepare: return m.prepareVotes.AddVote(vte) case vote.VoteTypePrecommit: return m.precommitVotes.AddVote(vte) case vote.VoteTypeCPPreVote: return m.cpPreVotes.AddVote(vte) case vote.VoteTypeCPMainVote: return m.cpMainVotes.AddVote(vte) case vote.VoteTypeCPDecided: return m.cpDecidedVotes.AddVote(vte) } return false, fmt.Errorf("unexpected vote type: %v", vte.Type()) } func (m *Messages) HasVote(h hash.Hash) bool { votes := m.AllVotes() for _, v := range votes { if v.Hash() == h { return true } } return false } func (m *Messages) AllVotes() []*vote.Vote { prepare := m.prepareVotes.AllVotes() precommit := m.precommitVotes.AllVotes() cpPre := m.cpPreVotes.AllVotes() cpMain := m.cpMainVotes.AllVotes() cpDecided := m.cpDecidedVotes.AllVotes() votes := make([]*vote.Vote, 0, len(prepare)+len(precommit)+len(cpPre)+len(cpMain)+len(cpDecided)) votes = append(votes, prepare...) votes = append(votes, precommit...) votes = append(votes, cpPre...) votes = append(votes, cpMain...) votes = append(votes, cpDecided...) return votes } ================================================ FILE: consensus/manager/interface.go ================================================ package manager import ( "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type Reader interface { ConsensusKey() *bls.PublicKey AllVotes() []*vote.Vote HandleQueryVote(height types.Height, round types.Round) *vote.Vote HandleQueryProposal(height types.Height, round types.Round) *proposal.Proposal Proposal() *proposal.Proposal HasVote(h hash.Hash) bool HeightRound() (types.Height, types.Round) IsActive() bool IsProposer() bool } type Consensus interface { Reader MoveToNewHeight() AddVote(vote *vote.Vote) SetProposal(prop *proposal.Proposal) IsDeprecated() bool } type ManagerReader interface { Instances() []Reader HandleQueryVote(height types.Height, round types.Round) *vote.Vote HandleQueryProposal(height types.Height, round types.Round) *proposal.Proposal Proposal() *proposal.Proposal HeightRound() (types.Height, types.Round) HasActiveInstance() bool } type Manager interface { ManagerReader MoveToNewHeight() AddVote(vote *vote.Vote) SetProposal(prop *proposal.Proposal) IsDeprecated() bool } ================================================ FILE: consensus/manager/manager.go ================================================ package manager import ( "context" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/consensus" "github.com/pactus-project/pactus/consensusv2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" "golang.org/x/exp/slices" ) type manager struct { instances []Consensus // Caching future votes and proposals due to potential server time misalignments. // Votes and proposals for upcoming blocks may be received before // the current block's consensus is complete. upcomingVotes []*vote.Vote // Map to cache votes for future block heights upcomingProposals []*proposal.Proposal // Map to cache proposals for future block heights state state.Facade } // NewManagerV1 creates a new manager instance that manages a set of consensus instances, // each associated with a validator key and a reward address. // It is not thread-safe. func NewManagerV1( ctx context.Context, conf *consensus.Config, state state.Facade, valKeys []*bls.ValidatorKey, rewardAddrs []crypto.Address, broadcastPipe pipeline.Pipeline[message.Message], ) Manager { mgr := &manager{ instances: make([]Consensus, len(valKeys)), upcomingVotes: make([]*vote.Vote, 0), upcomingProposals: make([]*proposal.Proposal, 0), state: state, } mediatorConcrete := consensus.NewConcreteMediator() for i, key := range valKeys { cons := consensus.NewConsensus(ctx, conf, state, key, rewardAddrs[i], broadcastPipe, mediatorConcrete) mgr.instances[i] = cons } return mgr } func NewManagerV2( ctx context.Context, conf *consensusv2.Config, state state.Facade, valKeys []*bls.ValidatorKey, rewardAddrs []crypto.Address, broadcastPipe pipeline.Pipeline[message.Message], ) Manager { mgr := &manager{ instances: make([]Consensus, len(valKeys)), upcomingVotes: make([]*vote.Vote, 0), upcomingProposals: make([]*proposal.Proposal, 0), state: state, } mediatorConcrete := consensus.NewConcreteMediator() for i, key := range valKeys { cons := consensusv2.NewConsensus(ctx, conf, state, key, rewardAddrs[i], broadcastPipe, mediatorConcrete) mgr.instances[i] = cons } return mgr } // Instances return all consensus instances that are read-only and // can be safely accessed without modifying their state. func (mgr *manager) Instances() []Reader { readers := make([]Reader, len(mgr.instances)) for i, cons := range mgr.instances { readers[i] = cons } return readers } // Proposal returns the current proposal for the active round from a random consensus instance. func (mgr *manager) Proposal() *proposal.Proposal { cons := mgr.getBestInstance() return cons.Proposal() } // HandleQueryProposal returns the proposal for a specific round from a random consensus instance. func (mgr *manager) HandleQueryProposal(height types.Height, round types.Round) *proposal.Proposal { cons := mgr.getBestInstance() return cons.HandleQueryProposal(height, round) } // HandleQueryVote returns a random vote from a random consensus instance. func (mgr *manager) HandleQueryVote(height types.Height, round types.Round) *vote.Vote { cons := mgr.getBestInstance() return cons.HandleQueryVote(height, round) } // HeightRound retrieves the current height and round from a random consensus instance. func (mgr *manager) HeightRound() (types.Height, types.Round) { cons := mgr.getBestInstance() return cons.HeightRound() } // HasActiveInstance checks if any of the consensus instances are currently active. func (mgr *manager) HasActiveInstance() bool { for _, cons := range mgr.instances { if cons.IsActive() { return true } } return false } // MoveToNewHeight moves all consensus instances to a new height. func (mgr *manager) MoveToNewHeight() { for _, cons := range mgr.instances { cons.MoveToNewHeight() } cons := mgr.getBestInstance() curHeight, _ := cons.HeightRound() for index := len(mgr.upcomingProposals) - 1; index >= 0; index-- { prop := mgr.upcomingProposals[index] switch { case prop.Height() < curHeight: // Ignore old proposals case prop.Height() > curHeight: // Keep this future proposal continue case prop.Height() == curHeight: // Process this current proposal for _, cons := range mgr.instances { cons.SetProposal(prop) } } mgr.upcomingProposals = slices.Delete(mgr.upcomingProposals, index, index+1) } for index := len(mgr.upcomingVotes) - 1; index >= 0; index-- { vote := mgr.upcomingVotes[index] switch { case vote.Height() < curHeight: // Ignore old votes case vote.Height() > curHeight: // Keep future vote continue case vote.Height() == curHeight: // Process current vote for _, cons := range mgr.instances { cons.AddVote(vote) } } mgr.upcomingVotes = slices.Delete(mgr.upcomingVotes, index, index+1) } } // AddVote adds a vote to all consensus instances. func (mgr *manager) AddVote(vote *vote.Vote) { cons := mgr.getBestInstance() curHeight, _ := cons.HeightRound() switch { case vote.Height() < curHeight: _ = mgr.state.UpdateLastCertificate(vote) case vote.Height() > curHeight: mgr.upcomingVotes = append(mgr.upcomingVotes, vote) case vote.Height() == curHeight: for _, cons := range mgr.instances { cons.AddVote(vote) } } } // SetProposal sets the proposal for all consensus instances. func (mgr *manager) SetProposal(prop *proposal.Proposal) { cons := mgr.getBestInstance() curHeight, _ := cons.HeightRound() switch { case prop.Height() < curHeight: // discard old proposal case prop.Height() > curHeight: mgr.upcomingProposals = append(mgr.upcomingProposals, prop) case prop.Height() == curHeight: for _, cons := range mgr.instances { cons.SetProposal(prop) } } } // getBestInstance iterates through all consensus instances and returns the instance // that is currently active, if there is one. // If there are no active instances, it returns the first instance. // // Note that all active instances are assumed to be in the same state, and all inactive // instances are assumed to be in the same state as well. func (mgr *manager) getBestInstance() Consensus { for _, cons := range mgr.instances { if cons.IsActive() { return cons } } return mgr.instances[0] } // IsDeprecated checks if any of the consensus instances are deprecated. func (mgr *manager) IsDeprecated() bool { return mgr.instances[0].IsDeprecated() } ================================================ FILE: consensus/manager/manager_test.go ================================================ package manager import ( "testing" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/consensusv2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestManager(t *testing.T) { ts := testsuite.NewTestSuite(t) state := state.MockingState(ts) state.TestCommittee.Validators() rewardAddrs := []crypto.Address{ts.RandAccAddress(), ts.RandAccAddress()} valKeys := []*bls.ValidatorKey{state.TestValKeys[0], ts.RandValKey()} pipe := pipeline.New[message.Message](t.Context()) randomHeight := ts.RandHeight() rndBlk, rndCert := ts.GenerateTestBlock(randomHeight) state.TestStore.SaveBlock(rndBlk, rndCert) conf := consensusv2.DefaultConfig() mgrInt := NewManagerV2(t.Context(), conf, state, valKeys, rewardAddrs, pipe) mgr := mgrInt.(*manager) consA := mgr.instances[0] // active consB := mgr.instances[1] // inactive t.Run("Check if keys are assigned properly", func(t *testing.T) { assert.Equal(t, consA.ConsensusKey(), valKeys[0].PublicKey()) assert.Equal(t, consB.ConsensusKey(), valKeys[1].PublicKey()) }) t.Run("Check if all instances move to new height", func(t *testing.T) { mgr.MoveToNewHeight() stateHeight := mgr.state.LastBlockHeight() consHeight, consRound := mgr.HeightRound() assert.True(t, mgr.HasActiveInstance()) assert.Equal(t, stateHeight+1, consHeight) assert.Zero(t, consRound) }) t.Run("Testing add vote", func(t *testing.T) { consHeight, _ := mgr.HeightRound() vote := vote.NewPrecommitVote(ts.RandHash(), consHeight, 0, valKeys[0].Address()) ts.HelperSignVote(valKeys[0], vote) mgr.AddVote(vote) assert.True(t, consA.HasVote(vote.Hash())) assert.False(t, consB.HasVote(vote.Hash())) }) t.Run("Testing set proposal", func(t *testing.T) { consHeight, _ := mgr.HeightRound() blk, _ := state.ProposeBlock(valKeys[0], valKeys[0].Address()) prop := proposal.NewProposal(consHeight, 0, blk) ts.HelperSignProposal(valKeys[0], prop) mgr.SetProposal(prop) assert.Equal(t, prop, consA.Proposal()) assert.Nil(t, consB.Proposal()) }) t.Run("Check discarding old votes", func(t *testing.T) { consHeight, _ := mgr.HeightRound() v := vote.NewPrepareVote(ts.RandHash(), consHeight-1, 0, state.TestValKeys[2].Address()) ts.HelperSignVote(state.TestValKeys[2], v) mgr.AddVote(v) assert.Empty(t, mgr.upcomingVotes) }) t.Run("Check discarding old proposals", func(t *testing.T) { consHeight, _ := mgr.HeightRound() blk, _ := state.ProposeBlock(valKeys[0], valKeys[0].Address()) prop := proposal.NewProposal(consHeight-1, 1, blk) ts.HelperSignProposal(valKeys[0], prop) mgr.SetProposal(prop) assert.Empty(t, mgr.upcomingProposals) }) t.Run("Processing upcoming votes", func(t *testing.T) { consHeight, _ := mgr.HeightRound() vote1 := vote.NewPrepareVote(ts.RandHash(), consHeight+1, 0, valKeys[0].Address()) vote2 := vote.NewPrepareVote(ts.RandHash(), consHeight+2, 0, valKeys[0].Address()) vote3 := vote.NewPrepareVote(ts.RandHash(), consHeight+3, 0, valKeys[0].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[0], vote2) ts.HelperSignVote(valKeys[0], vote3) mgr.AddVote(vote1) mgr.AddVote(vote2) mgr.AddVote(vote3) assert.Len(t, mgr.upcomingVotes, 3) blk1, cert1 := ts.GenerateTestBlock(consHeight) err := state.CommitBlock(blk1, cert1) require.NoError(t, err) blk2, cert2 := ts.GenerateTestBlock(consHeight + 1) err = state.CommitBlock(blk2, cert2) require.NoError(t, err) mgr.MoveToNewHeight() assert.Len(t, mgr.upcomingVotes, 1) }) t.Run("Processing upcoming proposal", func(t *testing.T) { consHeight, _ := mgr.HeightRound() prop1 := ts.GenerateTestProposal(consHeight+1, 0) prop2 := ts.GenerateTestProposal(consHeight+2, 0) prop3 := ts.GenerateTestProposal(consHeight+3, 0) mgr.SetProposal(prop1) mgr.SetProposal(prop2) mgr.SetProposal(prop3) assert.Len(t, mgr.upcomingProposals, 3) blk1, cert1 := ts.GenerateTestBlock(consHeight) err := state.CommitBlock(blk1, cert1) require.NoError(t, err) blk2, cert2 := ts.GenerateTestBlock(consHeight + 1) err = state.CommitBlock(blk2, cert2) require.NoError(t, err) mgr.MoveToNewHeight() assert.Len(t, mgr.upcomingProposals, 1) }) } func TestMediator(t *testing.T) { ts := testsuite.NewTestSuite(t) state := state.MockingState(ts) cmt, valKeys := ts.GenerateTestCommittee(4) state.TestCommittee = cmt state.TestParams.BlockIntervalInSecond = 1 rewardAddrs := []crypto.Address{ ts.RandAccAddress(), ts.RandAccAddress(), ts.RandAccAddress(), ts.RandAccAddress(), } stateHeight := ts.RandHeight() blk, cert := ts.GenerateTestBlock(stateHeight) state.TestStore.SaveBlock(blk, cert) pipe := pipeline.New[message.Message](t.Context()) conf := consensusv2.DefaultConfig() mgrInt := NewManagerV2(t.Context(), conf, state, valKeys, rewardAddrs, pipe) mgr := mgrInt.(*manager) mgr.MoveToNewHeight() for { msg := <-pipe.UnsafeGetChannel() logger.Info("Published Vote", "msg", msg, "type", msg.Type()) m, ok := msg.(*message.BlockAnnounceMessage) if ok { require.Equal(t, stateHeight+1, m.Height()) return } } } ================================================ FILE: consensus/manager/mock.go ================================================ package manager import ( "github.com/pactus-project/pactus/consensus" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" ) func MockingManager(ts *testsuite.TestSuite, state *state.MockState, valKeys []*bls.ValidatorKey, ) (Manager, []*consensus.MockConsensus) { mocks := make([]*consensus.MockConsensus, len(valKeys)) instances := make([]Consensus, len(valKeys)) for i, key := range valKeys { cons := consensus.MockingConsensus(ts, state, key) mocks[i] = cons instances[i] = cons } return &manager{ instances: instances, upcomingVotes: make([]*vote.Vote, 0), upcomingProposals: make([]*proposal.Proposal, 0), }, mocks } ================================================ FILE: consensus/mediator.go ================================================ package consensus import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) // The `mediator` interface defines a mechanism for setting proposals and votes // between independent consensus instances. type mediator interface { OnPublishProposal(from Consensus, prop *proposal.Proposal) OnPublishVote(from Consensus, vote *vote.Vote) OnBlockAnnounce(from Consensus) Register(cons Consensus) } // ConcreteMediator struct. type ConcreteMediator struct { instances []Consensus } func NewConcreteMediator() mediator { return &ConcreteMediator{} } func (m *ConcreteMediator) OnPublishProposal(from Consensus, prop *proposal.Proposal) { for _, cons := range m.instances { if cons != from { cons.SetProposal(prop) } } } func (m *ConcreteMediator) OnPublishVote(from Consensus, vote *vote.Vote) { for _, cons := range m.instances { if cons != from { cons.AddVote(vote) } } } func (m *ConcreteMediator) OnBlockAnnounce(from Consensus) { for _, cons := range m.instances { if cons != from { cons.MoveToNewHeight() } } } // Register a new Consensus instance to the mediator. func (m *ConcreteMediator) Register(cons Consensus) { m.instances = append(m.instances, cons) } ================================================ FILE: consensus/mock.go ================================================ package consensus import ( "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" ) var _ Consensus = &MockConsensus{} // MockConsensus is a mock implementation of the Consensus interface for testing. type MockConsensus struct { ts *testsuite.TestSuite State *state.MockState ValKey *bls.ValidatorKey Votes []*vote.Vote CurProposal *proposal.Proposal Active bool Proposer bool Height types.Height Round types.Round } func MockingConsensus(ts *testsuite.TestSuite, state *state.MockState, valKey *bls.ValidatorKey) *MockConsensus { return &MockConsensus{ ts: ts, State: state, ValKey: valKey, } } func (m *MockConsensus) ConsensusKey() *bls.PublicKey { return m.ValKey.PublicKey() } func (m *MockConsensus) MoveToNewHeight() { m.Height = m.State.LastBlockHeight() + 1 } func (m *MockConsensus) AddVote(v *vote.Vote) { m.Votes = append(m.Votes, v) } func (m *MockConsensus) AllVotes() []*vote.Vote { return m.Votes } func (m *MockConsensus) SetProposal(p *proposal.Proposal) { m.CurProposal = p } func (m *MockConsensus) HasVote(h hash.Hash) bool { for _, v := range m.Votes { if v.Hash() == h { return true } } return false } func (m *MockConsensus) Proposal() *proposal.Proposal { return m.CurProposal } func (m *MockConsensus) HandleQueryProposal(_ types.Height, _ types.Round) *proposal.Proposal { return m.CurProposal } func (m *MockConsensus) HeightRound() (types.Height, types.Round) { return m.Height, m.Round } func (*MockConsensus) LogString() string { return "" } func (m *MockConsensus) HandleQueryVote(_ types.Height, _ types.Round) *vote.Vote { if len(m.Votes) == 0 { return nil } r := m.ts.RandInt32Max(int32(len(m.Votes))) return m.Votes[r] } func (m *MockConsensus) IsActive() bool { return m.Active } func (m *MockConsensus) IsProposer() bool { return m.Proposer } func (m *MockConsensus) SetActive(active bool) { m.Active = active } func (*MockConsensus) IsDeprecated() bool { return false } ================================================ FILE: consensus/precommit.go ================================================ package consensus import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type precommitState struct { *consensus hasVoted bool } func (s *precommitState) enter() { s.hasVoted = false s.decide() } func (s *precommitState) decide() { s.vote() precommits := s.log.PrecommitVoteSet(s.round) precommitQH := precommits.QuorumHash() if precommitQH != nil { s.logger.Debug("pre-commit has quorum", "hash", precommitQH) if s.hasVoted { // To ensure we have voted and won't be absent from the certificate s.enterNewState(s.commitState) } } else { // // If a validator receives a set of f+1 valid cp:PRE-VOTE votes for this round, // it starts the changing proposer phase, even if its timer has not expired; // This prevents it from starting the change-proposer phase too late. // cpPreVotes := s.log.CPPreVoteVoteSet(s.round) if cpPreVotes.HasOneThirdOfTotalPower(0) { s.startChangingProposer() } } } func (s *precommitState) vote() { if s.hasVoted { return } roundProposal := s.log.RoundProposal(s.round) if roundProposal == nil { s.queryProposal() s.logger.Debug("no proposal yet") return } prepares := s.log.PrepareVoteSet(s.round) prepareQH := prepares.QuorumHash() if !roundProposal.IsForBlock(*prepareQH) { s.log.SetRoundProposal(s.round, nil) s.queryProposal() s.logger.Warn("double proposal detected", "roundProposal", roundProposal, "prepared", *prepareQH) return } // Everything is good s.signAddPrecommitVote(*prepareQH) s.hasVoted = true } func (s *precommitState) onAddVote(v *vote.Vote) { if v.Type() == vote.VoteTypePrecommit || v.Type() == vote.VoteTypeCPPreVote { s.decide() } } func (s *precommitState) onSetProposal(_ *proposal.Proposal) { s.decide() } func (s *precommitState) onTimeout(t *ticker) { if t.Target == tickerTargetChangeProposer { s.startChangingProposer() } } func (*precommitState) name() string { return "precommit" } ================================================ FILE: consensus/precommit_test.go ================================================ package consensus import ( "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" "github.com/stretchr/testify/assert" ) func TestPrecommitQueryProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) td.enterNewHeight(td.consP) prop := td.makeProposal(t, height, round) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexB) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.addPrecommitVote(td.consP, prop.Block().Hash(), height, round, tIndexB) td.shouldPublishQueryProposal(t, td.consP, height) } func TestPrecommitDuplicatedProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) prop1 := td.makeProposal(t, height, round) prop2 := td.makeProposal(t, height, round, td.RandAccAddress()) assert.NotEqual(t, prop1.Hash(), prop2.Hash()) td.enterNewHeight(td.consP) // Byzantine node sends second proposal to Partitioned node // in prepare step td.consP.SetProposal(prop2) assert.NotNil(t, td.consP.Proposal()) td.addPrepareVote(td.consP, prop1.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop1.Block().Hash(), height, round, tIndexY) td.addPrepareVote(td.consP, prop1.Block().Hash(), height, round, tIndexB) assert.Nil(t, td.consP.Proposal()) td.shouldPublishQueryProposal(t, td.consP, height) // Byzantine node sends second proposal to Partitioned node, // in precommit step td.consP.SetProposal(prop2) assert.Nil(t, td.consP.Proposal()) td.shouldPublishQueryProposal(t, td.consP, height) td.consP.SetProposal(prop1) assert.NotNil(t, td.consP.Proposal()) } func TestGoToChangeProposerFromPrecommit(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) td.enterNewHeight(td.consP) blockHash := td.RandHash() td.addPrepareVote(td.consP, blockHash, height, round, tIndexX) td.addPrepareVote(td.consP, blockHash, height, round, tIndexY) td.addPrepareVote(td.consP, blockHash, height, round, tIndexB) td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, &vote.JustInitYes{}, tIndexX) td.addCPPreVote(td.consP, hash.UndefHash, height, round, vote.CPValueYes, &vote.JustInitYes{}, tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, blockHash) } ================================================ FILE: consensus/prepare.go ================================================ package consensus import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type prepareState struct { *consensus hasVoted bool } func (s *prepareState) enter() { s.hasVoted = false changeProperTimeout := s.config.CalculateChangeProposerTimeout(s.round) queryProposalTimeout := changeProperTimeout / 2 s.scheduleTimeout(queryProposalTimeout, s.height, s.round, tickerTargetQueryProposal) s.scheduleTimeout(changeProperTimeout, s.height, s.round, tickerTargetChangeProposer) s.decide() } func (s *prepareState) decide() { s.vote() prepares := s.log.PrepareVoteSet(s.round) prepareQH := prepares.QuorumHash() if prepareQH != nil { s.logger.Debug("prepare has quorum", "hash", prepareQH) s.enterNewState(s.precommitState) } else { // // If a validator receives a set of f+1 valid cp:PRE-VOTE votes for this round, // it starts changing the proposer phase, even if its timer has not expired; // This prevents it from starting the change-proposer phase too late. // cpPreVotes := s.log.CPPreVoteVoteSet(s.round) if cpPreVotes.HasOneThirdOfTotalPower(0) { s.startChangingProposer() } } } func (s *prepareState) vote() { if s.hasVoted { return } roundProposal := s.log.RoundProposal(s.round) if roundProposal == nil { s.logger.Debug("no proposal yet") return } // Everything is good s.signAddPrepareVote(roundProposal.Block().Hash()) s.hasVoted = true } func (s *prepareState) onTimeout(ticker *ticker) { switch ticker.Target { case tickerTargetQueryProposal: roundProposal := s.log.RoundProposal(s.round) if roundProposal == nil { s.queryProposal() } if s.isProposer() { s.queryVote() } // Schedule another timeout to retry querying for the proposal or votes. // This ensures that delayed or missing data doesn't cause the process to stall. s.scheduleTimeout(ticker.Duration*2, s.height, s.round, tickerTargetQueryProposal) case tickerTargetChangeProposer: s.startChangingProposer() case tickerTargetNewHeight, tickerTargetQueryVote: // These targets are not used in the prepare state } } func (s *prepareState) onAddVote(v *vote.Vote) { if v.Type() == vote.VoteTypePrepare || v.Type() == vote.VoteTypeCPPreVote { s.decide() } } func (s *prepareState) onSetProposal(_ *proposal.Proposal) { s.decide() } func (*prepareState) name() string { return "prepare" } ================================================ FILE: consensus/prepare_test.go ================================================ package consensus import ( "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" ) func TestChangeProposerTimeout(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) } func TestQueryProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) td.queryProposalTimeout(td.consP) td.shouldPublishQueryProposal(t, td.consP, height) td.shouldNotPublish(t, td.consP, message.TypeQueryVote) } func TestQueryVote(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) height := types.Height(3) round := types.Round(1) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) // consP is the proposer for this round, but there are not enough votes. td.queryProposalTimeout(td.consP) td.shouldPublishProposal(t, td.consP, height, round) td.shouldPublishQueryVote(t, td.consP, height, round) td.shouldNotPublish(t, td.consP, message.TypeQueryProposal) } func TestGoToChangeProposerFromPrepare(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consP) td.addCPPreVote(td.consP, hash.UndefHash, 2, 0, vote.CPValueYes, &vote.JustInitYes{}, tIndexX) td.addCPPreVote(td.consP, hash.UndefHash, 2, 0, vote.CPValueYes, &vote.JustInitYes{}, tIndexY) // should move to the change proposer phase, even if it has the proposal and // its timer has not expired, if it has received 1/3 of the change-proposer votes. p := td.makeProposal(t, 2, 0) td.consP.SetProposal(p) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) } ================================================ FILE: consensus/propose.go ================================================ package consensus import ( "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type proposeState struct { *consensus } func (s *proposeState) enter() { s.decide() } func (s *proposeState) decide() { proposer := s.proposer(s.round) if proposer.Address() == s.valKey.Address() { s.logger.Info("our turn to propose", "proposer", proposer.Address()) s.createProposal(s.height, s.round) } else { s.logger.Debug("not our turn to propose", "proposer", proposer.Address()) } s.cpRound = 0 s.cpDecided = -1 s.cpWeakValidity = nil // TODO: write test for me score := s.bcState.AvailabilityScore(proposer.Number()) // Based on PIP-19, if the Availability Score is less than the Minimum threshold, // we initiate the Change-Proposer phase. if score < s.config.MinimumAvailabilityScore { s.logger.Info("availability score of proposer is low", "score", score, "proposer", proposer.Address()) s.startChangingProposer() } else { s.enterNewState(s.prepareState) } } func (s *proposeState) createProposal(height types.Height, round types.Round) { block, err := s.bcState.ProposeBlock(s.valKey, s.rewardAddr) if err != nil { s.logger.Error("unable to propose a block!", "error", err) return } prop := proposal.NewProposal(height, round, block) sig := s.valKey.Sign(prop.SignBytes()) prop.SetSignature(sig) s.log.SetRoundProposal(round, prop) s.broadcastProposal(prop) s.logger.Info("proposal signed and broadcasted", "proposal", prop) } func (*proposeState) onAddVote(_ *vote.Vote) { panic("Unreachable") } func (*proposeState) onSetProposal(_ *proposal.Proposal) { panic("Unreachable") } func (*proposeState) onTimeout(_ *ticker) { panic("Unreachable") } func (*proposeState) name() string { return "propose" } ================================================ FILE: consensus/propose_test.go ================================================ package consensus import ( "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestProposeBlock(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) p := td.shouldPublishProposal(t, td.consX, 1, 0) assert.Equal(t, td.consX.valKey.Address(), p.Block().Header().ProposerAddress()) } func TestSetProposalInvalidProposer(t *testing.T) { td := setup(t) td.enterNewHeight(td.consY) assert.Nil(t, td.consY.Proposal()) addr := td.consB.valKey.Address() blk, _ := td.GenerateTestBlock(1, testsuite.BlockWithProposer(addr)) invalidProp := proposal.NewProposal(1, 0, blk) td.consY.SetProposal(invalidProp) assert.Nil(t, td.consY.Proposal()) td.HelperSignProposal(td.consB.valKey, invalidProp) td.consY.SetProposal(invalidProp) assert.Nil(t, td.consY.Proposal()) } func TestSetProposalInvalidBlock(t *testing.T) { td := setup(t) addr := td.consB.valKey.Address() blk, _ := td.GenerateTestBlock(1, testsuite.BlockWithProposer(addr)) invProp := proposal.NewProposal(1, 2, blk) td.HelperSignProposal(td.consB.valKey, invProp) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) td.enterNextRound(td.consP) td.consP.SetProposal(invProp) assert.Nil(t, td.consP.Proposal()) } func TestSetProposalInvalidHeight(t *testing.T) { td := setup(t) addr := td.consB.valKey.Address() blk, _ := td.GenerateTestBlock(2, testsuite.BlockWithProposer(addr)) invProp := proposal.NewProposal(2, 0, blk) td.HelperSignProposal(td.consB.valKey, invProp) td.enterNewHeight(td.consY) td.consY.SetProposal(invProp) assert.Nil(t, td.consY.Proposal()) } func TestNetworkLagging(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) prop := td.makeProposal(t, height, round) // consP doesn't have the proposal, but it has received prepared votes from other peers td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrepareVote(td.consP, prop.Block().Hash(), height, round, tIndexY) td.queryProposalTimeout(td.consP) td.shouldPublishQueryProposal(t, td.consP, height) // Proposal is received now td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrepare, prop.Block().Hash()) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } func TestProposalNextRound(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) // Byzantine node sends proposal for the second round (his turn) even before the first round is started b, err := td.consB.bcState.ProposeBlock(td.consB.valKey, td.consB.rewardAddr) require.NoError(t, err) p := proposal.NewProposal(2, 1, b) td.HelperSignProposal(td.consB.valKey, p) td.consX.SetProposal(p) // consX accepts his proposal, but doesn't move to the next round assert.NotNil(t, td.consX.log.RoundProposal(1)) assert.Nil(t, td.consX.Proposal()) assert.Equal(t, types.Height(2), td.consX.height) assert.Equal(t, types.Round(0), td.consX.round) } ================================================ FILE: consensus/spec/.gitignore ================================================ *.dot *.out *.toolbox states *.tex *.dvi *.aux *.log ================================================ FILE: consensus/spec/Pactus.cfg ================================================ SPECIFICATION Spec CONSTANTS NumFaulty = 1 FaultyNodes = {3} MaxHeight = 1 MaxRound = 1 MaxCPRound = 1 INVARIANT TypeOK PROPERTY Success ================================================ FILE: consensus/spec/Pactus.tla ================================================ -------------------------------- MODULE Pactus -------------------------------- (***************************************************************************) (* The specification of the Pactus consensus algorithm: *) (* `^\url{https://pactus.org/learn/consensus/protocol/}^' *) (***************************************************************************) EXTENDS Integers, Sequences, FiniteSets, TLC CONSTANT \* The maximum number of height. \* this is to restrict the allowed behaviours that TLC scans through. MaxHeight, \* The maximum number of round per height. \* this is to restrict the allowed behaviours that TLC scans through. MaxRound, \* The maximum number of cp-round per height. \* this is to restrict the allowed behaviours that TLC scans through. MaxCPRound, \* The total number of faulty nodes NumFaulty, \* The index of faulty nodes FaultyNodes VARIABLES \* `log` is a set of received messages in the system. log, \* `states` represents the state of each replica in the consensus protocol. states \* Total number of replicas, which is `3f+1', where `f' is the number of faulty nodes. Replicas == (3 * NumFaulty) + 1 \* Quorum is 2/3+ of total replicas that is `2f+1' Quorum == (2 * NumFaulty) + 1 \* OneThird is 1/3+ of total replicas that is `f+1' OneThird == NumFaulty + 1 \* A tuple with all variables in the spec (for ease of use in temporal conditions) vars == <> ASSUME /\ NumFaulty >= 1 /\ FaultyNodes \subseteq 0..Replicas-1 ----------------------------------------------------------------------------- (***************************************************************************) (* Helper functions *) (***************************************************************************) \* Fetch a subset of messages in the network based on the params filter. SubsetOfMsgs(params) == {msg \in log: \A field \in DOMAIN params: msg[field] = params[field]} \* IsProposer checks if the replica is the proposer for this round. \* To simplify, we assume the proposer always starts with the first replica, \* and moves to the next by the change-proposer phase. IsProposer(index) == states[index].round % Replicas = index \* Helper function to check if a node is faulty or not. IsFaulty(index) == index \in FaultyNodes \* HasPrepareQuorum checks if there is a quorum of \* the PREPARE votes in this round. HasPrepareQuorum(index) == Cardinality(SubsetOfMsgs([ type |-> "PREPARE", height |-> states[index].height, round |-> states[index].round, cp_round |-> 0])) >= Quorum \* HasPrecommitQuorum checks if there is a quorum of \* the PRECOMMIT votes in this round. HasPrecommitQuorum(index) == Cardinality(SubsetOfMsgs([ type |-> "PRECOMMIT", height |-> states[index].height, round |-> states[index].round, cp_round |-> 0])) >= Quorum CPHasPreVotesQuorum(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round])) >= Quorum CPHasPreVotesQuorumForOne(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= Quorum CPHasPreVotesQuorumForZero(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 0])) >= Quorum CPHasPreVotesForZeroAndOne(index) == /\ Cardinality(SubsetOfMsgs([ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 0])) >= 1 /\ Cardinality(SubsetOfMsgs([ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= 1 CPHasOneMainVotesZeroInPrvRound(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round - 1, cp_val |-> 0])) > 0 CPHasOneMainVotesOneInPrvRound(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round - 1, cp_val |-> 1])) > 0 CPAllMainVotesAbstainInPrvRound(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round - 1, cp_val |-> 2])) >= Quorum CPHasMainVotesQuorum(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round])) >= Quorum CPHasMainVotesQuorumForOne(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= Quorum CPHasMainVotesQuorumForZero(index) == Cardinality(SubsetOfMsgs([ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 0])) >= Quorum GetProposal(height, round) == SubsetOfMsgs([type |-> "PROPOSAL", height |-> height, round |-> round]) HasProposal(index) == Cardinality(GetProposal(states[index].height, states[index].round)) > 0 HasBlockAnnounce(index) == Cardinality(SubsetOfMsgs([ type |-> "BLOCK-ANNOUNCE", height |-> states[index].height, round |-> states[index].round, cp_round |-> 0, cp_val |-> 0])) >= 1 \* Helper function to check if the block is committed or not. \* A block is considered committed iff supermajority of non-faulty replicas announce the same block. IsCommitted(height) == LET subset == SubsetOfMsgs([ type |-> "BLOCK-ANNOUNCE", height |-> height, cp_round |-> 0, cp_val |-> 0]) IN /\ Cardinality(subset) >= Quorum /\ \A m1, m2 \in subset : m1.round = m2.round ----------------------------------------------------------------------------- (***************************************************************************) (* Network functions *) (***************************************************************************) \* `SendMsg` simulates a replica sending a message by appending it to the `log`. SendMsg(msg) == log' = log \cup msg \* SendProposal is used to broadcast the PROPOSAL into the network. SendProposal(index) == SendMsg({[ type |-> "PROPOSAL", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]}) \* SendPrepareVote is used to broadcast PREPARE votes into the network. SendPrepareVote(index) == SendMsg({[ type |-> "PREPARE", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]}) \* SendPrecommitVote is used to broadcast PRECOMMIT votes into the network. SendPrecommitVote(index) == SendMsg({[ type |-> "PRECOMMIT", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]}) \* SendCPPreVote is used to broadcast CP:PRE-VOTE votes into the network. SendCPPreVote(index, cp_val) == SendMsg({[ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> states[index].cp_round, cp_val |-> cp_val]}) \* SendCPMainVote is used to broadcast CP:MAIN-VOTE votes into the network. SendCPMainVote(index, cp_val) == SendMsg({[ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> states[index].cp_round, cp_val |-> cp_val]}) SendCPVotesForNextRound(index, cp_val) == SendMsg({ [ type |-> "CP:PRE-VOTE", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> states[index].cp_round + 1, cp_val |-> cp_val], [ type |-> "CP:MAIN-VOTE", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> states[index].cp_round + 1, cp_val |-> cp_val]}) \* AnnounceBlock is used to broadcast BLOCK-ANNOUNCE messages into the network. AnnounceBlock(index) == SendMsg({[ type |-> "BLOCK-ANNOUNCE", height |-> states[index].height, round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]}) ----------------------------------------------------------------------------- (***************************************************************************) (* States functions *) (***************************************************************************) \* NewHeight state NewHeight(index) == IF states[index].height >= MaxHeight THEN UNCHANGED <> ELSE /\ ~IsFaulty(index) /\ states[index].name = "new-height" /\ states[index].height < MaxHeight /\ states' = [states EXCEPT ![index].name = "propose", ![index].height = states[index].height + 1, ![index].round = 0] /\ UNCHANGED <> \* Propose state Propose(index) == /\ ~IsFaulty(index) /\ states[index].name = "propose" /\ IF IsProposer(index) THEN SendProposal(index) ELSE UNCHANGED <> /\ states' = [states EXCEPT ![index].name = "prepare", ![index].timeout = FALSE, ![index].cp_round = 0] \* Prepare state Prepare(index) == /\ ~IsFaulty(index) /\ states[index].name = "prepare" /\ IF HasPrepareQuorum(index) THEN /\ states' = [states EXCEPT ![index].name = "precommit"] /\ UNCHANGED <> ELSE /\ HasProposal(index) /\ SendPrepareVote(index) /\ UNCHANGED <> \* Precommit state Precommit(index) == /\ ~IsFaulty(index) /\ states[index].name = "precommit" /\ IF HasPrecommitQuorum(index) THEN /\ states' = [states EXCEPT ![index].name = "commit"] /\ UNCHANGED <> ELSE /\ HasProposal(index) /\ SendPrecommitVote(index) /\ UNCHANGED <> \* Commit state Commit(index) == /\ ~IsFaulty(index) /\ states[index].name = "commit" /\ AnnounceBlock(index) /\ states' = [states EXCEPT ![index].name = "new-height"] \* Timeout: A non-faulty Replica try to change the proposer if its timer expires. Timeout(index) == /\ ~IsFaulty(index) /\ states[index].round < MaxRound /\ states[index].timeout = FALSE /\ \/ /\ states[index].name = "prepare" /\ SendCPPreVote(index, 1) \/ /\ states[index].name = "precommit" /\ SendCPPreVote(index, 0) /\ states' = [states EXCEPT ![index].name = "cp:main-vote", ![index].timeout = TRUE] CPPreVote(index) == /\ ~IsFaulty(index) /\ states[index].name = "cp:pre-vote" /\ \/ /\ CPHasOneMainVotesOneInPrvRound(index) /\ SendCPPreVote(index, 1) \/ /\ CPHasOneMainVotesZeroInPrvRound(index) /\ SendCPPreVote(index, 0) \/ /\ CPAllMainVotesAbstainInPrvRound(index) /\ SendCPPreVote(index, 0) \* biased to zero /\ states' = [states EXCEPT ![index].name = "cp:main-vote"] CPMainVote(index) == /\ ~IsFaulty(index) /\ states[index].name = "cp:main-vote" /\ CPHasPreVotesQuorum(index) /\ \/ \* all votes for 1 /\ CPHasPreVotesQuorumForOne(index) /\ SendCPMainVote(index, 1) /\ states' = [states EXCEPT ![index].name = "cp:decide"] \/ \* all votes for 0 /\ CPHasPreVotesQuorumForZero(index) /\ SendCPMainVote(index, 0) /\ states' = [states EXCEPT ![index].name = "cp:decide"] \/ \* Abstain vote /\ CPHasPreVotesForZeroAndOne(index) /\ SendCPMainVote(index, 2) /\ states' = [states EXCEPT ![index].name = "cp:decide"] CPDecide(index) == /\ ~IsFaulty(index) /\ states[index].name = "cp:decide" /\ \/ /\ states[index].cp_decided = 1 /\ states' = [states EXCEPT ![index].name = "propose", ![index].round = states[index].round + 1] \/ /\ states[index].cp_decided = 0 /\ states' = [states EXCEPT ![index].name = "prepare"] \/ /\ states[index].cp_decided = -1 /\ CPHasMainVotesQuorum(index) /\ IF /\ CPHasMainVotesQuorumForOne(index) /\ states[index].cp_round /= MaxCPRound - 1 THEN states' = [states EXCEPT ![index].name = "cp:pre-vote", ![index].cp_decided = 1, ![index].cp_round = states[index].cp_round + 1] ELSE IF \/ CPHasMainVotesQuorumForZero(index) \/ states[index].cp_round = MaxCPRound - 1 THEN states' = [states EXCEPT ![index].name = "cp:pre-vote", ![index].cp_decided = 0, ![index].cp_round = states[index].cp_round + 1] ELSE states' = [states EXCEPT ![index].name = "cp:pre-vote", ![index].cp_round = states[index].cp_round + 1] /\ log' = log Sync(index) == /\ ~IsFaulty(index) /\ \/ states[index].name = "cp:pre-vote" \/ states[index].name = "cp:main-vote" \/ states[index].name = "cp:decide" /\ HasBlockAnnounce(index) /\ states' = [states EXCEPT ![index].name = "prepare"] /\ log' = log ----------------------------------------------------------------------------- Init == /\ log = {} /\ states = [index \in 0..Replicas-1 |-> [ name |-> "new-height", height |-> 0, round |-> 0, timeout |-> FALSE, cp_round |-> 0, cp_decided |-> -1]] Next == \E index \in 0..Replicas-1: \/ NewHeight(index) \/ Propose(index) \/ Prepare(index) \/ Precommit(index) \/ Timeout(index) \/ Commit(index) \/ Sync(index) \/ CPPreVote(index) \/ CPMainVote(index) \/ CPDecide(index) Spec == Init /\ [][Next]_vars /\ WF_vars(Next) (***************************************************************************) (* Success: All non-faulty nodes eventually commit at MaxHeight. *) (***************************************************************************) Success == <>(IsCommitted(MaxHeight)) (***************************************************************************) (* TypeOK is the type-correctness invariant. *) (***************************************************************************) TypeOK == /\ \A index \in 0..Replicas-1: /\ states[index].name \in {"new-height", "propose", "prepare", "precommit", "commit", "cp:pre-vote", "cp:main-vote", "cp:decide"} /\ states[index].height <= MaxHeight /\ states[index].round <= MaxRound /\ states[index].cp_round <= MaxCPRound + 1 /\ states[index].name = "new-height" /\ states[index].height > 1 => /\ IsCommitted(states[index].height - 1) /\ states[index].name = "precommit" => /\ HasPrepareQuorum(index) /\ HasProposal(index) /\ states[index].name = "commit" => /\ HasPrepareQuorum(index) /\ HasPrecommitQuorum(index) /\ HasProposal(index) /\ \A round \in 0..states[index].round: \* Not more than one proposal per round /\ Cardinality(GetProposal(states[index].height, round)) <= 1 ============================================================================= ================================================ FILE: consensus/spec/README.md ================================================ # Consensus specification This folder contains the consensus specification for the Pactus blockchain, which is based on the TLA+ formal language. The specification defines the consensus algorithm used by the blockchain. More info can be found [here](https://docs.pactus.org/protocol/consensus/specification/) ## Model checking To run the model checker, you will need to download and install the [TLA+ Toolbox](https://lamport.azurewebsites.net/tla/toolbox.html), which includes the TLC model checker. Follow the steps below to run the TLC model checker: - Add the `Pactus.tla` spec to your TLA+ Toolbox project. - Create a new model and specify a temporal formula as `Spec`. - Specify an invariants formula as `TypeOK`. - Specify a properties formula as `Success`. - Define the required constants: - `NumFaulty`: the number of faulty nodes (e.g. 1) - `FaultyNodes`: the index of faulty nodes (e.g. {3}) - `MaxHeight`: the maximum height of the system (e.g. 1) - `MaxRound`: the maximum block-creation round of the consensus algorithm (e.g. 1) - `MaxCPRound`: the maximum change-proposer round of the consensus algorithm (e.g. 1) - Run the TLC checker to check the correctness of the specification. ================================================ FILE: consensus/state.go ================================================ package consensus import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type consState interface { enter() decide() onAddVote(v *vote.Vote) onSetProposal(p *proposal.Proposal) onTimeout(t *ticker) name() string } ================================================ FILE: consensus/ticker.go ================================================ package consensus import ( "fmt" "time" "github.com/pactus-project/pactus/types" ) type tickerTarget int const ( tickerTargetNewHeight = tickerTarget(1) tickerTargetChangeProposer = tickerTarget(2) tickerTargetQueryProposal = tickerTarget(3) tickerTargetQueryVote = tickerTarget(4) ) func (rs tickerTarget) String() string { switch rs { case tickerTargetNewHeight: return "new-height" case tickerTargetChangeProposer: return "change-proposer" case tickerTargetQueryProposal: return "query-proposal" case tickerTargetQueryVote: return "query-vote" default: return "Unknown" } } type ticker struct { Duration time.Duration Height types.Height Round types.Round Target tickerTarget } // LogString returns a concise string representation intended for use in logs. func (ti ticker) LogString() string { return fmt.Sprintf("%v@ %d/%d/%s", ti.Duration, ti.Height, ti.Round, ti.Target) } ================================================ FILE: consensus/voteset/binary_voteset.go ================================================ package voteset import ( "maps" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type roundVotes struct { // Each vote can have one of 3 possible values: {0,1,Abstain}. voteBoxes [3]*voteBox allVotes map[crypto.Address]*vote.Vote votedPower int64 } func newRoundVotes() *roundVotes { voteBoxes := [3]*voteBox{} voteBoxes[vote.CPValueNo] = newVoteBox() voteBoxes[vote.CPValueYes] = newVoteBox() voteBoxes[vote.CPValueAbstain] = newVoteBox() return &roundVotes{ voteBoxes: voteBoxes, allVotes: make(map[crypto.Address]*vote.Vote), votedPower: 0, } } func (rv *roundVotes) addVote(v *vote.Vote, power int64) { vb := rv.voteBoxes[v.CPValue()] vb.addVote(v, power) } type BinaryVoteSet struct { *voteSet roundVotes []*roundVotes } func NewCPPreVoteVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BinaryVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBinaryVoteSet(voteSet) } func NewCPMainVoteVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BinaryVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBinaryVoteSet(voteSet) } func NewCPDecidedVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BinaryVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBinaryVoteSet(voteSet) } func newBinaryVoteSet(voteSet *voteSet) *BinaryVoteSet { return &BinaryVoteSet{ voteSet: voteSet, roundVotes: make([]*roundVotes, 0, 1), } } func (vs *BinaryVoteSet) mustGetRoundVotes(cpRound int16) *roundVotes { for i := len(vs.roundVotes); i <= int(cpRound); i++ { rv := newRoundVotes() vs.roundVotes = append(vs.roundVotes, rv) } return vs.roundVotes[cpRound] } // AllVotes returns a list of all votes in the VoteSet. func (vs *BinaryVoteSet) AllVotes() []*vote.Vote { votes := make([]*vote.Vote, 0) for _, rv := range vs.roundVotes { for _, v := range rv.allVotes { votes = append(votes, v) } } return votes } // AddVote attempts to add a vote to the VoteSet. Returns an error if the vote is invalid. func (vs *BinaryVoteSet) AddVote(vote *vote.Vote) (bool, error) { power, err := vs.voteSet.verifyVote(vote) if err != nil { return false, err } roundVotes := vs.mustGetRoundVotes(vote.CPRound()) existingVote, ok := roundVotes.allVotes[vote.Signer()] if ok { if existingVote.Hash() == vote.Hash() { // The vote is already added return false, nil } // It is a duplicated vote err = ErrDuplicatedVote } else { roundVotes.allVotes[vote.Signer()] = vote roundVotes.votedPower += power } roundVotes.addVote(vote, power) return true, err } func (vs *BinaryVoteSet) HasOneThirdOfTotalPower(cpRound int16) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return vs.isOneThirdOfTotalPower(roundVotes.votedPower) } func (vs *BinaryVoteSet) HasTwoThirdOfTotalPower(cpRound int16) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return vs.isTwoThirdOfTotalPower(roundVotes.votedPower) } func (vs *BinaryVoteSet) HasAnyVoteFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return roundVotes.voteBoxes[cpValue].votedPower > 0 } func (vs *BinaryVoteSet) HasAllVotesFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return roundVotes.voteBoxes[cpValue].votedPower == roundVotes.votedPower } func (vs *BinaryVoteSet) HasQuorumVotesFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return vs.isTwoThirdOfTotalPower(roundVotes.voteBoxes[cpValue].votedPower) } func (vs *BinaryVoteSet) BinaryVotes(cpRound int16, cpValue vote.CPValue) map[crypto.Address]*vote.Vote { votes := map[crypto.Address]*vote.Vote{} roundVotes := vs.mustGetRoundVotes(cpRound) voteBox := roundVotes.voteBoxes[cpValue] maps.Copy(votes, voteBox.votes) return votes } func (vs *BinaryVoteSet) GetRandomVote(cpRound int16, cpValue vote.CPValue) *vote.Vote { roundVotes := vs.mustGetRoundVotes(cpRound) for _, v := range roundVotes.voteBoxes[cpValue].votes { return v } return nil } ================================================ FILE: consensus/voteset/block_voteset.go ================================================ package voteset import ( "maps" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type BlockVoteSet struct { *voteSet blockVotes map[hash.Hash]*voteBox allVotes map[crypto.Address]*vote.Vote quorumHash *hash.Hash } func NewPrepareVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BlockVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBlockVoteSet(voteSet) } func NewPrecommitVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BlockVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBlockVoteSet(voteSet) } func newBlockVoteSet(voteSet *voteSet) *BlockVoteSet { return &BlockVoteSet{ voteSet: voteSet, blockVotes: make(map[hash.Hash]*voteBox), allVotes: make(map[crypto.Address]*vote.Vote), } } func (vs *BlockVoteSet) BlockVotes(blockHash hash.Hash) map[crypto.Address]*vote.Vote { votes := map[crypto.Address]*vote.Vote{} blockVotes := vs.mustGetBlockVotes(blockHash) maps.Copy(votes, blockVotes.votes) return votes } func (vs *BlockVoteSet) mustGetBlockVotes(blockHash hash.Hash) *voteBox { blockVotes, exists := vs.blockVotes[blockHash] if !exists { blockVotes = newVoteBox() vs.blockVotes[blockHash] = blockVotes } return blockVotes } // AllVotes returns a list of all votes in the VoteSet. func (vs *BlockVoteSet) AllVotes() []*vote.Vote { votes := make([]*vote.Vote, 0, len(vs.allVotes)) for _, v := range vs.allVotes { votes = append(votes, v) } return votes } // AddVote attempts to add a vote to the VoteSet. Returns an error if the vote is invalid. func (vs *BlockVoteSet) AddVote(vote *vote.Vote) (bool, error) { power, err := vs.voteSet.verifyVote(vote) if err != nil { return false, err } existingVote, ok := vs.allVotes[vote.Signer()] if ok { if existingVote.Hash() == vote.Hash() { // The vote is already added return false, nil } // It is a duplicated vote err = ErrDuplicatedVote } else { vs.allVotes[vote.Signer()] = vote } blockVotes := vs.mustGetBlockVotes(vote.BlockHash()) blockVotes.addVote(vote, power) if vs.isTwoThirdOfTotalPower(blockVotes.votedPower) { h := vote.BlockHash() vs.quorumHash = &h } return true, err } // HasQuorumHash checks if there is a block that has received quorum votes (2/3+ of total power). func (vs *BlockVoteSet) HasQuorumHash() bool { return vs.quorumHash != nil } // QuorumHash returns the hash of the block that has received quorum votes (2/3+ of total power). // If no block has received the quorum threshold (2/3+ of total voting power), it returns nil. func (vs *BlockVoteSet) QuorumHash() *hash.Hash { return vs.quorumHash } ================================================ FILE: consensus/voteset/errors.go ================================================ package voteset import ( "errors" "fmt" "github.com/pactus-project/pactus/crypto" ) // ErrDuplicatedVote is returned when a duplicated vote from a validator is detected. var ErrDuplicatedVote = errors.New("duplicated vote") // IneligibleVoterError is returned when the voter is not a member of the committee. type IneligibleVoterError struct { Address crypto.Address } func (e IneligibleVoterError) Error() string { return fmt.Sprintf("validator %s is not part of the committee", e.Address) } ================================================ FILE: consensus/voteset/vote_box.go ================================================ package voteset import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/vote" ) type voteBox struct { votes map[crypto.Address]*vote.Vote votedPower int64 } func newVoteBox() *voteBox { return &voteBox{ votes: make(map[crypto.Address]*vote.Vote), votedPower: 0, } } func (vs *voteBox) addVote(vote *vote.Vote, power int64) { if vs.votes[vote.Signer()] == nil { vs.votes[vote.Signer()] = vote vs.votedPower += power } } ================================================ FILE: consensus/voteset/vote_box_test.go ================================================ package voteset import ( "testing" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestDuplicateVote(t *testing.T) { ts := testsuite.NewTestSuite(t) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() signer := ts.RandValAddress() power := ts.RandInt64Max(1000) v := vote.NewPrepareVote(hash, height, round, signer) vb := newVoteBox() vb.addVote(v, power) vb.addVote(v, power) assert.Equal(t, power, vb.votedPower) } ================================================ FILE: consensus/voteset/voteset.go ================================================ package voteset import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type voteSet struct { round types.Round validators map[crypto.Address]*validator.Validator totalPower int64 } func newVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *voteSet { return &voteSet{ round: round, validators: validators, totalPower: totalPower, } } // Round returns the round number for the VoteSet. func (vs *voteSet) Round() types.Round { return vs.round } // verifyVote checks if the given vote is valid. // It returns the voting power of if valid, or an error if not. func (vs *voteSet) verifyVote(vote *vote.Vote) (int64, error) { signer := vote.Signer() val := vs.validators[signer] if val == nil { return 0, IneligibleVoterError{ Address: signer, } } if err := vote.Verify(val.PublicKey()); err != nil { return 0, err } return val.Power(), nil } func (vs *voteSet) isTwoThirdOfTotalPower(power int64) bool { return power > (vs.totalPower * 2 / 3) } func (vs *voteSet) isOneThirdOfTotalPower(power int64) bool { return power > (vs.totalPower * 1 / 3) } ================================================ FILE: consensus/voteset/voteset_test.go ================================================ package voteset import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func setupCommittee(ts *testsuite.TestSuite, stakes ...amount.Amount) ( map[crypto.Address]*validator.Validator, []*bls.ValidatorKey, int64, ) { valKeys := make([]*bls.ValidatorKey, 0, len(stakes)) valsMap := map[crypto.Address]*validator.Validator{} totalPower := int64(0) for i, s := range stakes { pub, prv := ts.RandBLSKeyPair() val := ts.GenerateTestValidator( testsuite.ValidatorWithNumber(int32(i)), testsuite.ValidatorWithPublicKey(pub), testsuite.ValidatorWithStake(s), ) valsMap[val.Address()] = val totalPower += val.Power() valKeys = append(valKeys, bls.NewValidatorKey(prv)) } return valsMap, valKeys, totalPower } func TestAddBlockVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) hash1 := ts.RandHash() hash2 := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() invKey := ts.RandValKey() valKey := valKeys[0] voteSet := NewPrecommitVoteSet(round, totalPower, valsMap) vote1 := vote.NewPrecommitVote(hash1, height, round, invKey.Address()) vote2 := vote.NewPrecommitVote(hash1, height, round, valKey.Address()) vote3 := vote.NewPrecommitVote(hash2, height, round, valKey.Address()) ts.HelperSignVote(invKey, vote1) added, err := voteSet.AddVote(vote1) require.ErrorIs(t, err, IneligibleVoterError{Address: vote1.Signer()}) // unknown validator assert.False(t, added) ts.HelperSignVote(invKey, vote2) added, err = voteSet.AddVote(vote2) require.ErrorIs(t, err, crypto.ErrInvalidSignature) // invalid signature assert.False(t, added) ts.HelperSignVote(valKey, vote2) added, err = voteSet.AddVote(vote2) require.NoError(t, err) // ok assert.True(t, added) added, err = voteSet.AddVote(vote2) // Adding again assert.False(t, added) require.NoError(t, err) ts.HelperSignVote(valKey, vote3) added, err = voteSet.AddVote(vote3) require.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) } func TestAddBinaryVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) hash1 := ts.RandHash() hash2 := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cpRound := int16(ts.RandRound()) cpVal := ts.RandIntMax(2) just := &vote.JustInitYes{} invKey := ts.RandValKey() valKey := valKeys[0] voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) vote1 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, invKey.Address()) vote2 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) vote3 := vote.NewCPPreVote(hash2, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) ts.HelperSignVote(invKey, vote1) added, err := voteSet.AddVote(vote1) require.ErrorIs(t, err, IneligibleVoterError{Address: vote1.Signer()}) // unknown validator assert.False(t, added) ts.HelperSignVote(invKey, vote2) added, err = voteSet.AddVote(vote2) require.ErrorIs(t, err, crypto.ErrInvalidSignature) // invalid signature assert.False(t, added) ts.HelperSignVote(valKey, vote2) added, err = voteSet.AddVote(vote2) require.NoError(t, err) // ok assert.True(t, added) added, err = voteSet.AddVote(vote2) // Adding again assert.False(t, added) require.NoError(t, err) ts.HelperSignVote(valKey, vote3) added, err = voteSet.AddVote(vote3) require.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) } func TestDuplicateBlockVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1, 1, 1, 1) hash1 := ts.RandHash() hash2 := ts.RandHash() hash3 := ts.RandHash() addr := valKeys[0].Address() voteSet := NewPrepareVoteSet(0, totalPower, valsMap) correctVote := vote.NewPrepareVote(hash1, 1, 0, addr) duplicatedVote1 := vote.NewPrepareVote(hash2, 1, 0, addr) duplicatedVote2 := vote.NewPrepareVote(hash3, 1, 0, addr) // sign the votes ts.HelperSignVote(valKeys[0], correctVote) ts.HelperSignVote(valKeys[0], duplicatedVote1) ts.HelperSignVote(valKeys[0], duplicatedVote2) added, err := voteSet.AddVote(correctVote) require.NoError(t, err) assert.True(t, added) added, err = voteSet.AddVote(duplicatedVote1) require.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) added, err = voteSet.AddVote(duplicatedVote2) require.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) bv1 := voteSet.BlockVotes(hash1) bv2 := voteSet.BlockVotes(hash2) bv3 := voteSet.BlockVotes(hash3) assert.Equal(t, correctVote, bv1[addr]) assert.Equal(t, duplicatedVote1, bv2[addr]) assert.Equal(t, duplicatedVote2, bv3[addr]) assert.False(t, voteSet.HasQuorumHash()) } func TestDuplicateBinaryVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1, 1, 1, 1) hash1 := ts.RandHash() hash2 := ts.RandHash() hash3 := ts.RandHash() addr := valKeys[0].Address() voteSet := NewCPPreVoteVoteSet(0, totalPower, valsMap) correctVote := vote.NewCPPreVote(hash1, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) duplicatedVote1 := vote.NewCPPreVote(hash2, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) duplicatedVote2 := vote.NewCPPreVote(hash3, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) // sign the votes ts.HelperSignVote(valKeys[0], correctVote) ts.HelperSignVote(valKeys[0], duplicatedVote1) ts.HelperSignVote(valKeys[0], duplicatedVote2) added, err := voteSet.AddVote(correctVote) require.NoError(t, err) assert.True(t, added) added, err = voteSet.AddVote(duplicatedVote1) require.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) added, err = voteSet.AddVote(duplicatedVote2) require.ErrorIs(t, err, ErrDuplicatedVote) assert.True(t, added) assert.False(t, voteSet.HasOneThirdOfTotalPower(0)) } func TestQuorum(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) voteSet := NewPrecommitVoteSet(0, totalPower, valsMap) blockHash := ts.RandHash() vote1 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[1].Address()) vote3 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[2].Address()) vote4 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[3].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) ts.HelperSignVote(valKeys[3], vote4) _, err := voteSet.AddVote(vote1) require.NoError(t, err) _, err = voteSet.AddVote(vote2) require.NoError(t, err) assert.Nil(t, voteSet.QuorumHash()) assert.False(t, voteSet.HasQuorumHash()) assert.Contains(t, voteSet.BlockVotes(blockHash), vote1.Signer()) assert.Contains(t, voteSet.BlockVotes(blockHash), vote2.Signer()) _, err = voteSet.AddVote(vote3) require.NoError(t, err) assert.True(t, voteSet.HasQuorumHash()) assert.Contains(t, voteSet.BlockVotes(blockHash), vote3.Signer()) assert.NotContains(t, voteSet.BlockVotes(blockHash), vote4.Signer()) // Add one more vote _, err = voteSet.AddVote(vote4) require.NoError(t, err) assert.NotNil(t, voteSet.QuorumHash()) assert.Equal(t, &blockHash, voteSet.QuorumHash()) assert.True(t, voteSet.HasQuorumHash()) assert.Contains(t, voteSet.BlockVotes(blockHash), vote4.Signer()) } func TestAllBlockVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) voteSet := NewPrecommitVoteSet(1, totalPower, valsMap) hash1 := ts.RandHash() hash2 := ts.RandHash() vote1 := vote.NewPrecommitVote(hash1, 1, 1, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(hash1, 1, 1, valKeys[1].Address()) vote3 := vote.NewPrecommitVote(hash1, 1, 1, valKeys[2].Address()) vote4 := vote.NewPrecommitVote(hash2, 1, 1, valKeys[0].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) ts.HelperSignVote(valKeys[0], vote4) _, err := voteSet.AddVote(vote1) require.NoError(t, err) _, err = voteSet.AddVote(vote2) require.NoError(t, err) _, err = voteSet.AddVote(vote3) require.NoError(t, err) assert.Equal(t, &hash1, voteSet.QuorumHash()) _, err = voteSet.AddVote(vote4) require.ErrorIs(t, err, ErrDuplicatedVote) // Check accumulated power assert.Equal(t, &hash1, voteSet.QuorumHash()) // Check previous votes assert.Contains(t, voteSet.AllVotes(), vote1) assert.Contains(t, voteSet.AllVotes(), vote2) assert.Contains(t, voteSet.AllVotes(), vote3) assert.NotContains(t, voteSet.AllVotes(), vote4) } func TestAllBinaryVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1000, 1500, 2500, 2000) voteSet := NewCPMainVoteVoteSet(1, totalPower, valsMap) vote1 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) vote2 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 1, vote.CPValueYes, &vote.JustInitYes{}, valKeys[1].Address()) vote3 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 2, vote.CPValueAbstain, &vote.JustInitYes{}, valKeys[2].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) assert.Empty(t, voteSet.AllVotes()) _, err := voteSet.AddVote(vote1) require.NoError(t, err) _, err = voteSet.AddVote(vote2) require.NoError(t, err) _, err = voteSet.AddVote(vote3) require.NoError(t, err) assert.Contains(t, voteSet.AllVotes(), vote1) assert.Contains(t, voteSet.AllVotes(), vote2) assert.Contains(t, voteSet.AllVotes(), vote3) ranVote1 := voteSet.GetRandomVote(1, vote.CPValueNo) assert.Nil(t, ranVote1) ranVote2 := voteSet.GetRandomVote(1, vote.CPValueYes) assert.Equal(t, vote2, ranVote2) } func TestOneThirdPower(t *testing.T) { ts := testsuite.NewTestSuite(t) // total power = 3000 // 1/3 of total power = 1000 // 2/3 of total power = 2000 valsMap, valKeys, totalPower := setupCommittee(ts, 999, 3, 999, 999) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) vote1 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) vote2 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[1].Address()) vote3 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[2].Address()) vote4 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueNo, just, valKeys[3].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) ts.HelperSignVote(valKeys[3], vote4) _, err := voteSet.AddVote(vote1) require.NoError(t, err) assert.False(t, voteSet.HasOneThirdOfTotalPower(0)) assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueAbstain)) _, err = voteSet.AddVote(vote2) require.NoError(t, err) assert.True(t, voteSet.HasOneThirdOfTotalPower(0)) assert.False(t, voteSet.HasTwoThirdOfTotalPower(0)) _, err = voteSet.AddVote(vote3) require.NoError(t, err) assert.True(t, voteSet.HasTwoThirdOfTotalPower(0)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasQuorumVotesFor(0, vote.CPValueNo)) assert.True(t, voteSet.HasQuorumVotesFor(0, vote.CPValueYes)) assert.True(t, voteSet.HasAllVotesFor(0, vote.CPValueYes)) _, err = voteSet.AddVote(vote4) require.NoError(t, err) assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) assert.False(t, voteSet.HasQuorumVotesFor(0, vote.CPValueNo)) assert.True(t, voteSet.HasQuorumVotesFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasAllVotesFor(0, vote.CPValueYes)) bv1 := voteSet.BinaryVotes(0, vote.CPValueYes) bv2 := voteSet.BinaryVotes(0, vote.CPValueNo) assert.Contains(t, bv1, vote1.Signer()) assert.Contains(t, bv1, vote2.Signer()) assert.Contains(t, bv1, vote3.Signer()) assert.Contains(t, bv2, vote4.Signer()) } func TestDecidedVoteset(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 1, 1, 1, 1) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} voteSet := NewCPDecidedVoteSet(round, totalPower, valsMap) vte := vote.NewCPDecidedVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) ts.HelperSignVote(valKeys[0], vte) _, err := voteSet.AddVote(vte) require.NoError(t, err) assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) } ================================================ FILE: consensusv2/commit.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type commitState struct { *consensusV2 } func (s *commitState) enter() { s.decide() } func (s *commitState) decide() { roundProposal := s.log.RoundProposal(s.round) block := roundProposal.Block() precommits := s.log.PrecommitVoteSet(s.round) votes := precommits.BlockVotes(block.Hash()) cert := s.makeCertificate(votes) err := s.bcState.CommitBlock(block, cert) if err != nil { s.logger.Error("committing block failed", "block", block, "error", err) } else { s.logger.Info("block committed, schedule new height", "hash", block.Hash()) // Now we can announce the committed block and certificate s.announceNewBlock(block, cert, s.cpDecidedCert) } s.enterNewState(s.newHeightState) } func (*commitState) onAddVote(_ *vote.Vote) { panic("Unreachable") } func (*commitState) onSetProposal(_ *proposal.Proposal) { panic("Unreachable") } func (*commitState) onTimeout(_ *ticker) { panic("Unreachable") } func (*commitState) name() string { return "commit" } ================================================ FILE: consensusv2/config.go ================================================ package consensusv2 import ( "time" "github.com/pactus-project/pactus/types" ) // Config defines parameters for the consensusv2 algorithm. type Config struct { ChangeProposerTimeout time.Duration `toml:"-"` ChangeProposerDelta time.Duration `toml:"-"` QueryVoteTimeout time.Duration `toml:"-"` MinimumAvailabilityScore float64 `toml:"-"` } func DefaultConfig() *Config { return &Config{ ChangeProposerTimeout: 5 * time.Second, ChangeProposerDelta: 5 * time.Second, QueryVoteTimeout: 5 * time.Second, MinimumAvailabilityScore: 0.666667, // TODO: Shall not be a consensus parameter? } } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { if conf.ChangeProposerTimeout <= 0 { return ConfigError{ Reason: "change proposer timeout must be greater than zero", } } if conf.ChangeProposerDelta <= 0 { return ConfigError{ Reason: "change proposer delta must be greater than zero", } } if conf.MinimumAvailabilityScore < 0 || conf.MinimumAvailabilityScore > 1 { return ConfigError{ Reason: "minimum availability score can't be negative or more than 1", } } return nil } func (conf *Config) CalculateChangeProposerTimeout(round types.Round) time.Duration { return conf.ChangeProposerTimeout + conf.ChangeProposerDelta*time.Duration(round) } ================================================ FILE: consensusv2/config_test.go ================================================ package consensusv2 import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConfigBasicCheck(t *testing.T) { tests := []struct { name string expectedErr error updateFn func(c *Config) }{ { name: "Invalid ChangeProposerDelta", expectedErr: ConfigError{ Reason: "change proposer delta must be greater than zero", }, updateFn: func(c *Config) { c.ChangeProposerDelta = 0 }, }, { name: "Invalid ChangeProposerTimeout", expectedErr: ConfigError{ Reason: "change proposer timeout must be greater than zero", }, updateFn: func(c *Config) { c.ChangeProposerTimeout = -1 * time.Second }, }, { name: "Invalid MinimumAvailabilityScore", expectedErr: ConfigError{ Reason: "minimum availability score can't be negative or more than 1", }, updateFn: func(c *Config) { c.MinimumAvailabilityScore = 1.5 }, }, { name: "Invalid MinimumAvailabilityScore - Negative", expectedErr: ConfigError{ Reason: "minimum availability score can't be negative or more than 1", }, updateFn: func(c *Config) { c.MinimumAvailabilityScore = -0.8 }, }, { name: "DefaultConfig", updateFn: func(*Config) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() tt.updateFn(conf) if tt.expectedErr != nil { err := conf.BasicCheck() require.ErrorIs(t, tt.expectedErr, err, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } func TestConfigCalculateChangeProposerTimeout(t *testing.T) { c := DefaultConfig() assert.Equal(t, c.ChangeProposerTimeout, c.CalculateChangeProposerTimeout(0)) assert.Equal(t, c.ChangeProposerTimeout+c.ChangeProposerDelta, c.CalculateChangeProposerTimeout(1)) assert.Equal(t, c.ChangeProposerTimeout+(4*c.ChangeProposerDelta), c.CalculateChangeProposerTimeout(4)) } ================================================ FILE: consensusv2/consensus.go ================================================ package consensusv2 import ( "context" "fmt" "sync" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/ezex-io/gopkg/scheduler" "github.com/pactus-project/pactus/consensus" "github.com/pactus-project/pactus/consensusv2/log" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" ) type broadcaster func(crypto.Address, message.Message) type consensusV2 struct { lk sync.RWMutex ctx context.Context config *Config logger *logger.SubLogger log *log.Log validators []*validator.Validator height types.Height round types.Round valKey *bls.ValidatorKey rewardAddr crypto.Address bcState state.Facade // Blockchain state broadcaster broadcaster mediator mediator active bool cpWeakValidity hash.Hash cpDecidedCert *certificate.Certificate cpRound int16 changeProposer *changeProposer newHeightState *newHeightState proposeState *proposeState precommitState *precommitState commitState *commitState cpPreVoteState *cpPreVoteState cpMainVoteState *cpMainVoteState cpDecideState *cpDecideState currentState consState } func NewConsensus( ctx context.Context, conf *Config, bcState state.Facade, valKey *bls.ValidatorKey, rewardAddr crypto.Address, broadcastPipe pipeline.Pipeline[message.Message], mediator mediator, ) consensus.Consensus { broadcaster := func(_ crypto.Address, msg message.Message) { broadcastPipe.Send(msg) } return makeConsensus(ctx, conf, bcState, valKey, rewardAddr, broadcaster, mediator) } func makeConsensus( ctx context.Context, conf *Config, bcState state.Facade, valKey *bls.ValidatorKey, rewardAddr crypto.Address, broadcaster broadcaster, mediator mediator, ) *consensusV2 { cons := &consensusV2{ ctx: ctx, config: conf, bcState: bcState, broadcaster: broadcaster, valKey: valKey, } // Update height later, See enterNewHeight. cons.log = log.NewLog() cons.logger = logger.NewSubLogger("_consensus", cons) cons.rewardAddr = rewardAddr cons.changeProposer = &changeProposer{cons} cons.newHeightState = &newHeightState{cons} cons.proposeState = &proposeState{cons} cons.precommitState = &precommitState{cons, false} cons.commitState = &commitState{cons} cons.cpPreVoteState = &cpPreVoteState{cons.changeProposer} cons.cpMainVoteState = &cpMainVoteState{cons.changeProposer} cons.cpDecideState = &cpDecideState{cons.changeProposer} cons.currentState = cons.newHeightState cons.mediator = mediator cons.height = 0 cons.round = 0 cons.active = false cons.mediator = mediator mediator.Register(cons) logger.Info("consensus instance created", "validator address", valKey.Address().String(), "reward address", rewardAddr.String()) return cons } // LogString returns a concise string representation intended for use in logs. func (cs *consensusV2) LogString() string { return fmt.Sprintf("{%s %d/%d/%s/%d}", cs.valKey.Address(), cs.height, cs.round, cs.currentState.name(), cs.cpRound) } func (cs *consensusV2) ConsensusKey() *bls.PublicKey { cs.lk.RLock() defer cs.lk.RUnlock() return cs.valKey.PublicKey() } func (cs *consensusV2) HeightRound() (types.Height, types.Round) { cs.lk.RLock() defer cs.lk.RUnlock() return cs.height, cs.round } func (cs *consensusV2) HasVote(h hash.Hash) bool { cs.lk.RLock() defer cs.lk.RUnlock() return cs.log.HasVote(h) } // AllVotes returns all valid votes inside the consensus log up to and including // the current consensus round. // Valid votes from subsequent rounds are not included. func (cs *consensusV2) AllVotes() []*vote.Vote { cs.lk.RLock() defer cs.lk.RUnlock() votes := []*vote.Vote{} for r := types.Round(0); r <= cs.round; r++ { m := cs.log.RoundMessages(r) votes = append(votes, m.AllVotes()...) } return votes } func (cs *consensusV2) enterNewState(s consState) { cs.currentState = s cs.currentState.enter() } func (cs *consensusV2) MoveToNewHeight() { cs.lk.Lock() defer cs.lk.Unlock() stateHeight := cs.bcState.LastBlockHeight() if cs.height != stateHeight+1 { cs.enterNewState(cs.newHeightState) } } func (cs *consensusV2) scheduleTimeout(duration time.Duration, height types.Height, round types.Round, target tickerTarget, ) { cs.logger.Trace("new timer scheduled ⏱️", "duration", duration, "height", height, "round", round, "target", target) ticker := &ticker{duration, height, round, target} scheduler.After(duration).Do(cs.ctx, func(context.Context) { cs.handleTimeout(ticker) }) } func (cs *consensusV2) handleTimeout(ticker *ticker) { cs.lk.Lock() defer cs.lk.Unlock() // Old tickers might be triggered now. Ignore them. if cs.height != ticker.Height || cs.round != ticker.Round { cs.logger.Trace("stale ticker", "ticker", ticker) return } cs.logger.Trace("timer expired", "ticker", ticker) cs.currentState.onTimeout(ticker) } func (cs *consensusV2) SetProposal(prop *proposal.Proposal) { cs.lk.Lock() defer cs.lk.Unlock() if !cs.active { return } if prop.Height() != cs.height { return } if prop.Round() < cs.round { cs.logger.Debug("proposal for expired round", "proposal", prop) return } roundProposal := cs.log.RoundProposal(prop.Round()) if roundProposal != nil { cs.logger.Trace("this round has proposal", "proposal", prop) return } if err := prop.BasicCheck(); err != nil { cs.logger.Warn("invalid proposal", "proposal", prop, "error", err) return } proposer := cs.proposer(prop.Round()) if err := prop.Verify(proposer.PublicKey()); err != nil { cs.logger.Warn("invalid proposer", "proposal", prop, "error", err) return } if err := cs.bcState.ValidateBlock(prop.Block(), prop.Round()); err != nil { cs.logger.Warn("invalid proposed block", "proposal", prop, "error", err) return } cs.logger.Info("proposal set", "proposal", prop) cs.log.SetRoundProposal(prop.Round(), prop) cs.currentState.onSetProposal(prop) } func (cs *consensusV2) AddVote(vte *vote.Vote) { cs.lk.Lock() defer cs.lk.Unlock() if !cs.active { return } if vte.Height() != cs.height { return } if vte.Round() < cs.round { cs.logger.Debug("vote for expired round", "vote", vte) return } if vte.Type() == vote.VoteTypeCPPreVote || vte.Type() == vote.VoteTypeCPMainVote || vte.Type() == vote.VoteTypeCPDecided { err := cs.changeProposer.cpCheckJust(vte) if err != nil { cs.logger.Error("error on adding a cp vote", "vote", vte, "error", err) return } } added, err := cs.log.AddVote(vte) if err != nil { cs.logger.Warn("error on adding a vote", "vote", vte, "error", err) } if added { cs.logger.Info("new vote added", "vote", vte) cs.currentState.onAddVote(vte) } } func (cs *consensusV2) proposer(round types.Round) *validator.Validator { return cs.bcState.Proposer(round) } func (cs *consensusV2) IsProposer() bool { cs.lk.RLock() defer cs.lk.RUnlock() return cs.isProposer() } func (cs *consensusV2) isProposer() bool { return cs.proposer(cs.round).Address() == cs.valKey.Address() } func (cs *consensusV2) signAddCPPreVote(h hash.Hash, cpRound int16, cpValue vote.CPValue, just vote.Just, ) { v := vote.NewCPPreVote(h, cs.height, cs.round, cpRound, cpValue, just, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensusV2) signAddCPMainVote(h hash.Hash, cpRound int16, cpValue vote.CPValue, just vote.Just, ) { v := vote.NewCPMainVote(h, cs.height, cs.round, cpRound, cpValue, just, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensusV2) signAddCPDecidedVote(h hash.Hash, cpRound int16, cpValue vote.CPValue, just vote.Just, ) { v := vote.NewCPDecidedVote(h, cs.height, cs.round, cpRound, cpValue, just, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensusV2) signAddPrecommitVote(h hash.Hash) { v := vote.NewPrecommitVote(h, cs.height, cs.round, cs.valKey.Address()) cs.signAddVote(v) } func (cs *consensusV2) signAddVote(vte *vote.Vote) { sig := cs.valKey.Sign(vte.SignBytes()) vte.SetSignature(sig) cs.logger.Info("our vote signed and broadcasted", "vote", vte) _, err := cs.log.AddVote(vte) if err != nil { cs.logger.Warn("error on adding our vote", "error", err, "vote", vte) } cs.broadcastVote(vte) } // queryProposal requests any missing proposal from other validators. func (cs *consensusV2) queryProposal() { cs.broadcaster(cs.valKey.Address(), message.NewQueryProposalMessage(cs.height, cs.round, cs.valKey.Address())) } // queryVote requests any missing votes from other validators. func (cs *consensusV2) queryVote() { cs.broadcaster(cs.valKey.Address(), message.NewQueryVoteMessage(cs.height, cs.round, cs.valKey.Address())) } func (cs *consensusV2) broadcastProposal(p *proposal.Proposal) { go cs.mediator.OnPublishProposal(cs, p) cs.broadcaster(cs.valKey.Address(), message.NewProposalMessage(p)) } func (cs *consensusV2) broadcastVote(v *vote.Vote) { go cs.mediator.OnPublishVote(cs, v) cs.broadcaster(cs.valKey.Address(), message.NewVoteMessage(v)) } func (cs *consensusV2) announceNewBlock(blk *block.Block, cert *certificate.Certificate, proof *certificate.Certificate, ) { go cs.mediator.OnBlockAnnounce(cs) cs.broadcaster(cs.valKey.Address(), message.NewBlockAnnounceMessage(blk, cert, proof)) } func (cs *consensusV2) makeCertificate(votes map[crypto.Address]*vote.Vote, ) *certificate.Certificate { cert := certificate.NewCertificate(cs.height, cs.round) vals := cs.validators committers := make([]int32, len(vals)) absentees := make([]int32, 0) sigs := make([]*bls.Signature, 0) for i, val := range vals { vote := votes[val.Address()] if vote != nil { sigs = append(sigs, vote.Signature()) } else { absentees = append(absentees, val.Number()) } committers[i] = val.Number() } aggSig, _ := bls.SignatureAggregate(sigs...) cert.SetSignature(committers, absentees, aggSig) return cert } // IsActive checks if the consensus is in an active state and participating in the consensus algorithm. func (cs *consensusV2) IsActive() bool { cs.lk.RLock() defer cs.lk.RUnlock() return cs.active } func (cs *consensusV2) Proposal() *proposal.Proposal { cs.lk.RLock() defer cs.lk.RUnlock() return cs.log.RoundProposal(cs.round) } func (cs *consensusV2) HandleQueryProposal(height types.Height, round types.Round) *proposal.Proposal { cs.lk.RLock() defer cs.lk.RUnlock() if !cs.active { return nil } if height != cs.height { return nil } if round != cs.round { return nil } if cs.isProposer() { return cs.log.RoundProposal(cs.round) } if cs.cpDecidedCert != nil { // It is decided not to change the proposer and the proposal is locked. // Locked proposals can be sent by all validators. // This helps prevent a situation where the proposer goes offline after proposing the block. return cs.log.RoundProposal(cs.round) } return nil } // TODO: Improve the performance? func (cs *consensusV2) HandleQueryVote(height types.Height, round types.Round) *vote.Vote { cs.lk.RLock() defer cs.lk.RUnlock() if !cs.active { return nil } if height != cs.height { return nil } votes := []*vote.Vote{} switch { case round < cs.round: // Past round: Only broadcast cp:decided votes vs := cs.log.CPDecidedVoteSet(round) votes = append(votes, vs.AllVotes()...) case round == cs.round: // Current round m := cs.log.RoundMessages(round) votes = append(votes, m.AllVotes()...) case round > cs.round: // Future round } if len(votes) == 0 { return nil } return votes[util.RandInt32(int32(len(votes)))] } func (cs *consensusV2) startChangingProposer() { // If it is not decided yet. if cs.cpDecidedCert == nil { cs.logger.Info("changing proposer started", "cpRound", cs.cpRound, "proposer", cs.proposer(cs.round).Address()) cs.enterNewState(cs.cpPreVoteState) } } func (cs *consensusV2) absoluteCommit() { prop := cs.log.RoundProposal(cs.round) if prop == nil { return } precommits := cs.log.PrecommitVoteSet(cs.round) if precommits.Has3FP1VotesFor(prop.Block().Hash()) { cs.logger.Debug("precommits has 3f+1 votes", "block", prop.Block().Hash()) cs.enterNewState(cs.commitState) } } func (*consensusV2) IsDeprecated() bool { return false } ================================================ FILE: consensusv2/consensus_test.go ================================================ package consensusv2 import ( "fmt" "testing" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "golang.org/x/exp/slices" ) const ( tIndexX = 0 tIndexY = 1 tIndexB = 2 tIndexP = 3 ) type consMessage struct { sender crypto.Address receiver crypto.Address message message.Message } type testData struct { *testsuite.TestSuite valKeys []*bls.ValidatorKey mockTxPool *txpool.MockTxPool genDoc *genesis.Genesis consX *consensusV2 // Good peer consY *consensusV2 // Good peer consB *consensusV2 // Byzantine or offline peer consP *consensusV2 // Partitioned peer network []consMessage // Network messages } func testConfig() *Config { return &Config{ ChangeProposerTimeout: 1 * time.Hour, // Disabling timers ChangeProposerDelta: 1 * time.Hour, // Disabling timers QueryVoteTimeout: 1 * time.Hour, // Disabling timers } } func setup(t *testing.T) *testData { t.Helper() return setupWithSeed(t, testsuite.GenerateSeed()) } func setupWithSeed(t *testing.T, seed int64) *testData { t.Helper() fmt.Printf("=== test %s, seed: %d\n", t.Name(), seed) ts := testsuite.NewTestSuiteFromSeed(t, seed) _, valKeys := ts.GenerateTestCommittee(4) mockTxPool := txpool.NewMockTxPool(ts.Ctrl) mockTxPool.EXPECT().SetNewSandboxAndRecheck(gomock.Any()).Return().AnyTimes() mockTxPool.EXPECT().PrepareBlockTransactions().Return(nil).AnyTimes() mockTxPool.EXPECT().HandleCommittedBlock(gomock.Any()).Return().AnyTimes() vals := make([]*validator.Validator, 4) for i, key := range valKeys { val := validator.NewValidator(key.PublicKey(), int32(i)) vals[i] = val } acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) accs := map[crypto.Address]*account.Account{crypto.TreasuryAddress: acc} params := genesis.DefaultGenesisParams() params.CommitteeSize = 4 // To prevent triggering timers before starting the tests and // avoid double entries for new heights in some tests. getTime := util.RoundNow(params.BlockIntervalInSecond). Add(time.Duration(params.BlockIntervalInSecond) * time.Second) genDoc := genesis.MakeGenesis(getTime, accs, vals, params) eventPipe := pipeline.New[any](t.Context()) stateX, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexX]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) stateY, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexY]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) stateB, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexB]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) stateP, err := state.LoadOrNewState(genDoc, []*bls.ValidatorKey{valKeys[tIndexP]}, store.MockingStore(ts), mockTxPool, eventPipe) require.NoError(t, err) network := make([]consMessage, 0) td := &testData{ TestSuite: ts, valKeys: valKeys, mockTxPool: mockTxPool, genDoc: genDoc, network: network, } broadcasterFunc := func(sender crypto.Address, msg message.Message) { for _, key := range valKeys { td.network = append(td.network, consMessage{ sender: sender, receiver: key.Address(), message: msg, }) } } td.consX = makeConsensus(t.Context(), testConfig(), stateX, valKeys[tIndexX], valKeys[tIndexX].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) td.consY = makeConsensus(t.Context(), testConfig(), stateY, valKeys[tIndexY], valKeys[tIndexY].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) td.consB = makeConsensus(t.Context(), testConfig(), stateB, valKeys[tIndexB], valKeys[tIndexB].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) td.consP = makeConsensus(t.Context(), testConfig(), stateP, valKeys[tIndexP], valKeys[tIndexP].PublicKey().AccountAddress(), broadcasterFunc, newConcreteMediator()) // ------------------------------- // Better logging during testing overrideLogger := func(cons *consensusV2, name string) { cons.logger = logger.NewSubLogger("_consensus", testsuite.NewOverrideLogStringer(fmt.Sprintf("%s - %s: ", name, t.Name()), cons)) } overrideLogger(td.consX, "consX") overrideLogger(td.consY, "consY") overrideLogger(td.consB, "consB") overrideLogger(td.consP, "consP") // ------------------------------- logger.Info("setup finished, start running the test", "name", t.Name()) return td } func (td *testData) shouldNotPublish(t *testing.T, cons *consensusV2, msgType message.Type) { t.Helper() for _, consMsg := range td.network { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == msgType { require.Fail(t, fmt.Sprintf("should not publish %s", msgType)) } } } func (td *testData) shouldPublishBlockAnnounce(t *testing.T, cons *consensusV2, hash hash.Hash) { t.Helper() for _, consMsg := range td.network { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeBlockAnnounce { m := consMsg.message.(*message.BlockAnnounceMessage) assert.Equal(t, hash, m.Block.Hash()) return } } require.Fail(t, fmt.Sprintf("should publish block announce for block hash %s", hash)) } func (td *testData) shouldPublishProposal(t *testing.T, cons *consensusV2, height types.Height, round types.Round, ) *proposal.Proposal { t.Helper() for _, consMsg := range td.network { if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeProposal { m := consMsg.message.(*message.ProposalMessage) require.Equal(t, height, m.Proposal.Height()) require.Equal(t, round, m.Proposal.Round()) return m.Proposal } } require.Fail(t, fmt.Sprintf("should publish proposal for height %d and round %d", height, round)) return nil } func (td *testData) shouldPublishQueryProposal(t *testing.T, cons *consensusV2, height types.Height, round types.Round, ) { t.Helper() for _, consMsg := range td.network { if consMsg.sender != cons.valKey.Address() || consMsg.message.Type() != message.TypeQueryProposal { continue } m := consMsg.message.(*message.QueryProposalMessage) assert.Equal(t, m.Height, height) assert.Equal(t, m.Round, round) assert.Equal(t, m.Querier, cons.valKey.Address()) return } require.Fail(t, fmt.Sprintf("should publish query proposal message for height %d and round %d", height, round)) } func (td *testData) shouldPublishQueryVote(t *testing.T, cons *consensusV2, height types.Height, round types.Round) { t.Helper() for _, consMsg := range td.network { if consMsg.sender != cons.valKey.Address() || consMsg.message.Type() != message.TypeQueryVote { continue } m := consMsg.message.(*message.QueryVoteMessage) assert.Equal(t, m.Height, height) assert.Equal(t, m.Round, round) assert.Equal(t, m.Querier, cons.valKey.Address()) return } require.Fail(t, fmt.Sprintf("should publish query vote message for height %d and round %d", height, round)) } func (td *testData) shouldPublishVote(t *testing.T, cons *consensusV2, voteType vote.Type, hash hash.Hash) *vote.Vote { t.Helper() for i := len(td.network) - 1; i >= 0; i-- { consMsg := td.network[i] if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeVote { m := consMsg.message.(*message.VoteMessage) if m.Vote.Type() == voteType && m.Vote.BlockHash() == hash { return m.Vote } } } require.Fail(t, fmt.Sprintf("should publish %s vote for block hash %s", voteType, hash)) return nil } func (*testData) checkHeightRound(t *testing.T, cons *consensusV2, height types.Height, round types.Round) { t.Helper() h, r := cons.HeightRound() assert.Equal(t, h, height) assert.Equal(t, r, round) } func (td *testData) addPrecommitVote(t *testing.T, cons *consensusV2, blockHash hash.Hash, height types.Height, round types.Round, valID int, ) *vote.Vote { t.Helper() v := vote.NewPrecommitVote(blockHash, height, round, td.valKeys[valID].Address()) return td.addVote(t, cons, v, valID) } func (td *testData) addCPPreVote(t *testing.T, cons *consensusV2, blockHash hash.Hash, height types.Height, round types.Round, cpVal vote.CPValue, just vote.Just, valID int, ) *vote.Vote { t.Helper() v := vote.NewCPPreVote(blockHash, height, round, 0, cpVal, just, td.valKeys[valID].Address()) return td.addVote(t, cons, v, valID) } func (td *testData) addCPMainVote(t *testing.T, cons *consensusV2, blockHash hash.Hash, height types.Height, round types.Round, cpVal vote.CPValue, just vote.Just, valID int, ) *vote.Vote { t.Helper() v := vote.NewCPMainVote(blockHash, height, round, 0, cpVal, just, td.valKeys[valID].Address()) return td.addVote(t, cons, v, valID) } func (td *testData) addCPDecidedVote(t *testing.T, cons *consensusV2, blockHash hash.Hash, height types.Height, round types.Round, cpVal vote.CPValue, just vote.Just, valID int, ) *vote.Vote { t.Helper() v := vote.NewCPDecidedVote(blockHash, height, round, 0, cpVal, just, td.valKeys[valID].Address()) return td.addVote(t, cons, v, valID) } func (td *testData) addVote(t *testing.T, cons *consensusV2, vote *vote.Vote, valID int) *vote.Vote { t.Helper() td.HelperSignVote(td.valKeys[valID], vote) cons.AddVote(vote) return vote } func (*testData) newHeightTimeout(cons *consensusV2) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetNewHeight}) cons.lk.Unlock() } func (*testData) queryProposalTimeout(cons *consensusV2) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetQueryProposal}) cons.lk.Unlock() } func (*testData) changeProposerTimeout(cons *consensusV2) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetChangeProposer}) cons.lk.Unlock() } func (*testData) queryVoteTimeout(cons *consensusV2) { cons.lk.Lock() cons.currentState.onTimeout(&ticker{time.Hour, cons.height, cons.round, tickerTargetQueryVote}) cons.lk.Unlock() } // enterNewHeight helps tests to enter new height safely // without scheduling new height. It boosts the test speed. func (td *testData) enterNewHeight(cons *consensusV2) { cons.lk.Lock() cons.enterNewState(cons.newHeightState) cons.lk.Unlock() td.newHeightTimeout(cons) } // enterNextRound helps tests to enter next round safely. func (*testData) enterNextRound(cons *consensusV2) { cons.lk.Lock() cons.round++ cons.enterNewState(cons.proposeState) cons.lk.Unlock() } func (td *testData) commitBlockForAllStates(t *testing.T) (*block.Block, *certificate.Certificate) { t.Helper() height := td.consX.bcState.LastBlockHeight() var err error prop := td.makeProposal(t, height+1, 0) cert := certificate.NewCertificate(height+1, 0) sb := cert.SignBytesPrecommit(prop.Block().Hash()) sigX := td.consX.valKey.Sign(sb) sigY := td.consY.valKey.Sign(sb) sigP := td.consP.valKey.Sign(sb) sig, _ := bls.SignatureAggregate(sigX, sigY, sigP) cert.SetSignature([]int32{tIndexX, tIndexY, tIndexB, tIndexP}, []int32{tIndexB}, sig) blk := prop.Block() err = td.consX.bcState.CommitBlock(blk, cert) require.NoError(t, err) err = td.consY.bcState.CommitBlock(blk, cert) require.NoError(t, err) err = td.consB.bcState.CommitBlock(blk, cert) require.NoError(t, err) err = td.consP.bcState.CommitBlock(blk, cert) require.NoError(t, err) return blk, cert } // makeProposal generates a signed and valid proposal for the given height and round. // If rewardAddr is provided, it will be used instead of the consensus instance's default reward address. func (td *testData) makeProposal(t *testing.T, height types.Height, round types.Round, rewardAddr ...crypto.Address, ) *proposal.Proposal { t.Helper() var cons *consensusV2 switch uint32(height%4) + uint32(round%4) { case 1: cons = td.consX case 2: cons = td.consY case 3: cons = td.consB case 4, 0: cons = td.consP } // Use provided reward address or fall back to consensus instance's default addr := cons.rewardAddr if len(rewardAddr) > 0 { addr = rewardAddr[0] } blk, err := cons.bcState.ProposeBlock(cons.valKey, addr) require.NoError(t, err) p := proposal.NewProposal(height, round, blk) td.HelperSignProposal(cons.valKey, p) return p } // makeChangeProposerJusts generates justifications for changing the proposer at the specified height and round. // If `proposal` is nil, it creates justifications for not changing the proposer; // otherwise, it generates justifications to change the proposer. // It returns three justifications: // // 1. `JustInitNo` if the proposal is set, or `JustInitYes` if not for the pre-vote step, // 2. `JustMainVoteNoConflict` for the main-vote step, // 3. `JustDecided` for the decided step. func (td *testData) makeChangeProposerJusts(t *testing.T, propBlockHash hash.Hash, height types.Height, round types.Round, ) (preVoteJust, mainVoteJust, decidedJust vote.Just) { t.Helper() cpRound := int16(0) // Create PreVote Justification var cpValue vote.CPValue if propBlockHash != hash.UndefHash { cpValue = vote.CPValueNo committers := make([]int32, 0, len(td.consP.validators)) sigs := make([]*bls.Signature, 0, len(td.consP.validators)) for i, val := range td.consP.validators { vote := vote.NewPrecommitVote(propBlockHash, height, round, val.Address()) signBytes := vote.SignBytes() committers = append(committers, val.Number()) sigs = append(sigs, td.valKeys[i].Sign(signBytes)) } aggSig, _ := bls.SignatureAggregate(sigs...) cert := certificate.NewCertificate(height, round) cert.SetSignature(committers, []int32{}, aggSig) preVoteJust = &vote.JustInitNo{ QCert: cert, } } else { cpValue = vote.CPValueYes preVoteJust = &vote.JustInitYes{} } // Create MainVote Justification preVoteCommitters := make([]int32, 0, len(td.consP.validators)) preVoteSigs := make([]*bls.Signature, 0, len(td.consP.validators)) for i, val := range td.consP.validators { preVote := vote.NewCPPreVote(propBlockHash, height, round, cpRound, cpValue, preVoteJust, val.Address()) signBytes := preVote.SignBytes() preVoteCommitters = append(preVoteCommitters, val.Number()) preVoteSigs = append(preVoteSigs, td.valKeys[i].Sign(signBytes)) } preVoteAggSig, _ := bls.SignatureAggregate(preVoteSigs...) certPreVote := certificate.NewCertificate(height, round) certPreVote.SetSignature(preVoteCommitters, []int32{}, preVoteAggSig) mainVoteJust = &vote.JustMainVoteNoConflict{QCert: certPreVote} // Create Decided Justification mainVoteCommitters := make([]int32, 0, len(td.consP.validators)) mainVoteSigs := make([]*bls.Signature, 0, len(td.consP.validators)) for i, val := range td.consP.validators { mainVote := vote.NewCPMainVote(propBlockHash, height, round, cpRound, cpValue, mainVoteJust, val.Address()) signBytes := mainVote.SignBytes() mainVoteCommitters = append(mainVoteCommitters, val.Number()) mainVoteSigs = append(mainVoteSigs, td.valKeys[i].Sign(signBytes)) } mainVoteAggSig, _ := bls.SignatureAggregate(mainVoteSigs...) certMainVote := certificate.NewCertificate(height, round) certMainVote.SetSignature(mainVoteCommitters, []int32{}, mainVoteAggSig) decidedJust = &vote.JustDecided{QCert: certMainVote} return preVoteJust, mainVoteJust, decidedJust } func TestStart(t *testing.T) { td := setup(t) td.consX.MoveToNewHeight() td.checkHeightRound(t, td.consX, 1, 0) } func TestNotInCommittee(t *testing.T) { td := setup(t) valKey := td.RandValKey() str := store.MockingStore(td.TestSuite) state, _ := state.LoadOrNewState(td.genDoc, []*bls.ValidatorKey{valKey}, str, td.mockTxPool, nil) pipe := pipeline.New[message.Message](t.Context()) consInst := NewConsensus(t.Context(), testConfig(), state, valKey, valKey.Address(), pipe, newConcreteMediator()) cons := consInst.(*consensusV2) td.enterNewHeight(cons) td.newHeightTimeout(cons) assert.Equal(t, "new-height", cons.currentState.name()) } func TestIsProposer(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) assert.False(t, td.consX.IsProposer()) assert.True(t, td.consY.IsProposer()) } func TestVoteWithInvalidHeight(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) vote1 := td.addPrecommitVote(t, td.consP, td.RandHash(), 1, 0, tIndexX) vote2 := td.addPrecommitVote(t, td.consP, td.RandHash(), 2, 0, tIndexX) vote3 := td.addPrecommitVote(t, td.consP, td.RandHash(), 2, 0, tIndexY) vote4 := td.addPrecommitVote(t, td.consP, td.RandHash(), 3, 0, tIndexX) require.False(t, td.consP.HasVote(vote1.Hash())) require.True(t, td.consP.HasVote(vote2.Hash())) require.True(t, td.consP.HasVote(vote3.Hash())) require.False(t, td.consP.HasVote(vote4.Hash())) } func TestConsensusAbsoluteCommit(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consX) td.checkHeightRound(t, td.consX, 2, 0) prop := td.makeProposal(t, 2, 0) td.consX.SetProposal(prop) td.shouldPublishVote(t, td.consX, vote.VoteTypePrecommit, prop.Block().Hash()) td.addPrecommitVote(t, td.consX, prop.Block().Hash(), 2, 0, tIndexY) td.addPrecommitVote(t, td.consX, prop.Block().Hash(), 2, 0, tIndexB) td.addPrecommitVote(t, td.consX, prop.Block().Hash(), 2, 0, tIndexP) td.shouldPublishBlockAnnounce(t, td.consX, prop.Block().Hash()) } func TestConsensusAddVote(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) vote1 := td.addPrecommitVote(t, td.consP, td.RandHash(), 1, 0, tIndexX) vote2 := td.addPrecommitVote(t, td.consP, td.RandHash(), 1, 2, tIndexX) vote3 := td.addPrecommitVote(t, td.consP, td.RandHash(), 1, 1, tIndexX) vote4 := td.addPrecommitVote(t, td.consP, td.RandHash(), 2, 0, tIndexX) vote5, _ := td.GenerateTestPrecommitVote(1, 0) td.consP.AddVote(vote5) assert.False(t, td.consP.HasVote(vote1.Hash())) // previous round assert.True(t, td.consP.HasVote(vote2.Hash())) // next round assert.True(t, td.consP.HasVote(vote3.Hash())) assert.False(t, td.consP.HasVote(vote4.Hash())) // valid votes for the next height assert.False(t, td.consP.HasVote(vote5.Hash())) // invalid votes assert.Equal(t, []*vote.Vote{vote3}, td.consP.AllVotes()) assert.NotContains(t, td.consP.AllVotes(), vote2) } // TestConsensusDelayedProposal tests the scenario where a node receives votes // before receiving the proposal due to network delays. func TestConsensusDelayedProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) blockHash := prop.Block().Hash() // consP receives other votes first td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexX) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexY) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexB) // consP receives proposal now td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, blockHash) td.shouldPublishBlockAnnounce(t, td.consP, blockHash) } // TestConsensusDelayedVote tests the scenario where a node receives votes // after timing out due to network delays. func TestConsensusDelayedVote(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) blockHash := prop.Block().Hash() td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, blockHash) // consP moves to change proposer state td.changeProposerTimeout(td.consP) // consP receives other votes now td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexX) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexY) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexB) td.shouldPublishBlockAnnounce(t, td.consP, blockHash) } func TestHandleQueryVote(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consP) height := types.Height(2) assert.Nil(t, td.consP.HandleQueryVote(height, 0)) // round 0 preVoteJust, mainVoteJust, decidedJust := td.makeChangeProposerJusts(t, hash.UndefHash, height, 0) r0Vote1 := td.addCPPreVote(t, td.consP, hash.UndefHash, height, 0, vote.CPValueYes, preVoteJust, tIndexY) r0Vote2 := td.addCPMainVote(t, td.consP, hash.UndefHash, height, 0, vote.CPValueYes, mainVoteJust, tIndexY) r0Vote3 := td.addCPDecidedVote(t, td.consP, hash.UndefHash, height, 0, vote.CPValueYes, decidedJust, tIndexY) // round 1 td.enterNextRound(td.consP) hash := td.RandHash() preVoteJust, mainVoteJust, decidedJust = td.makeChangeProposerJusts(t, hash, height, 1) r1Vote1 := td.addPrecommitVote(t, td.consP, td.RandHash(), height, 1, tIndexY) r1Vote2 := td.addCPPreVote(t, td.consP, hash, height, 1, vote.CPValueNo, preVoteJust, tIndexY) r1Vote3 := td.addCPMainVote(t, td.consP, hash, height, 1, vote.CPValueNo, mainVoteJust, tIndexY) r1Vote4 := td.addCPDecidedVote(t, td.consP, hash, height, 1, vote.CPValueNo, decidedJust, tIndexY) // Round 2 td.enterNextRound(td.consP) td.addPrecommitVote(t, td.consP, td.RandHash(), height, 2, tIndexY) require.True(t, td.consP.HasVote(r0Vote1.Hash())) require.True(t, td.consP.HasVote(r0Vote2.Hash())) require.True(t, td.consP.HasVote(r0Vote3.Hash())) require.True(t, td.consP.HasVote(r1Vote1.Hash())) require.True(t, td.consP.HasVote(r1Vote2.Hash())) require.True(t, td.consP.HasVote(r1Vote3.Hash())) require.True(t, td.consP.HasVote(r1Vote4.Hash())) rndVote0 := td.consP.HandleQueryVote(height, 0) assert.Equal(t, r0Vote3, rndVote0, "should send the decided vote for the round 0") rndVote1 := td.consP.HandleQueryVote(height, 1) assert.Equal(t, r1Vote4, rndVote1, "should send the decided vote for the round 1") rndVote2 := td.consP.HandleQueryVote(height, 2) assert.Equal(t, types.Round(2), rndVote2.Round(), "should send the precommit vote for the current round") rndVote3 := td.consP.HandleQueryVote(height, 3) assert.Nil(t, rndVote3, "should not send a vote for the next round") rndVote4 := td.consP.HandleQueryVote(height+1, 0) assert.Nil(t, rndVote4, "should not have a vote for the next height") } func TestHandleQueryProposal(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) // Round 1 td.enterNextRound(td.consX) td.enterNextRound(td.consY) // consY is the proposer td.consX.SetProposal(td.consY.Proposal()) height := types.Height(1) round := types.Round(1) prop0 := td.consY.HandleQueryProposal(height, round-1) assert.Nil(t, prop0, "proposer should not send a proposal for the previous round") prop1 := td.consX.HandleQueryProposal(height, round) assert.Nil(t, prop1, "non-proposer should not send a proposal") prop2 := td.consY.HandleQueryProposal(height, round) assert.NotNil(t, prop2, "proposer should send a proposal") td.consX.cpDecidedCert = td.GenerateTestCertificate(1) // TODO: better way? prop3 := td.consX.HandleQueryProposal(height, round) assert.NotNil(t, prop3, "non-proposer should send a proposal on decided proposal") prop4 := td.consX.HandleQueryProposal(height+1, 0) assert.Nil(t, prop4, "should not have a proposal for the next height") } func TestSetProposalFromPreviousRound(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) // It should ignore proposals for previous rounds prop := td.makeProposal(t, 1, 0) td.consP.SetProposal(prop) assert.Nil(t, td.consP.Proposal()) td.checkHeightRound(t, td.consP, 1, 1) } func TestSetProposalFromPreviousHeight(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 td.enterNewHeight(td.consP) prop := td.makeProposal(t, 1, 0) td.consP.SetProposal(prop) assert.Nil(t, td.consP.Proposal()) td.checkHeightRound(t, td.consP, 2, 0) } func TestDoubleProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) height := types.Height(4) round := types.Round(0) prop1 := td.makeProposal(t, height, round, td.RandAccAddress()) prop2 := td.makeProposal(t, height, round, td.RandAccAddress()) assert.NotEqual(t, prop1.Hash(), prop2.Hash()) td.consX.SetProposal(prop1) td.consX.SetProposal(prop2) assert.Equal(t, td.consX.Proposal().Hash(), prop1.Hash()) } func TestNonActiveValidator(t *testing.T) { td := setup(t) valKey := td.RandValKey() pipe := pipeline.New[message.Message](t.Context()) consInst := NewConsensus(t.Context(), testConfig(), state.MockingState(td.TestSuite), valKey, valKey.Address(), pipe, newConcreteMediator()) nonActiveCons := consInst.(*consensusV2) t.Run("non-active instances should be in new-height state", func(t *testing.T) { nonActiveCons.MoveToNewHeight() td.newHeightTimeout(nonActiveCons) td.checkHeightRound(t, nonActiveCons, 1, 0) // Double entry nonActiveCons.MoveToNewHeight() td.newHeightTimeout(nonActiveCons) td.checkHeightRound(t, nonActiveCons, 1, 0) assert.False(t, nonActiveCons.IsActive()) assert.Equal(t, "new-height", nonActiveCons.currentState.name()) }) t.Run("non-active instances should ignore proposals", func(t *testing.T) { prop := td.makeProposal(t, 1, 0) nonActiveCons.SetProposal(prop) assert.Nil(t, nonActiveCons.Proposal()) }) t.Run("non-active instances should ignore votes", func(t *testing.T) { v := td.addPrecommitVote(t, nonActiveCons, td.RandHash(), 1, 0, tIndexX) assert.False(t, nonActiveCons.HasVote(v.Hash())) }) t.Run("non-active instances should move to new height", func(t *testing.T) { b1, cert1 := td.commitBlockForAllStates(t) nonActiveCons.MoveToNewHeight() td.checkHeightRound(t, nonActiveCons, 1, 0) require.NoError(t, nonActiveCons.bcState.CommitBlock(b1, cert1)) nonActiveCons.MoveToNewHeight() td.newHeightTimeout(nonActiveCons) td.checkHeightRound(t, nonActiveCons, 2, 0) }) } func TestVoteWithBigRound(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) vote := td.addPrecommitVote(t, td.consX, td.RandHash(), 1, types.Round(util.MaxInt16), tIndexB) assert.True(t, td.consX.HasVote(vote.Hash())) } func TestProposalWithBigRound(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) prop := td.makeProposal(t, 1, types.Round(util.MaxInt16)) td.consP.SetProposal(prop) assert.Nil(t, td.consP.Proposal()) } func TestInvalidProposal(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) prop := td.makeProposal(t, 1, 0) prop.SetSignature(nil) // Make proposal invalid td.consP.SetProposal(prop) assert.Nil(t, td.consP.Proposal()) } // TestCases runs some special cases to test the consensus algorithm. func TestCasesNormal(t *testing.T) { tests := []struct { seed int64 certRound types.Round description string }{ {1758015756630707317, 1, "precommit: startChangingProposer on 1f+1 pre-votes"}, {1758013793525473037, 1, "cp_prevote: has one main-vote for `yes` from previous round"}, {1758014151948449992, 0, "cp_prevote: all main-votes are `abstain` from previous round"}, {1758014780626270377, 2, "cp_mainvote: has 2f+1 pre-votes for `no`, decided on `no (biased)`"}, {1758014728375405734, 1, "cp_mainvote: has 2f+1 pre-votes for `yes`"}, {1758014840359554900, 1, "cp_mainvote: has no pre-votes quorum"}, {1758015210671486317, 2, "cp_decide: decide on `yes`"}, {1758015258023425309, 0, "cp_decide: conflicting main-votes"}, {1758015607471650150, 0, "cons.cpRound = 1, decided vote for `yes` in cpRound 0"}, } for _, tt := range tests { td := setupWithSeed(t, tt.seed) cert := td.executeConsensusNormal(t) require.Equal(t, tt.certRound, cert.Round(), "test '%s' failed. round not matched (expected %d, got %d)", tt.description, tt.certRound, cert.Round()) } } // TestConsensusNormal runs multiple iterations of the consensus process to // ensure stability and correctness across repeated executions. // If the consensus process fails in any iteration, the test will fail. // A random seed is generated for each iteration, allowing the test to be // reproduced deterministically with same seed. // This test doesn't involve any Byzantine behavior or network partitions. func TestConsensusNormal(t *testing.T) { for i := 0; i < 10; i++ { td := setup(t) td.executeConsensusNormal(t) } } func (td *testData) executeConsensusNormal(t *testing.T) *certificate.Certificate { t.Helper() td.commitBlockForAllStates(t) height := types.Height(2) td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) td.enterNewHeight(td.consB) td.enterNewHeight(td.consP) cert, err := executeConsensus(td, td.RandBool()) require.NoError(t, err) require.Equal(t, cert.Height(), height) return cert } func TestCasesByzantine(t *testing.T) { tests := []struct { seed int64 certRound types.Round description string }{ {1758019943838125552, 0, "double proposal detected"}, } for _, tt := range tests { td := setupWithSeed(t, tt.seed) cert := td.executeConsensusByzantine(t) require.Equal(t, tt.certRound, cert.Round(), "test '%s' failed. round not matched (expected %d, got %d)", tt.description, tt.certRound, cert.Round()) } } // TestConsensusByzantine tests a scenario involving a Byzantine node and a network partition. // // We have four nodes: X, Y, B, and P, which: // - B is a Byzantine node // - X, Y, and P are honest nodes // - However, P is partitioned and perceives the network through B. // // Byzantine node B acts maliciously by double proposing: // sending one proposal to X and Y, and another proposal to P. // Consensus halts because X and Y cannot reach consensus without P, // and P cannot reach consensus without X and Y. // // The network partition is healed after some time. // Once the partition is healed, honest nodes can reach consensus. // // The Byzantine node B acts maliciously by double proposing and double voting in this test. func TestConsensusByzantine(t *testing.T) { for i := 0; i < 10; i++ { td := setup(t) td.executeConsensusByzantine(t) } } func (td *testData) executeConsensusByzantine(t *testing.T) *certificate.Certificate { t.Helper() td.commitBlockForAllStates(t) td.commitBlockForAllStates(t) height := types.Height(3) round := types.Round(0) // ================================= // Byzantine node B prop1 := td.makeProposal(t, height, round, td.RandAccAddress()) prop2 := td.makeProposal(t, height, round, td.RandAccAddress()) require.NotEqual(t, prop1.Block().Hash(), prop2.Block().Hash()) require.Equal(t, td.consB.valKey.Address(), prop1.Block().Header().ProposerAddress()) require.Equal(t, td.consB.valKey.Address(), prop2.Block().Header().ProposerAddress()) // ================================= // Honest nodes X, Y td.enterNewHeight(td.consX) td.enterNewHeight(td.consY) td.consX.SetProposal(prop1) td.consY.SetProposal(prop1) voteX := td.shouldPublishVote(t, td.consX, vote.VoteTypePrecommit, prop1.Block().Hash()) voteY := td.shouldPublishVote(t, td.consY, vote.VoteTypePrecommit, prop1.Block().Hash()) // Byzantine node partitioned the network and blocked the Node P. // X and Y request to change proposer td.changeProposerTimeout(td.consX) td.changeProposerTimeout(td.consY) // X and Y are unable to progress... // ================================= // Honest node P, partitioned node td.enterNewHeight(td.consP) // P receives the second proposal td.consP.SetProposal(prop2) voteP := td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop2.Block().Hash()) // Request to change proposer td.changeProposerTimeout(td.consP) // P is unable to progress... // ================================= // Byzantine node B votes on both proposals byzVote1 := vote.NewPrecommitVote(prop1.Block().Hash(), height, round, td.consB.valKey.Address()) byzVote2 := vote.NewPrecommitVote(prop2.Block().Hash(), height, round, td.consB.valKey.Address()) td.HelperSignVote(td.consB.valKey, byzVote1) td.HelperSignVote(td.consB.valKey, byzVote2) aggSig1, _ := bls.SignatureAggregate(voteX.Signature(), voteY.Signature()) aggSig2, _ := bls.SignatureAggregate(voteP.Signature(), byzVote1.Signature()) cert1 := certificate.NewCertificate(height, round) cert1.SetSignature([]int32{tIndexX, tIndexY, tIndexB, tIndexP}, []int32{tIndexB, tIndexP}, aggSig1) cert2 := certificate.NewCertificate(height, round) cert2.SetSignature([]int32{tIndexX, tIndexY, tIndexB, tIndexP}, []int32{tIndexX, tIndexY}, aggSig2) byzVote3 := vote.NewCPPreVote(prop1.Block().Hash(), height, round, 0, vote.CPValueNo, &vote.JustInitNo{QCert: cert1}, td.consB.valKey.Address()) byzVote4 := vote.NewCPPreVote(prop2.Block().Hash(), height, round, 0, vote.CPValueNo, &vote.JustInitNo{QCert: cert2}, td.consB.valKey.Address()) td.HelperSignVote(td.consB.valKey, byzVote2) td.HelperSignVote(td.consB.valKey, byzVote3) td.consB.broadcastVote(byzVote1) td.consB.broadcastVote(byzVote2) td.consB.broadcastVote(byzVote3) td.consB.broadcastVote(byzVote4) // ================================= // Now, Partition heals fmt.Println("== Partition heals") td.checkHeightRound(t, td.consX, height, round) td.checkHeightRound(t, td.consY, height, round) td.checkHeightRound(t, td.consP, height, round) cert, err := executeConsensus(td, true) require.NoError(t, err) require.Equal(t, cert.Height(), height) return cert } // executeConsensus runs the consensus algorithm until it reaches consensus or the network is exhausted. // If `withoutByzantineNode` is true, it simulates the scenario where the Byzantine node goes offline. // It returns the certificate of the committed block if consensus is reached, // or an error if consensus is violated or cannot be reached. func executeConsensus(td *testData, withoutByzantineNode bool) ( *certificate.Certificate, error, ) { instances := []*consensusV2{td.consX, td.consY, td.consB, td.consP} if withoutByzantineNode { // remove byzantine node (Byzantine node goes offline) instances = []*consensusV2{td.consX, td.consY, td.consP} } // 50% chance for the first proposal to be lost, // then decrease the chance by 5% for each iteration. changeProposerChance := 50 blockAnnounces := map[crypto.Address]*message.BlockAnnounceMessage{} for len(td.network) > 0 { rndIndex := td.RandIntMax(len(td.network)) rndMsg := td.network[rndIndex] td.network = slices.Delete(td.network, rndIndex, rndIndex+1) switch rndMsg.message.Type() { case message.TypeVote: m := rndMsg.message.(*message.VoteMessage) for _, cons := range instances { if cons.valKey.Address() == rndMsg.receiver { cons.AddVote(m.Vote) } } case message.TypeProposal: m := rndMsg.message.(*message.ProposalMessage) for _, cons := range instances { if cons.valKey.Address() == rndMsg.receiver { cons.SetProposal(m.Proposal) } } case message.TypeQueryProposal: m := rndMsg.message.(*message.QueryProposalMessage) for _, cons := range instances { p := cons.HandleQueryProposal(m.Height, m.Round) if p != nil { td.network = append(td.network, consMessage{ sender: cons.valKey.Address(), message: message.NewProposalMessage(p), }) } } case message.TypeQueryVote: // To make the test reproducible, we ignore the QueryVote message. // This is because QueryVote returns a random vote that can make the test non-reproducible. case message.TypeBlockAnnounce: m := rndMsg.message.(*message.BlockAnnounceMessage) blockAnnounces[rndMsg.sender] = m case message.TypeHello, message.TypeHelloAck, message.TypeTransaction, message.TypeBlocksRequest, message.TypeBlocksResponse: // } for _, cons := range instances { rnd := td.RandIntMax(100) if rnd < changeProposerChance || len(td.network) == 0 { td.changeProposerTimeout(cons) } } changeProposerChance -= 5 } // Verify whether more than (1f+1) nodes have committed to the same block. if len(blockAnnounces) >= 2 { var firstAnnounce *message.BlockAnnounceMessage for _, msg := range blockAnnounces { if firstAnnounce == nil { firstAnnounce = msg } else if msg.Block.Hash() != firstAnnounce.Block.Hash() { return nil, fmt.Errorf("consensus violated, seed %v", td.TestSuite.Seed) } } // everything is ok return firstAnnounce.Certificate, nil } return nil, fmt.Errorf("unable to reach consensus, seed %v", td.TestSuite.Seed) } ================================================ FILE: consensusv2/cp.go ================================================ package consensusv2 import ( "fmt" "slices" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type changeProposer struct { *consensusV2 } func (*changeProposer) onSetProposal(_ *proposal.Proposal) { // Ignore proposal } func (cp *changeProposer) onTimeout(t *ticker) { if t.Target == tickerTargetQueryVote { cp.queryVote() cp.scheduleTimeout(t.Duration*2, cp.height, cp.round, tickerTargetQueryVote) } } func (*changeProposer) cpCheckCPValue(value vote.CPValue, allowedValues ...vote.CPValue) error { if slices.Contains(allowedValues, value) { return nil } return InvalidJustificationError{ Reason: fmt.Sprintf("invalid value: %v", value), } } func (cp *changeProposer) cpCheckJustInitNo(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustInitNo) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } if cpRound != 0 { return InvalidJustificationError{ Reason: fmt.Sprintf("invalid round: %v", cpRound), } } err := cp.cpCheckCPValue(cpValue, vote.CPValueNo) if err != nil { return err } err = j.QCert.ValidatePrecommit(cp.validators, blockHash) if err != nil { return err } return nil } func (cp *changeProposer) cpCheckJustInitYes(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { _, ok := just.(*vote.JustInitYes) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } if cpRound != 0 { return InvalidJustificationError{ Reason: fmt.Sprintf("invalid round: %v", cpRound), } } err := cp.cpCheckCPValue(cpValue, vote.CPValueYes) if err != nil { return err } if !blockHash.IsUndef() { return InvalidJustificationError{ Reason: fmt.Sprintf("invalid block hash: %s", blockHash), } } return nil } func (cp *changeProposer) cpCheckJustPreVoteHard(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustPreVoteHard) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } if cpRound == 0 { return InvalidJustificationError{ Reason: "invalid round: 0", } } err := cp.cpCheckCPValue(cpValue, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } err = j.QCert.ValidateCPPreVote(cp.validators, blockHash, cpRound-1, byte(cpValue)) if err != nil { return InvalidJustificationError{ Reason: err.Error(), } } return nil } func (cp *changeProposer) cpCheckJustPreVoteSoft(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustPreVoteSoft) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } if cpRound == 0 { return InvalidJustificationError{ Reason: "invalid round: 0", } } err := cp.cpCheckCPValue(cpValue, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } err = j.QCert.ValidateCPMainVote(cp.validators, blockHash, cpRound-1, byte(vote.CPValueAbstain)) if err != nil { return InvalidJustificationError{ Reason: err.Error(), } } return nil } func (cp *changeProposer) cpCheckJustMainVoteNoConflict(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustMainVoteNoConflict) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } err := cp.cpCheckCPValue(cpValue, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } err = j.QCert.ValidateCPPreVote(cp.validators, blockHash, cpRound, byte(cpValue)) if err != nil { return InvalidJustificationError{ Reason: err.Error(), } } return nil } func (cp *changeProposer) cpCheckJustMainVoteConflict(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustMainVoteConflict) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } err := cp.cpCheckCPValue(cpValue, vote.CPValueAbstain) if err != nil { return err } switch j.JustNo.Type() { case vote.JustTypeInitNo: err := cp.cpCheckJustInitNo(j.JustNo, blockHash, cpRound, vote.CPValueNo) if err != nil { return err } case vote.JustTypePreVoteHard: err := cp.cpCheckJustPreVoteHard(j.JustNo, blockHash, cpRound, vote.CPValueNo) if err != nil { return err } case vote.JustTypePreVoteSoft: err := cp.cpCheckJustPreVoteSoft(j.JustNo, blockHash, cpRound, vote.CPValueNo) if err != nil { return err } case vote.JustTypeInitYes, vote.JustTypeMainVoteConflict, vote.JustTypeMainVoteNoConflict, vote.JustTypeDecided: return InvalidJustificationError{ Reason: fmt.Sprintf("unexpected justification: %s", j.JustNo.Type()), } } switch j.JustYes.Type() { case vote.JustTypeInitYes: err := cp.cpCheckJustInitYes(j.JustYes, hash.UndefHash, cpRound, vote.CPValueYes) if err != nil { return err } case vote.JustTypePreVoteHard: err := cp.cpCheckJustPreVoteHard(j.JustYes, hash.UndefHash, cpRound, vote.CPValueYes) if err != nil { return err } case vote.JustTypeInitNo, vote.JustTypePreVoteSoft, vote.JustTypeMainVoteConflict, vote.JustTypeMainVoteNoConflict, vote.JustTypeDecided: return InvalidJustificationError{ Reason: fmt.Sprintf("unexpected justification: %s", j.JustYes.Type()), } } return nil } func (cp *changeProposer) cpCheckJustDecide(just vote.Just, blockHash hash.Hash, cpRound int16, cpValue vote.CPValue, ) error { j, ok := just.(*vote.JustDecided) if !ok { return InvalidJustificationError{ Reason: "invalid just data", } } err := cp.cpCheckCPValue(cpValue, vote.CPValueNo, vote.CPValueYes) if err != nil { return err } err = j.QCert.ValidateCPMainVote(cp.validators, blockHash, cpRound, byte(cpValue)) if err != nil { return InvalidJustificationError{ Reason: err.Error(), } } return nil } func (cp *changeProposer) cpCheckJust(vte *vote.Vote) error { switch vte.CPJust().Type() { case vote.JustTypeInitYes: return cp.cpCheckJustInitYes(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypeInitNo: return cp.cpCheckJustInitNo(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypePreVoteSoft: return cp.cpCheckJustPreVoteSoft(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypePreVoteHard: return cp.cpCheckJustPreVoteHard(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypeMainVoteNoConflict: return cp.cpCheckJustMainVoteNoConflict(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypeMainVoteConflict: return cp.cpCheckJustMainVoteConflict(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) case vote.JustTypeDecided: return cp.cpCheckJustDecide(vte.CPJust(), vte.BlockHash(), vte.CPRound(), vte.CPValue()) default: panic("unreachable") } } // cpStrongTermination decides if the Change Proposer phase should be terminated. // If there is only one proper and justified `Decided` vote, the validators can // move on to the next phase. // If the `Decided` vote is for "No", then validators move to the precommit step and // wait for committing the current proposal by gathering enough precommit votes. // If the `Decided` vote is for "Yes", then the validator moves to the propose step // and starts a new round. func (cp *changeProposer) cpStrongTermination() { cpDecided := cp.log.CPDecidedVoteSet(cp.round) for cpRound := cp.cpRound; cpRound >= 0; cpRound-- { if cpDecided.HasAnyVoteFor(cpRound, vote.CPValueYes) { cp.round++ cp.enterNewState(cp.proposeState) } } } ================================================ FILE: consensusv2/cp_decide.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/vote" ) type cpDecideState struct { *changeProposer } func (s *cpDecideState) enter() { s.decide() } func (s *cpDecideState) decide() { cpMainVotes := s.log.CPMainVoteVoteSet(s.round) if cpMainVotes.Has2FP1Votes(s.cpRound) { switch { case cpMainVotes.Has2FP1VotesFor(s.cpRound, vote.CPValueNo): s.logger.Panic("unreachable state: decide on 'no (biased)' should be handled in pre-vote state") case cpMainVotes.Has2FP1VotesFor(s.cpRound, vote.CPValueYes): s.logger.Info("binary agreement decided", "value", "yes", "round", s.cpRound) // decided for yes, and proceeds to the next round votes := cpMainVotes.BinaryVotes(s.cpRound, vote.CPValueYes) cert := s.makeCertificate(votes) just := &vote.JustDecided{ QCert: cert, } s.signAddCPDecidedVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just) default: // conflicting votes s.logger.Debug("conflicting main votes", "round", s.cpRound) s.cpRound++ s.enterNewState(s.cpPreVoteState) } } s.cpStrongTermination() s.absoluteCommit() } func (s *cpDecideState) onAddVote(_ *vote.Vote) { s.decide() } func (*cpDecideState) name() string { return "cp:decide" } ================================================ FILE: consensusv2/cp_mainvote.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/vote" ) type cpMainVoteState struct { *changeProposer } func (s *cpMainVoteState) enter() { s.decide() } func (s *cpMainVoteState) decide() { s.checkForWeakValidity() s.detectDoubleProposal() cpPreVotes := s.log.CPPreVoteVoteSet(s.round) if cpPreVotes.Has2FP1Votes(s.cpRound) { switch { case cpPreVotes.Has2FP1VotesFor(s.cpRound, vote.CPValueNo): s.logger.Debug("cp: quorum for pre-votes", "value", "no") votes := cpPreVotes.BinaryVotes(s.cpRound, vote.CPValueNo) s.cpDecidedCert = s.makeCertificate(votes) s.enterNewState(s.precommitState) case cpPreVotes.Has2FP1VotesFor(s.cpRound, vote.CPValueYes): s.logger.Debug("cp: quorum for pre-votes", "value", "yes") votes := cpPreVotes.BinaryVotes(s.cpRound, vote.CPValueYes) cert := s.makeCertificate(votes) just := &vote.JustMainVoteNoConflict{ QCert: cert, } s.signAddCPMainVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just) s.enterNewState(s.cpDecideState) default: s.logger.Debug("cp: no-quorum for pre-votes", "value", "abstain") vote0 := cpPreVotes.GetRandomVote(s.cpRound, vote.CPValueNo) vote1 := cpPreVotes.GetRandomVote(s.cpRound, vote.CPValueYes) just := &vote.JustMainVoteConflict{ JustNo: vote0.CPJust(), JustYes: vote1.CPJust(), } s.signAddCPMainVote(s.cpWeakValidity, s.cpRound, vote.CPValueAbstain, just) s.enterNewState(s.cpDecideState) } } s.cpStrongTermination() s.absoluteCommit() } func (s *cpMainVoteState) checkForWeakValidity() { if s.cpWeakValidity != hash.UndefHash { return } preVotes := s.log.CPPreVoteVoteSet(s.round) randVote := preVotes.GetRandomVote(s.cpRound, vote.CPValueNo) if randVote != nil { s.cpWeakValidity = randVote.BlockHash() } } func (s *cpMainVoteState) detectDoubleProposal() { if s.cpWeakValidity == hash.UndefHash { return } roundProposal := s.log.RoundProposal(s.round) if roundProposal != nil && roundProposal.Block().Hash() != s.cpWeakValidity { s.logger.Warn("double proposal detected", "prepared", s.cpWeakValidity, "roundProposal", roundProposal.Block().Hash()) s.log.SetRoundProposal(s.round, nil) s.queryProposal() } } func (s *cpMainVoteState) onAddVote(_ *vote.Vote) { s.decide() } func (*cpMainVoteState) name() string { return "cp:main-vote" } ================================================ FILE: consensusv2/cp_prevote.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/vote" ) type cpPreVoteState struct { *changeProposer } func (s *cpPreVoteState) enter() { s.scheduleTimeout(s.config.QueryVoteTimeout, s.height, s.round, tickerTargetQueryVote) s.decide() } func (s *cpPreVoteState) decide() { if s.cpRound == 0 { s.decideFirstRound() } else { s.decideNextRounds() } s.cpStrongTermination() s.absoluteCommit() } func (s *cpPreVoteState) decideFirstRound() { if !s.precommitState.hasVoted { just := &vote.JustInitYes{} s.signAddCPPreVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just) s.enterNewState(s.cpMainVoteState) return } precommits := s.log.PrecommitVoteSet(s.round) cpPreVotes := s.log.CPPreVoteVoteSet(s.round) votedPower := cpPreVotes.VotedPower(0) + precommits.VotedPower() if !certificate.Has2FP1Power(s.log.TotalPower(), votedPower) { // Waiting for more votes... // Transition from Synchronous to Asynchronous Consensus.... return } prop := s.log.RoundProposal(s.round) if precommits.Has2FP1VotesFor(prop.Block().Hash()) { votes := precommits.BlockVotes(prop.Block().Hash()) cert := s.makeCertificate(votes) just := &vote.JustInitNo{ QCert: cert, } s.cpWeakValidity = prop.Block().Hash() s.signAddCPPreVote(s.cpWeakValidity, s.cpRound, vote.CPValueNo, just) s.enterNewState(s.cpMainVoteState) return } just := &vote.JustInitYes{} s.signAddCPPreVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just) s.enterNewState(s.cpMainVoteState) } func (s *cpPreVoteState) decideNextRounds() { cpMainVotes := s.log.CPMainVoteVoteSet(s.round) switch { case cpMainVotes.HasAnyVoteFor(s.cpRound-1, vote.CPValueNo): s.logger.Panic("unreachable state: decide on 'no (biased)' should be handled in main-vote state") case cpMainVotes.HasAnyVoteFor(s.cpRound-1, vote.CPValueYes): s.logger.Debug("cp: one main-vote for one", "b", "1") vote1 := cpMainVotes.GetRandomVote(s.cpRound-1, vote.CPValueYes) just1 := &vote.JustPreVoteHard{ QCert: vote1.CPJust().(*vote.JustMainVoteNoConflict).QCert, } s.signAddCPPreVote(hash.UndefHash, s.cpRound, vote.CPValueYes, just1) case cpMainVotes.HasAllVotesFor(s.cpRound-1, vote.CPValueAbstain): s.logger.Debug("cp: all main-votes are abstain", "b", "0 (biased)") votes := cpMainVotes.BinaryVotes(s.cpRound-1, vote.CPValueAbstain) cert := s.makeCertificate(votes) just := &vote.JustPreVoteSoft{ QCert: cert, } s.signAddCPPreVote(s.cpWeakValidity, s.cpRound, vote.CPValueNo, just) default: s.logger.Panic("unreachable state") } s.enterNewState(s.cpMainVoteState) } func (s *cpPreVoteState) onAddVote(_ *vote.Vote) { s.decide() } func (*cpPreVoteState) name() string { return "cp:pre-vote" } ================================================ FILE: consensusv2/cp_test.go ================================================ package consensusv2 import ( "fmt" "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCPChangeProposer(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) } func TestCPQueryVote(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.queryVoteTimeout(td.consP) td.shouldPublishQueryVote(t, td.consP, 2, 0) } func TestCPSetProposalAfterChangeProposer(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) prop := td.makeProposal(t, 2, 0) td.consP.SetProposal(prop) assert.NotNil(t, td.consP.Proposal()) } func TestCPChangeProposerAgreementYes(t *testing.T) { td := setup(t) height := types.Height(1) round := types.Round(0) td.enterNewHeight(td.consP) td.checkHeightRound(t, td.consP, height, round) td.changeProposerTimeout(td.consP) preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) td.addCPPreVote(t, td.consP, hash.UndefHash, height, round, vote.CPValueYes, preVote0.CPJust(), tIndexX) td.addCPPreVote(t, td.consP, hash.UndefHash, height, round, vote.CPValueYes, preVote0.CPJust(), tIndexY) mainVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPMainVote, hash.UndefHash) td.addCPMainVote(t, td.consP, hash.UndefHash, height, round, vote.CPValueYes, mainVote0.CPJust(), tIndexX) td.addCPMainVote(t, td.consP, hash.UndefHash, height, round, vote.CPValueYes, mainVote0.CPJust(), tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPDecided, hash.UndefHash) td.checkHeightRound(t, td.consP, height, round+1) } func TestCPChangeProposerAgreementNo(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 height := types.Height(2) round := types.Round(1) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) td.checkHeightRound(t, td.consP, height, round) prop := td.makeProposal(t, height, round) blockHash := prop.Block().Hash() td.consP.SetProposal(prop) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexX) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexY) td.changeProposerTimeout(td.consP) preVote0 := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, blockHash) td.addCPPreVote(t, td.consP, blockHash, height, round, vote.CPValueNo, preVote0.CPJust(), tIndexX) td.addCPPreVote(t, td.consP, blockHash, height, round, vote.CPValueNo, preVote0.CPJust(), tIndexY) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, blockHash) td.shouldPublishBlockAnnounce(t, td.consP, blockHash) td.checkHeightRound(t, td.consP, height+1, 0) } // ConsP receives all `PRE-VOTE:no` votes before receiving a proposal or precommit votes. // It should vote `PRE-VOTES:yes` but goes to the pre-commit phase. func TestCPCrashOnTestnet(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) // height 1 height := types.Height(2) round := types.Round(0) td.consP.MoveToNewHeight() blockHash := td.RandHash() just0, _, _ := td.makeChangeProposerJusts(t, blockHash, height, round) td.addCPPreVote(t, td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexX) td.addCPPreVote(t, td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexY) td.addCPPreVote(t, td.consP, blockHash, height, round, vote.CPValueNo, just0, tIndexB) td.newHeightTimeout(td.consP) td.changeProposerTimeout(td.consP) preVote := td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) assert.Equal(t, vote.CPValueYes, preVote.CPValue()) assert.Equal(t, "precommit", td.consP.currentState.name()) } func TestCPMoveToNextRoundOnDecidedVoteYes(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) hright := types.Height(1) round := types.Round(0) td.checkHeightRound(t, td.consP, hright, round) _, _, decideJust := td.makeChangeProposerJusts(t, hash.UndefHash, hright, round) td.addCPDecidedVote(t, td.consP, hash.UndefHash, hright, round, vote.CPValueYes, decideJust, tIndexX) td.checkHeightRound(t, td.consP, hright, round+1) } func TestCPInvalidJustInitYes(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) just := &vote.JustInitYes{} t.Run("invalid value: no", func(t *testing.T) { v := vote.NewCPPreVote(hash.UndefHash, height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: no", }) }) t.Run("cp-round should be 0", func(t *testing.T) { v := vote.NewCPPreVote(hash.UndefHash, height, round, 1, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid round: 1", }) }) t.Run("invalid block hash", func(t *testing.T) { blockHash := td.RandHash() v := vote.NewCPPreVote(blockHash, height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid block hash: " + blockHash.String(), }) }) } func TestCPInvalidJustInitNo(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) just := &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: yes", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: yes", }) }) t.Run("cp-round should be 0", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid round: 1", }) }) t.Run("invalid certificate", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.Error(t, err) }) } func TestCPInvalidJustPreVoteHard(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) just := &vote.JustPreVoteHard{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: abstain", }) }) t.Run("cp-round should not be 0", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid round: 0", }) }) t.Run("invalid certificate", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestCPInvalidJustPreVoteSoft(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) just := &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: abstain", }) }) t.Run("cp-round should not be 0", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid round: 0", }) }) t.Run("invalid certificate", func(t *testing.T) { v := vote.NewCPPreVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestCPInvalidJustMainVoteNoConflict(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) just := &vote.JustMainVoteNoConflict{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { v := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: abstain", }) }) t.Run("invalid certificate", func(t *testing.T) { v := vote.NewCPMainVote(td.RandHash(), height, round, 1, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } func TestCPInvalidJustMainVoteConflict(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) blockHash := td.RandHash() properJustInitNo, _, _ := td.makeChangeProposerJusts(t, blockHash, height, round) properJustInitYes := &vote.JustInitYes{} t.Run("invalid value: no", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: properJustInitNo, JustYes: properJustInitYes, } v := vote.NewCPMainVote(blockHash, height, round, 0, vote.CPValueNo, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: no", }) }) t.Run("invalid value: yes", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: properJustInitNo, JustYes: properJustInitYes, } v := vote.NewCPMainVote(blockHash, height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: yes", }) }) t.Run("invalid value: unexpected justification (JustNo)", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustInitYes{}, JustYes: properJustInitYes, } v := vote.NewCPMainVote(blockHash, height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "unexpected justification: JustInitYes", }) }) t.Run("invalid value: unexpected justification (JustYes)", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: properJustInitNo, JustYes: &vote.JustInitNo{ QCert: td.GenerateTestCertificate(height), }, } v := vote.NewCPMainVote(blockHash, height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "unexpected justification: JustInitNo", }) }) t.Run("invalid certificate - No", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: &vote.JustPreVoteSoft{ QCert: td.GenerateTestCertificate(height), }, JustYes: properJustInitYes, } v := vote.NewCPMainVote(blockHash, height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid round: 0", }) }) t.Run("invalid certificate - Yes", func(t *testing.T) { just := &vote.JustMainVoteConflict{ JustNo: properJustInitNo, JustYes: &vote.JustPreVoteHard{ QCert: td.GenerateTestCertificate(height), }, } v := vote.NewCPMainVote(blockHash, height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid round: 0", }) }) } func TestCPInvalidJustDecided(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) just := &vote.JustDecided{ QCert: td.GenerateTestCertificate(height), } t.Run("invalid value: abstain", func(t *testing.T) { v := vote.NewCPDecidedVote(td.RandHash(), height, round, 0, vote.CPValueAbstain, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: "invalid value: abstain", }) }) t.Run("invalid certificate", func(t *testing.T) { v := vote.NewCPDecidedVote(hash.UndefHash, height, round, 0, vote.CPValueYes, just, td.consB.valKey.Address()) err := td.consP.changeProposer.cpCheckJust(v) require.ErrorIs(t, err, InvalidJustificationError{ Reason: fmt.Sprintf("certificate has an unexpected committers: %v", just.QCert.Committers()), }) }) } ================================================ FILE: consensusv2/errors.go ================================================ package consensusv2 import ( "fmt" ) // InvalidJustificationError is returned when the justification for a change-proposer // vote is invalid. type InvalidJustificationError struct { Reason string } func (e InvalidJustificationError) Error() string { return fmt.Sprintf("invalid justification: %s", e.Reason) } // ConfigError is returned when the config is not valid with a descriptive Reason message. type ConfigError struct { Reason string } func (e ConfigError) Error() string { return e.Reason } ================================================ FILE: consensusv2/height.go ================================================ package consensusv2 import ( "time" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type newHeightState struct { *consensusV2 } func (s *newHeightState) enter() { s.decide() } func (s *newHeightState) decide() { sateHeight := s.bcState.LastBlockHeight() validators := s.bcState.CommitteeValidators() s.log.MoveToNewHeight(validators) s.validators = validators s.height = sateHeight + 1 s.round = 0 s.cpRound = 0 s.cpDecidedCert = nil s.cpWeakValidity = hash.UndefHash s.active = s.bcState.IsInCommittee(s.valKey.Address()) s.logger.Info("entering new height", "height", s.height, "active", s.active) sleep := time.Until(s.bcState.LastBlockTime().Add(s.bcState.Params().BlockInterval())) s.scheduleTimeout(sleep, s.height, s.round, tickerTargetNewHeight) } func (s *newHeightState) onAddVote(_ *vote.Vote) { precommits := s.log.PrecommitVoteSet(s.round) if precommits.Has2FP1Votes() { // Detect when the network majority has voted (2f+1 precommits) but the new height // timer hasn't started yet. This edge case occurs when the local system time is // lagging behind the network time, causing the scheduled timeout to be delayed. // In this scenario, we should immediately transition to the propose state rather // than waiting for the timer to expire. s.logger.Warn("network majority has voted but new-height timer has not started yet. " + "System time may be lagging behind network time.") s.enterNewState(s.proposeState) } } func (*newHeightState) onSetProposal(_ *proposal.Proposal) { // Ignore proposal } func (s *newHeightState) onTimeout(t *ticker) { if t.Target == tickerTargetNewHeight { if s.active { s.enterNewState(s.proposeState) } } } func (*newHeightState) name() string { return "new-height" } ================================================ FILE: consensusv2/height_test.go ================================================ package consensusv2 import ( "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" "github.com/stretchr/testify/assert" ) func TestNewHeightTimeout(t *testing.T) { td := setup(t) td.enterNewHeight(td.consY) td.commitBlockForAllStates(t) consState := &newHeightState{td.consY} consState.enter() // Invalid target consState.onTimeout(&ticker{Height: 2, Target: -1}) td.checkHeightRound(t, td.consY, 2, 0) consState.onTimeout(&ticker{Height: 2, Target: tickerTargetNewHeight}) td.checkHeightRound(t, td.consY, 2, 0) td.shouldPublishProposal(t, td.consY, 2, 0) } func TestNewHeightDoubleEntry(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.consX.MoveToNewHeight() td.newHeightTimeout(td.consX) // double entry and timeout td.consX.MoveToNewHeight() td.checkHeightRound(t, td.consX, 2, 0) assert.True(t, td.consX.active) assert.NotEqual(t, "new-height", td.consX.currentState.name()) } func TestNewHeightTimeBehindNetwork(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.consP.MoveToNewHeight() height := types.Height(2) round := types.Round(0) prop := td.makeProposal(t, height, round) blockHash := prop.Block().Hash() td.consP.SetProposal(prop) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexX) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexY) td.addPrecommitVote(t, td.consP, blockHash, height, round, tIndexB) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, blockHash) td.shouldPublishBlockAnnounce(t, td.consP, blockHash) } ================================================ FILE: consensusv2/log/log.go ================================================ package log import ( "github.com/pactus-project/pactus/consensusv2/voteset" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type Log struct { validators map[crypto.Address]*validator.Validator totalPower int64 roundMessages map[types.Round]*Messages } func NewLog() *Log { return &Log{ roundMessages: make(map[types.Round]*Messages, 0), } } func (log *Log) RoundMessages(round types.Round) *Messages { return log.mustGetRoundMessages(round) } func (log *Log) HasVote(h hash.Hash) bool { for _, m := range log.roundMessages { if m.HasVote(h) { return true } } return false } func (log *Log) mustGetRoundMessages(round types.Round) *Messages { msgs, ok := log.roundMessages[round] if !ok { msgs = &Messages{ precommitVotes: voteset.NewPrecommitVoteSet(round, log.totalPower, log.validators), cpPreVotes: voteset.NewCPPreVoteVoteSet(round, log.totalPower, log.validators), cpMainVotes: voteset.NewCPMainVoteVoteSet(round, log.totalPower, log.validators), cpDecidedVotes: voteset.NewCPDecidedVoteSet(round, log.totalPower, log.validators), } log.roundMessages[round] = msgs } return msgs } func (log *Log) AddVote(v *vote.Vote) (bool, error) { msgs := log.mustGetRoundMessages(v.Round()) return msgs.addVote(v) } func (log *Log) PrecommitVoteSet(round types.Round) *voteset.BlockVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.precommitVotes } func (log *Log) CPPreVoteVoteSet(round types.Round) *voteset.BinaryVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.cpPreVotes } func (log *Log) CPMainVoteVoteSet(round types.Round) *voteset.BinaryVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.cpMainVotes } func (log *Log) CPDecidedVoteSet(round types.Round) *voteset.BinaryVoteSet { msgs := log.mustGetRoundMessages(round) return msgs.cpDecidedVotes } func (log *Log) HasRoundProposal(round types.Round) bool { return log.RoundProposal(round) != nil } func (log *Log) RoundProposal(round types.Round) *proposal.Proposal { m := log.RoundMessages(round) if m == nil { return nil } return m.proposal } func (log *Log) SetRoundProposal(round types.Round, prop *proposal.Proposal) { msgs := log.mustGetRoundMessages(round) msgs.proposal = prop } func (log *Log) MoveToNewHeight(validators []*validator.Validator) { log.roundMessages = make(map[types.Round]*Messages) log.validators = make(map[crypto.Address]*validator.Validator) log.totalPower = 0 for _, val := range validators { log.totalPower += val.Power() log.validators[val.Address()] = val } } func (log *Log) CanVote(addr crypto.Address) bool { for _, val := range log.validators { if val.Address() == addr { return true } } return false } func (log *Log) TotalPower() int64 { return log.totalPower } ================================================ FILE: consensusv2/log/log_test.go ================================================ package log import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMustGetRound(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, _ := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) assert.NotNil(t, log.RoundMessages(ts.RandRound())) } func TestAddValidVote(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, valKeys := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) height := ts.RandHeight() round := ts.RandRound() precommits := log.PrecommitVoteSet(round) preVotes := log.CPPreVoteVoteSet(round) mainVotes := log.CPMainVoteVoteSet(round) decidedVotes := log.CPDecidedVoteSet(round) vote1 := vote.NewPrecommitVote(ts.RandHash(), height, round, valKeys[0].Address()) vote2 := vote.NewCPPreVote(ts.RandHash(), height, round, 0, vote.CPValueYes, &vote.JustInitYes{}, valKeys[0].Address()) vote3 := vote.NewCPMainVote(ts.RandHash(), height, round, 0, vote.CPValueYes, &vote.JustInitYes{}, valKeys[0].Address()) vote4 := vote.NewCPDecidedVote(ts.RandHash(), height, round, 0, vote.CPValueYes, &vote.JustInitYes{}, valKeys[0].Address()) for _, v := range []*vote.Vote{vote1, vote2, vote3, vote4} { ts.HelperSignVote(valKeys[0], v) added, err := log.AddVote(v) require.NoError(t, err) assert.True(t, added) } assert.True(t, log.HasVote(vote1.Hash())) assert.True(t, log.HasVote(vote2.Hash())) assert.True(t, log.HasVote(vote3.Hash())) assert.True(t, log.HasVote(vote4.Hash())) assert.False(t, log.HasVote(ts.RandHash())) assert.Contains(t, precommits.AllVotes(), vote1) assert.Contains(t, preVotes.AllVotes(), vote2) assert.Contains(t, mainVotes.AllVotes(), vote3) assert.Contains(t, decidedVotes.AllVotes(), vote4) } func TestAddInvalidVoteType(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, _ := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) data, _ := hex.DecodeString( "A7010F0218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") invVote := new(vote.Vote) err := invVote.UnmarshalCBOR(data) require.NoError(t, err) added, err := log.AddVote(invVote) require.ErrorContains(t, err, "unexpected vote type: 15") assert.False(t, added) assert.False(t, log.HasVote(invVote.Hash())) } func TestSetRoundProposal(t *testing.T) { ts := testsuite.NewTestSuite(t) height := ts.RandHeight() round := ts.RandRound() cmt, _ := ts.GenerateTestCommittee(7) prop := ts.GenerateTestProposal(height, round) log := NewLog() log.MoveToNewHeight(cmt.Validators()) log.SetRoundProposal(round, prop) assert.False(t, log.HasRoundProposal(round+1)) assert.True(t, log.HasRoundProposal(round)) assert.Nil(t, log.RoundProposal(round+1)) assert.Equal(t, prop.Hash(), log.RoundProposal(round).Hash()) } func TestCanVote(t *testing.T) { ts := testsuite.NewTestSuite(t) cmt, valKeys := ts.GenerateTestCommittee(4) log := NewLog() log.MoveToNewHeight(cmt.Validators()) addr := ts.RandAccAddress() assert.True(t, log.CanVote(valKeys[0].Address())) assert.False(t, log.CanVote(addr)) } func TestTotalPower(t *testing.T) { ts := testsuite.NewTestSuite(t) log := NewLog() assert.Zero(t, log.TotalPower()) cmt, _ := ts.GenerateTestCommittee(4) log.MoveToNewHeight(cmt.Validators()) assert.Equal(t, cmt.TotalPower(), log.TotalPower()) } ================================================ FILE: consensusv2/log/messages.go ================================================ package log import ( "fmt" "github.com/pactus-project/pactus/consensusv2/voteset" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type Messages struct { precommitVotes *voteset.BlockVoteSet // Precommit votes cpPreVotes *voteset.BinaryVoteSet // Change proposer Pre-votes cpMainVotes *voteset.BinaryVoteSet // Change proposer Main-votes cpDecidedVotes *voteset.BinaryVoteSet // Change proposer Decided-votes proposal *proposal.Proposal } func (m *Messages) addVote(vte *vote.Vote) (bool, error) { switch vte.Type() { case vote.VoteTypePrepare: // Deprecated case vote.VoteTypePrecommit: return m.precommitVotes.AddVote(vte) case vote.VoteTypeCPPreVote: return m.cpPreVotes.AddVote(vte) case vote.VoteTypeCPMainVote: return m.cpMainVotes.AddVote(vte) case vote.VoteTypeCPDecided: return m.cpDecidedVotes.AddVote(vte) } return false, fmt.Errorf("unexpected vote type: %v", vte.Type()) } func (m *Messages) HasVote(h hash.Hash) bool { votes := m.AllVotes() for _, v := range votes { if v.Hash() == h { return true } } return false } func (m *Messages) AllVotes() []*vote.Vote { precommit := m.precommitVotes.AllVotes() cpPre := m.cpPreVotes.AllVotes() cpMain := m.cpMainVotes.AllVotes() cpDecided := m.cpDecidedVotes.AllVotes() votes := make([]*vote.Vote, 0, len(precommit)+len(cpPre)+len(cpMain)+len(cpDecided)) votes = append(votes, precommit...) votes = append(votes, cpPre...) votes = append(votes, cpMain...) votes = append(votes, cpDecided...) return votes } ================================================ FILE: consensusv2/mediator.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/consensus" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) // The `mediator` interface defines a mechanism for setting proposals and votes // between independent consensus instances. type mediator interface { OnPublishProposal(from consensus.Consensus, prop *proposal.Proposal) OnPublishVote(from consensus.Consensus, vte *vote.Vote) OnBlockAnnounce(from consensus.Consensus) Register(cons consensus.Consensus) } // ConcreteMediator struct. type ConcreteMediator struct { instances []consensus.Consensus } func newConcreteMediator() mediator { return &ConcreteMediator{} } func (m *ConcreteMediator) OnPublishProposal(from consensus.Consensus, prop *proposal.Proposal) { for _, cons := range m.instances { if cons != from { cons.SetProposal(prop) } } } func (m *ConcreteMediator) OnPublishVote(from consensus.Consensus, vte *vote.Vote) { for _, cons := range m.instances { if cons != from { cons.AddVote(vte) } } } func (m *ConcreteMediator) OnBlockAnnounce(from consensus.Consensus) { for _, cons := range m.instances { if cons != from { cons.MoveToNewHeight() } } } // Register a new Consensus instance to the mediator. func (m *ConcreteMediator) Register(cons consensus.Consensus) { m.instances = append(m.instances, cons) } ================================================ FILE: consensusv2/precommit.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type precommitState struct { *consensusV2 hasVoted bool } func (s *precommitState) enter() { if s.cpDecidedCert == nil { s.hasVoted = false changeProperTimeout := s.config.CalculateChangeProposerTimeout(s.round) queryProposalTimeout := changeProperTimeout / 2 s.scheduleTimeout(queryProposalTimeout, s.height, s.round, tickerTargetQueryProposal) s.scheduleTimeout(changeProperTimeout, s.height, s.round, tickerTargetChangeProposer) } s.decide() } func (s *precommitState) decide() { s.vote() // // The block can be committed by `2f+1` votes from the committee and // the proof of the change-proposer phase. // if s.cpDecidedCert != nil { prop := s.log.RoundProposal(s.round) if prop == nil { s.queryProposal() return } precommits := s.log.PrecommitVoteSet(s.round) if !precommits.Has2FP1VotesFor(prop.Block().Hash()) { s.queryVote() return } s.enterNewState(s.commitState) } else { // // If a validator receives a set of `f+1` valid `cp:PRE-VOTE` votes for this round, // it starts changing the proposer phase, even if its timer has not expired; // This prevents it from starting the change-proposer phase too late. // cpPreVotes := s.log.CPPreVoteVoteSet(s.round) if cpPreVotes.Has1FP1VotesFor(0, vote.CPValueYes) { s.startChangingProposer() } // TODO: write test for me cpDecide := s.log.CPDecidedVoteSet(s.round) if cpDecide.Has2FP1VotesFor(s.cpRound, vote.CPValueYes) { s.startChangingProposer() } } s.absoluteCommit() } func (s *precommitState) vote() { if s.hasVoted { return } roundProposal := s.log.RoundProposal(s.round) if roundProposal == nil { s.logger.Debug("no proposal yet") return } // Everything is good s.signAddPrecommitVote(roundProposal.Block().Hash()) s.hasVoted = true } func (s *precommitState) onAddVote(_ *vote.Vote) { s.decide() } func (s *precommitState) onSetProposal(_ *proposal.Proposal) { s.decide() } func (s *precommitState) onTimeout(ticker *ticker) { switch ticker.Target { case tickerTargetQueryProposal: roundProposal := s.log.RoundProposal(s.round) if roundProposal == nil { s.queryProposal() } if s.isProposer() { s.queryVote() } // Schedule another timeout to retry querying for the proposal or votes. // This ensures that delayed or missing data doesn't cause the process to stall. s.scheduleTimeout(ticker.Duration*2, s.height, s.round, tickerTargetQueryProposal) case tickerTargetChangeProposer: s.startChangingProposer() case tickerTargetNewHeight, tickerTargetQueryVote: // Ignore it } } func (*precommitState) name() string { return "precommit" } ================================================ FILE: consensusv2/precommit_test.go ================================================ package consensusv2 import ( "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" ) func TestPrecommitStrongCommit(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) td.enterNewHeight(td.consP) prop := td.makeProposal(t, height, round) propBlockHash := prop.Block().Hash() td.addPrecommitVote(t, td.consP, propBlockHash, height, round, tIndexX) td.addPrecommitVote(t, td.consP, propBlockHash, height, round, tIndexY) td.addPrecommitVote(t, td.consP, propBlockHash, height, round, tIndexB) td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, propBlockHash) td.shouldPublishBlockAnnounce(t, td.consP, propBlockHash) td.shouldNotPublish(t, td.consP, message.TypeQueryProposal) td.shouldNotPublish(t, td.consP, message.TypeQueryVote) } func TestPrecommitQueryProposal(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) // ConsP is not the proposer for this round. td.enterNewHeight(td.consP) td.queryProposalTimeout(td.consP) td.shouldPublishQueryProposal(t, td.consP, height, round) td.shouldNotPublish(t, td.consP, message.TypeQueryVote) } func TestPrecommitQueryVote(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) // ConsY is the proposer for this round. td.enterNewHeight(td.consY) td.queryProposalTimeout(td.consY) td.shouldNotPublish(t, td.consY, message.TypeQueryProposal) td.shouldPublishQueryVote(t, td.consY, height, round) } func TestPrecommitChangeProposerTimeout(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) td.changeProposerTimeout(td.consP) td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) } func TestPrecommitChangeProposer(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) td.enterNewHeight(td.consP) prop := td.makeProposal(t, height, round) td.consP.SetProposal(prop) td.addCPPreVote(t, td.consP, hash.UndefHash, height, round, vote.CPValueYes, &vote.JustInitYes{}, tIndexX) td.addCPPreVote(t, td.consP, hash.UndefHash, height, round, vote.CPValueYes, &vote.JustInitYes{}, tIndexY) // should move to the change proposer phase, even if it has the proposal and // its timer has not expired, if it has received 1/3 of the change-proposer votes. td.shouldPublishVote(t, td.consP, vote.VoteTypeCPPreVote, hash.UndefHash) } func TestPrecommitQueryProposalWithCert(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) td.enterNewHeight(td.consP) td.consP.cpDecidedCert = td.GenerateTestCertificate(height) td.consP.currentState.decide() td.shouldPublishQueryProposal(t, td.consP, height, round) td.shouldNotPublish(t, td.consP, message.TypeQueryVote) } func TestPrecommitQueryVoteWithCert(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) height := types.Height(2) round := types.Round(0) td.enterNewHeight(td.consP) prop := td.makeProposal(t, height, round) td.consP.SetProposal(prop) td.consP.cpDecidedCert = td.GenerateTestCertificate(height) td.consP.currentState.decide() td.shouldNotPublish(t, td.consP, message.TypeQueryProposal) td.shouldPublishQueryVote(t, td.consP, height, round) } ================================================ FILE: consensusv2/propose.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type proposeState struct { *consensusV2 } func (s *proposeState) enter() { s.decide() } func (s *proposeState) decide() { proposer := s.proposer(s.round) s.cpRound = 0 s.cpDecidedCert = nil s.cpWeakValidity = hash.UndefHash // Based on PIP-19, if the Availability Score is less than the Minimum threshold, // we initiate the Change-Proposer phase. // TODO: write test for me score := s.bcState.AvailabilityScore(proposer.Number()) if score < s.config.MinimumAvailabilityScore { s.logger.Info("availability score of proposer is low", "score", score, "proposer", proposer.Address()) s.startChangingProposer() return } if proposer.Address() == s.valKey.Address() { s.logger.Info("our turn to propose", "proposer", proposer.Address()) s.createProposal(s.height, s.round) } else { s.logger.Debug("not our turn to propose", "proposer", proposer.Address()) } s.enterNewState(s.precommitState) } func (s *proposeState) createProposal(height types.Height, round types.Round) { block, err := s.bcState.ProposeBlock(s.valKey, s.rewardAddr) if err != nil { s.logger.Error("unable to propose a block!", "error", err) return } prop := proposal.NewProposal(height, round, block) sig := s.valKey.Sign(prop.SignBytes()) prop.SetSignature(sig) s.log.SetRoundProposal(round, prop) s.broadcastProposal(prop) s.logger.Info("proposal signed and broadcasted", "proposal", prop) } func (*proposeState) onAddVote(_ *vote.Vote) { panic("Unreachable") } func (*proposeState) onSetProposal(_ *proposal.Proposal) { panic("Unreachable") } func (*proposeState) onTimeout(_ *ticker) { panic("Unreachable") } func (*proposeState) name() string { return "propose" } ================================================ FILE: consensusv2/propose_test.go ================================================ package consensusv2 import ( "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestProposePublishProposal(t *testing.T) { td := setup(t) td.enterNewHeight(td.consX) p := td.shouldPublishProposal(t, td.consX, 1, 0) assert.Equal(t, td.consX.valKey.Address(), p.Block().Header().ProposerAddress()) } func TestProposeInvalidProposer(t *testing.T) { td := setup(t) td.enterNewHeight(td.consY) assert.Nil(t, td.consY.Proposal()) addr := td.consB.valKey.Address() blk, _ := td.GenerateTestBlock(1, testsuite.BlockWithProposer(addr)) invalidProp := proposal.NewProposal(1, 0, blk) td.consY.SetProposal(invalidProp) assert.Nil(t, td.consY.Proposal()) td.HelperSignProposal(td.consB.valKey, invalidProp) td.consY.SetProposal(invalidProp) assert.Nil(t, td.consY.Proposal()) } func TestProposeInvalidBlock(t *testing.T) { td := setup(t) addr := td.consB.valKey.Address() blk, _ := td.GenerateTestBlock(1, testsuite.BlockWithProposer(addr)) invProp := proposal.NewProposal(1, 2, blk) td.HelperSignProposal(td.consB.valKey, invProp) td.enterNewHeight(td.consP) td.enterNextRound(td.consP) td.enterNextRound(td.consP) td.consP.SetProposal(invProp) assert.Nil(t, td.consP.Proposal()) } func TestProposeInvalidHeight(t *testing.T) { td := setup(t) addr := td.consB.valKey.Address() blk, _ := td.GenerateTestBlock(2, testsuite.BlockWithProposer(addr)) invProp := proposal.NewProposal(2, 0, blk) td.HelperSignProposal(td.consB.valKey, invProp) td.enterNewHeight(td.consY) td.consY.SetProposal(invProp) assert.Nil(t, td.consY.Proposal()) } func TestProposeNetworkLagging(t *testing.T) { td := setup(t) td.enterNewHeight(td.consP) height := types.Height(1) round := types.Round(0) prop := td.makeProposal(t, height, round) // consP doesn't have the proposal, but it has received prepared votes from other peers td.addPrecommitVote(t, td.consP, prop.Block().Hash(), height, round, tIndexX) td.addPrecommitVote(t, td.consP, prop.Block().Hash(), height, round, tIndexY) td.queryProposalTimeout(td.consP) td.shouldPublishQueryProposal(t, td.consP, height, round) // Proposal is received now td.consP.SetProposal(prop) td.shouldPublishVote(t, td.consP, vote.VoteTypePrecommit, prop.Block().Hash()) } func TestProposeNextRound(t *testing.T) { td := setup(t) td.commitBlockForAllStates(t) td.enterNewHeight(td.consX) // Byzantine node sends proposal for the second round (his turn) even before the first round is started b, err := td.consB.bcState.ProposeBlock(td.consB.valKey, td.consB.rewardAddr) require.NoError(t, err) p := proposal.NewProposal(2, 1, b) td.HelperSignProposal(td.consB.valKey, p) td.consX.SetProposal(p) // consX accepts his proposal, but doesn't move to the next round assert.NotNil(t, td.consX.log.RoundProposal(1)) assert.Nil(t, td.consX.Proposal()) assert.Equal(t, types.Height(2), td.consX.height) assert.Equal(t, types.Round(0), td.consX.round) } ================================================ FILE: consensusv2/spec/.gitignore ================================================ *.dot *.out *.toolbox states *.tex *.dvi *.aux *.log ================================================ FILE: consensusv2/spec/Pactus.cfg ================================================ SPECIFICATION Spec CONSTANTS N = 4 F = 1 FaultyNodes = {3} MaxRound = 1 MaxCPRound = 1 INVARIANT TypeOK PROPERTY Success ================================================ FILE: consensusv2/spec/Pactus.tla ================================================ -------------------------------- MODULE Pactus -------------------------------- (***************************************************************************) (* The specification of the Pactus consensus algorithm: *) (* `^\url{https://docs.pactus.org/protocol/consensus/protocol/}^' *) (***************************************************************************) EXTENDS Integers, Sequences, FiniteSets, TLC CONSTANT \* The maximum number of rounds, limiting the range of behaviors evaluated by TLC. MaxRound, \* The maximum number of change-proposer (CP) rounds, limiting the range of behaviors evaluated by TLC. MaxCPRound, \* The total number of nodes in the network, denoted as `N` in the protocol. N, \* The maximum number of faulty nodes in the network, denoted as `F` in the protocol. F, \* The indices of faulty nodes. FaultyNodes VARIABLES \* The set of messages received by the network. network, \* The set of messages delivered to each replica. logs, \* The state of each replica in the consensus protocol. states \* Helper expressions for common values. ThreeFPlusOne == (3 * F) + 1 TwoFPlusOne == (2 * F) + 1 OneFPlusOne == (1 * F) + 1 \* A tuple containing all variables in the spec for ease of use in temporal conditions. vars == <> ASSUME \* Ensure the number of nodes is sufficient to tolerate the specified number of faults. /\ N >= ThreeFPlusOne \* Ensure that `FaultyNodes` is a valid subset of node indices. /\ FaultyNodes \subseteq 0..N-1 \* Ensure that the number of faulty nodes does not exceed the maximum allowed. /\ Cardinality(FaultyNodes) <= F \* Ensure that `MaxRound` is greater than 0. /\ MaxRound > 0 ----------------------------------------------------------------------------- (***************************************************************************) (* Helper functions *) (***************************************************************************) \* Check if the replica is the proposer for this round. \* The proposer starts with the first replica and moves to the next in the change-proposer phase. IsProposer(index) == states[index].round % N = index \* Check if a node is faulty. IsFaulty(index) == index \in FaultyNodes \* Returns a subset of `bag` where each element matches all criteria specified in `params`. SubsetOfMsgs(bag, params) == {i \in bag: \A field \in DOMAIN params: i[field] = params[field]} \* Check if the node has received at least `3f+1` PRECOMMIT votes for a proposal in the current round. HasPreCommitAbsolute(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "PRECOMMIT", round |-> states[index].round])) >= ThreeFPlusOne \* Check if the node has received at least `2f+1` PRECOMMIT votes for a proposal in the current round. HasPreCommitQuorum(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "PRECOMMIT", round |-> states[index].round])) >= TwoFPlusOne \* Check if the node has received at least `2f+1` CP:PRE-VOTE votes in the current CP round. CPHasPreVotesQuorum(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round])) >= TwoFPlusOne \* Check if the node has received at least `2f+1` CP:PRE-VOTE votes with value 1 (yes) in the current CP round. CPHasPreVotesQuorumForYes(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= TwoFPlusOne \* Check if the node has received at least `2f+1` CP:PRE-VOTE votes with value 0 (no) in the current CP round. CPHasPreVotesQuorumForNo(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 0])) >= TwoFPlusOne \* Check if the node has received at least `f+1` CP:PRE-VOTE votes with value 1 (yes) in the current CP round. CPHasPreVotesMinorityForYes(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= OneFPlusOne \* Check if the node has received both yes and no CP:PRE-VOTE votes in the current CP round. CPHasPreVotesForYesAndNo(index) == /\ Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 0])) >= 1 /\ Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= 1 \* Check if the node has received at least one CP:MAIN-VOTE with value 0 (no) in the previous CP round. CPHasOneMainVotesNoInPrvRound(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:MAIN-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round - 1, cp_val |-> 0])) > 0 \* Check if the node has received at least one CP:MAIN-VOTE with value 1 (yes) in the previous CP round. CPHasOneMainVotesYesInPrvRound(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:MAIN-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round - 1, cp_val |-> 1])) > 0 \* Check if the node has received at least `2f+1` CP:MAIN-VOTE votes with value 2 (abstain) in the previous CP round. CPAllMainVotesAbstainInPrvRound(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:MAIN-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round - 1, cp_val |-> 2])) >= TwoFPlusOne \* Check if the node has received at least `2f+1` CP:MAIN-VOTE votes in the current CP round. CPHasMainVotesQuorum(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:MAIN-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round])) >= TwoFPlusOne \* Check if the node has received at least `2f+1` CP:MAIN-VOTE votes with value 1 (yes) in the current CP round. CPHasMainVotesQuorumForYes(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:MAIN-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 1])) >= TwoFPlusOne \* Check if the node has received at least `2f+1` CP:MAIN-VOTE votes with value 2 (abstain) in the current CP round. CPHasMainVotesQuorumForAbstain(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:MAIN-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round, cp_val |-> 2])) >= TwoFPlusOne \* Check if the node has received at least one CP:DECIDED vote with value 1 (yes) in the current round. CPHasDecideVotesForYes(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "CP:DECIDED", round |-> states[index].round, cp_val |-> 1])) > 0 \* Check if the node has received a proposal in the current round. HasProposal(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "PROPOSAL", round |-> states[index].round])) > 0 \* Check if the node has sent its own PRECOMMIT vote in the current round. HasPrecommited(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "PRECOMMIT", round |-> states[index].round, index |-> index])) = 1 \* Check if the node has received an announcement message in the current round. HasAnnouncement(index) == Cardinality(SubsetOfMsgs(logs[index], [ type |-> "ANNOUNCEMENT", round |-> states[index].round])) > 0 \* Check if the proposal is committed. \* A proposal is considered committed if a super-majority of non-faulty replicas announce the same proposal. IsCommitted == LET subset == SubsetOfMsgs(network, [type |-> "ANNOUNCEMENT"]) IN /\ Cardinality(subset) >= TwoFPlusOne /\ \A m1, m2 \in subset : m1.round = m2.round ----------------------------------------------------------------------------- (***************************************************************************) (* Network functions *) (***************************************************************************) \* Simulate a replica sending a message by appending it to the `network`. \* The message is delivered to the sender's log immediately. SendMsg(msg) == /\ network' = network \cup {msg} /\ logs' = [logs EXCEPT ![msg.index] = logs[msg.index] \cup {msg}] \* Deliver a message to the specified replica's log. DeliverMsg(index) == LET undeliveredMsgs == network \ logs[index] IN IF Cardinality(undeliveredMsgs) = 0 THEN UNCHANGED <> ELSE LET msg == CHOOSE x \in undeliveredMsgs: TRUE IN /\ logs' = [logs EXCEPT ![index] = logs[index] \cup {msg}] /\ UNCHANGED <> \* Broadcast a PROPOSAL message into the network. SendProposal(index) == SendMsg([ type |-> "PROPOSAL", round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]) \* Broadcast PRECOMMIT votes into the network. SendPreCommitVote(index) == SendMsg([ type |-> "PRECOMMIT", round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]) \* Broadcast CP:PRE-VOTE votes into the network. SendCPPreVote(index, cp_val) == SendMsg([ type |-> "CP:PRE-VOTE", round |-> states[index].round, index |-> index, cp_round |-> states[index].cp_round, cp_val |-> cp_val]) \* Broadcast CP:MAIN-VOTE votes into the network. SendCPMainVote(index, cp_val) == SendMsg([ type |-> "CP:MAIN-VOTE", round |-> states[index].round, index |-> index, cp_round |-> states[index].cp_round, cp_val |-> cp_val]) \* Broadcast CP:DECIDED votes into the network. SendCPDecideVote(index, cp_val) == SendMsg([ type |-> "CP:DECIDED", round |-> states[index].round, cp_round |-> states[index].cp_round, index |-> index, cp_val |-> cp_val]) \* Broadcast ANNOUNCEMENT messages into the network. Announce(index) == SendMsg([ type |-> "ANNOUNCEMENT", round |-> states[index].round, index |-> index, cp_round |-> 0, cp_val |-> 0]) ----------------------------------------------------------------------------- (***************************************************************************) (* State transition functions *) (***************************************************************************) \* Transition to the propose state. Propose(index) == /\ ~IsFaulty(index) /\ states[index].name = "propose" /\ IF IsProposer(index) THEN SendProposal(index) ELSE UNCHANGED <> /\ states' = [states EXCEPT ![index].name = "precommit"] \* Transition to the precommit state. PreCommit(index) == /\ ~IsFaulty(index) /\ states[index].name = "precommit" /\ HasProposal(index) /\ SendPreCommitVote(index) /\ states' = states \* AbsoluteCommit checks if 3F+1 replicas voted for the proposal. AbsoluteCommit(index) == /\ ~IsFaulty(index) /\ states[index].name # "commit" \* to prevent shuttering /\ HasPreCommitAbsolute(index) /\ states' = [states EXCEPT ![index].name = "commit"] /\ UNCHANGED <> \* QuorumCommit checks if 2F+1 replicas voted for the proposal after the change-proposer phase. QuorumCommit(index) == /\ ~IsFaulty(index) /\ states[index].name = "precommit" /\ states[index].decided = TRUE /\ HasPreCommitQuorum(index) /\ states' = [states EXCEPT ![index].name = "commit"] /\ UNCHANGED <> \* Transition to the commit state. Commit(index) == /\ ~IsFaulty(index) /\ states[index].name = "commit" /\ Announce(index) /\ UNCHANGED <> \* Transition for timeout: a non-faulty replica changes the proposer if its timer expires. Timeout(index) == /\ ~IsFaulty(index) /\ states[index].name = "precommit" /\ states[index].decided = FALSE /\ \* To limit the the behaviors. \/ states[index].round < MaxRound \/ HasPreCommitQuorum(index) /\ states' = [states EXCEPT ![index].name = "cp:pre-vote"] /\ UNCHANGED <> \* Transition to the CP pre-vote state. CPPreVote(index) == /\ ~IsFaulty(index) /\ states[index].name = "cp:pre-vote" /\ IF states[index].cp_round = 0 THEN IF ~HasPrecommited(index) THEN /\ SendCPPreVote(index, 1) /\ states' = [states EXCEPT ![index].name = "cp:main-vote"] ELSE IF Cardinality( SubsetOfMsgs(logs[index], [type |-> "PRECOMMIT", round |-> states[index].round]) \cup SubsetOfMsgs(logs[index], [type |-> "CP:PRE-VOTE", round |-> states[index].round, cp_round |-> states[index].cp_round]) ) >= TwoFPlusOne THEN \* Check if there is quorum of PRECOMMIT votes IF HasPreCommitQuorum(index) THEN /\ SendCPPreVote(index, 0) /\ states' = [states EXCEPT ![index].name = "cp:main-vote"] ELSE /\ SendCPPreVote(index, 1) /\ states' = [states EXCEPT ![index].name = "cp:main-vote"] ELSE /\ UNCHANGED <> ELSE /\ \/ /\ CPHasOneMainVotesNoInPrvRound(index) /\ SendCPPreVote(index, 0) \/ /\ CPHasOneMainVotesYesInPrvRound(index) /\ SendCPPreVote(index, 1) \/ /\ CPAllMainVotesAbstainInPrvRound(index) /\ SendCPPreVote(index, 0) \* biased to zero when all votes abstain /\ states' = [states EXCEPT ![index].name = "cp:main-vote"] \* Transition to the CP main-vote state. CPMainVote(index) == /\ ~IsFaulty(index) /\ states[index].name = "cp:main-vote" /\ CPHasPreVotesQuorum(index) /\ \/ \* all votes for 0 /\ CPHasPreVotesQuorumForNo(index) /\ states' = [states EXCEPT ![index].name = "precommit", ![index].decided = TRUE] /\ UNCHANGED <> \/ \* all votes for 1 /\ CPHasPreVotesQuorumForYes(index) /\ SendCPMainVote(index, 1) /\ states' = [states EXCEPT ![index].name = "cp:decide"] \/ \* Abstain vote /\ CPHasPreVotesForYesAndNo(index) /\ SendCPMainVote(index, 2) \* Abstain /\ states' = [states EXCEPT ![index].name = "cp:decide"] \* Transition to the CP decide state. CPDecide(index) == /\ ~IsFaulty(index) /\ states[index].name = "cp:decide" /\ CPHasMainVotesQuorum(index) /\ \/ /\ CPHasMainVotesQuorumForYes(index) /\ SendCPDecideVote(index, 1) /\ states' = [states EXCEPT ![index].name = "propose", ![index].round = states[index].round + 1] \/ /\ states[index].cp_round < MaxCPRound /\ CPHasMainVotesQuorumForAbstain(index) /\ states' = [states EXCEPT ![index].name = "cp:pre-vote", ![index].cp_round = states[index].cp_round + 1] /\ UNCHANGED <> \* Transition for strong termination of Change-Proposer phase. CPStrongTerminate(index) == /\ ~IsFaulty(index) /\ \/ states[index].name = "cp:pre-vote" \/ states[index].name = "cp:main-vote" \/ states[index].name = "cp:decide" /\ \* To limit the the behaviors. IF /\ states[index].cp_round = MaxCPRound /\ HasPreCommitQuorum(index) THEN /\ states' = [states EXCEPT ![index].name = "precommit", ![index].decided = TRUE] ELSE IF CPHasDecideVotesForYes(index) THEN /\ states' = [states EXCEPT ![index].name = "propose", ![index].round = states[index].round + 1, ![index].cp_round = 0] ELSE /\ states' = states /\ UNCHANGED <> ----------------------------------------------------------------------------- \* Initial state Init == /\ network = {} /\ logs = [index \in 0..N-1 |-> {}] /\ states = [index \in 0..N-1 |-> [ name |-> "propose", decided |-> FALSE, round |-> 0, cp_round |-> 0]] \* State transition relation Next == \E index \in 0..N-1: \/ Propose(index) \/ PreCommit(index) \/ Timeout(index) \/ Commit(index) \/ AbsoluteCommit(index) \/ QuorumCommit(index) \/ CPPreVote(index) \/ CPMainVote(index) \/ CPDecide(index) \/ CPStrongTerminate(index) \/ DeliverMsg(index) \* Specification Spec == Init /\ [][Next]_vars /\ WF_vars(Next) (***************************************************************************) (* Success: All non-faulty nodes eventually commit. *) (***************************************************************************) Success == <>(IsCommitted) (***************************************************************************) (* TypeOK is the type-correctness invariant. *) (***************************************************************************) TypeOK == /\ \A index \in 0..N-1: /\ states[index].round <= MaxRound /\ states[index].cp_round <= MaxCPRound /\ states[index].round >= 0 /\ states[index].cp_round >= 0 /\ states[index].name \in {"propose", "precommit", "commit", "cp:pre-vote", "cp:main-vote", "cp:decide"} /\ states[index].decided \in {TRUE, FALSE} /\ states[index].name = "propose" /\ states[index].round > 0 => /\ Cardinality(SubsetOfMsgs(network, [ type |-> "CP:DECIDED", round |-> states[index].round-1, cp_val |-> 1])) > 0 /\ Cardinality(SubsetOfMsgs(network, [ type |-> "ANNOUNCEMENT", round |-> states[index].round-1])) = 0 /\ states[index].name = "commit" => /\ Cardinality(SubsetOfMsgs(network, [ type |-> "PRECOMMIT", round |-> states[index].round])) >= TwoFPlusOne /\ Cardinality(SubsetOfMsgs(network, [ type |-> "PROPOSAL", round |-> states[index].round])) = 1 /\ LET subset == SubsetOfMsgs(network, [type |-> "ANNOUNCEMENT"]) IN /\ \A m1, m2 \in subset : m1.round = m2.round /\ \A msg \in network: /\ msg.round <= MaxRound /\ msg.cp_round <= MaxCPRound /\ msg.round >= 0 /\ msg.cp_round >= 0 /\ msg.type \in {"PROPOSAL", "PRECOMMIT", "CP:PRE-VOTE", "CP:MAIN-VOTE", "CP:DECIDED", "ANNOUNCEMENT"} /\ msg.index \in 0..N-1 ============================================================================= ================================================ FILE: consensusv2/spec/README.md ================================================ # Consensus specification This folder contains the consensus specification for the Pactus blockchain, which is based on the TLA+ formal language. The specification defines the consensus algorithm used by the Pactus blockchain. More info can be found [here](https://docs.pactus.org/protocol/consensus/specification/) ## Model checking To run the model checker, you will need to download and install the [TLA+ Toolbox](https://lamport.azurewebsites.net/tla/toolbox.html), which includes the TLC model checker. Follow the steps below to run the TLC model checker: - Add the `Pactus.tla` spec to your TLA+ Toolbox project. - Create a new model and specify a temporal formula as `Spec`. - Specify an invariants formula as `TypeOK`. - Specify a properties formula as `Success`. - Define the required constants: - `N`: The total number of nodes (e.g. 4) - `F`: The maximum number of faulty nodes (e.g. 1) - `FaultyNodes`: the index of faulty nodes (e.g. {3}) - `MaxRound`: The maximum number of rounds (e.g. 1) - `MaxCPRound`: The maximum number of change-proposer (CP) rounds (e.g. 1) - Run the TLC checker to check the correctness of the specification: ```bash java -XX:+UseParallelGC -jar /opt/TLA+Toolbox/tla2tools.jar -config ./Pactus.cfg ./Pactus.tla -workers auto -fpmem 1 ``` ================================================ FILE: consensusv2/state.go ================================================ package consensusv2 import ( "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/vote" ) type consState interface { enter() decide() onAddVote(v *vote.Vote) onSetProposal(p *proposal.Proposal) onTimeout(t *ticker) name() string } ================================================ FILE: consensusv2/ticker.go ================================================ package consensusv2 import ( "fmt" "time" "github.com/pactus-project/pactus/types" ) type tickerTarget int const ( tickerTargetNewHeight = tickerTarget(1) tickerTargetChangeProposer = tickerTarget(2) tickerTargetQueryProposal = tickerTarget(3) tickerTargetQueryVote = tickerTarget(4) ) func (rs tickerTarget) String() string { switch rs { case tickerTargetNewHeight: return "new-height" case tickerTargetChangeProposer: return "change-proposer" case tickerTargetQueryProposal: return "query-proposal" case tickerTargetQueryVote: return "query-vote" default: return "Unknown" } } type ticker struct { Duration time.Duration Height types.Height Round types.Round Target tickerTarget } // LogString returns a concise string representation intended for use in logs. func (ti ticker) LogString() string { return fmt.Sprintf("%v@ %d/%d/%s", ti.Duration, ti.Height, ti.Round, ti.Target) } ================================================ FILE: consensusv2/voteset/binary_voteset.go ================================================ package voteset import ( "maps" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type roundVotes struct { // Each vote can have one of 3 possible values: {0,1,Abstain}. voteBoxes [3]*voteBox allVotes map[crypto.Address]*vote.Vote votedPower int64 } func newRoundVotes() *roundVotes { voteBoxes := [3]*voteBox{} voteBoxes[vote.CPValueNo] = newVoteBox() voteBoxes[vote.CPValueYes] = newVoteBox() voteBoxes[vote.CPValueAbstain] = newVoteBox() return &roundVotes{ voteBoxes: voteBoxes, allVotes: make(map[crypto.Address]*vote.Vote), votedPower: 0, } } func (rv *roundVotes) addVote(v *vote.Vote, power int64) { vb := rv.voteBoxes[v.CPValue()] vb.addVote(v, power) } type BinaryVoteSet struct { *voteSet roundVotes []*roundVotes } func NewCPPreVoteVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BinaryVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBinaryVoteSet(voteSet) } func NewCPMainVoteVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BinaryVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBinaryVoteSet(voteSet) } func NewCPDecidedVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BinaryVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBinaryVoteSet(voteSet) } func newBinaryVoteSet(voteSet *voteSet) *BinaryVoteSet { return &BinaryVoteSet{ voteSet: voteSet, roundVotes: make([]*roundVotes, 0, 1), } } func (vs *BinaryVoteSet) mustGetRoundVotes(cpRound int16) *roundVotes { for i := len(vs.roundVotes); i <= int(cpRound); i++ { rv := newRoundVotes() vs.roundVotes = append(vs.roundVotes, rv) } return vs.roundVotes[cpRound] } // AllVotes returns a list of all votes in the VoteSet. func (vs *BinaryVoteSet) AllVotes() []*vote.Vote { votes := make([]*vote.Vote, 0) for _, rv := range vs.roundVotes { for _, v := range rv.allVotes { votes = append(votes, v) } } return votes } // AddVote attempts to add a vote to the VoteSet. Returns an error if the vote is invalid. func (vs *BinaryVoteSet) AddVote(vote *vote.Vote) (bool, error) { power, err := vs.voteSet.verifyVote(vote) if err != nil { return false, err } roundVotes := vs.mustGetRoundVotes(vote.CPRound()) existingVote, ok := roundVotes.allVotes[vote.Signer()] if ok { if existingVote.Hash() == vote.Hash() { // The vote is already added return false, nil } // It is a double vote err = ErrDoubleVote } else { roundVotes.allVotes[vote.Signer()] = vote roundVotes.votedPower += power } roundVotes.addVote(vote, power) return true, err } // Has2FP1Votes checks whether the given change-proposer round has received 2f+1 votes. func (vs *BinaryVoteSet) Has2FP1Votes(cpRound int16) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return vs.has2FP1Power(roundVotes.votedPower) } // HasAnyVoteFor checks whether the given change-proposer round has received any votes for the given value. func (vs *BinaryVoteSet) HasAnyVoteFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return roundVotes.voteBoxes[cpValue].votedPower > 0 } // HasAllVotesFor checks whether the given change-proposer round has received all votes for the given value. func (vs *BinaryVoteSet) HasAllVotesFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return roundVotes.voteBoxes[cpValue].votedPower == roundVotes.votedPower } // Has1FP1VotesFor checks whether the given change-proposer round has received f+1 votes for the given value. func (vs *BinaryVoteSet) Has1FP1VotesFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return vs.has1FP1Power(roundVotes.voteBoxes[cpValue].votedPower) } // Has2FP1VotesFor checks whether the given change-proposer round has received 2f+1 votes for the given value. func (vs *BinaryVoteSet) Has2FP1VotesFor(cpRound int16, cpValue vote.CPValue) bool { roundVotes := vs.mustGetRoundVotes(cpRound) return vs.has2FP1Power(roundVotes.voteBoxes[cpValue].votedPower) } // BinaryVotes returns the votes for the given change-proposer round and value. func (vs *BinaryVoteSet) BinaryVotes(cpRound int16, cpValue vote.CPValue) map[crypto.Address]*vote.Vote { votes := map[crypto.Address]*vote.Vote{} roundVotes := vs.mustGetRoundVotes(cpRound) voteBox := roundVotes.voteBoxes[cpValue] maps.Copy(votes, voteBox.votes) return votes } // GetRandomVote returns a random vote for the given change-proposer round and value. func (vs *BinaryVoteSet) GetRandomVote(cpRound int16, cpValue vote.CPValue) *vote.Vote { roundVotes := vs.mustGetRoundVotes(cpRound) for _, v := range roundVotes.voteBoxes[cpValue].votes { return v } return nil } // VotedPower returns the total voting power of the votes for the given change-proposer round. func (vs *BinaryVoteSet) VotedPower(cpRound int16) int64 { roundVotes := vs.mustGetRoundVotes(cpRound) return roundVotes.votedPower } ================================================ FILE: consensusv2/voteset/block_voteset.go ================================================ package voteset import ( "maps" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type BlockVoteSet struct { *voteSet blockVotes map[hash.Hash]*voteBox allVotes map[crypto.Address]*vote.Vote votedPower int64 } func NewPrecommitVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *BlockVoteSet { voteSet := newVoteSet(round, totalPower, validators) return newBlockVoteSet(voteSet) } func newBlockVoteSet(voteSet *voteSet) *BlockVoteSet { return &BlockVoteSet{ voteSet: voteSet, blockVotes: make(map[hash.Hash]*voteBox), allVotes: make(map[crypto.Address]*vote.Vote), votedPower: 0, } } func (vs *BlockVoteSet) BlockVotes(blockHash hash.Hash) map[crypto.Address]*vote.Vote { votes := map[crypto.Address]*vote.Vote{} blockVotes := vs.mustGetBlockVotes(blockHash) maps.Copy(votes, blockVotes.votes) return votes } func (vs *BlockVoteSet) mustGetBlockVotes(blockHash hash.Hash) *voteBox { blockVotes, exists := vs.blockVotes[blockHash] if !exists { blockVotes = newVoteBox() vs.blockVotes[blockHash] = blockVotes } return blockVotes } // AllVotes returns a list of all votes in the VoteSet. func (vs *BlockVoteSet) AllVotes() []*vote.Vote { votes := make([]*vote.Vote, 0, len(vs.allVotes)) for _, v := range vs.allVotes { votes = append(votes, v) } return votes } // AddVote attempts to add a vote to the VoteSet. // Returns an error if the vote is invalid or if it is a double vote. func (vs *BlockVoteSet) AddVote(vote *vote.Vote) (bool, error) { power, err := vs.voteSet.verifyVote(vote) if err != nil { return false, err } existingVote, ok := vs.allVotes[vote.Signer()] if ok { if existingVote.Hash() == vote.Hash() { // The vote is already added return false, nil } // It is a double vote err = ErrDoubleVote } else { vs.allVotes[vote.Signer()] = vote vs.votedPower += power } blockVotes := vs.mustGetBlockVotes(vote.BlockHash()) blockVotes.addVote(vote, power) return true, err } // Has2FP1Votes checks whether has received 2f+1 votes. func (vs *BlockVoteSet) Has2FP1Votes() bool { return vs.has2FP1Power(vs.votedPower) } // Has3FP1VotesFor checks whether the given block has received 3f+1 votes. func (vs *BlockVoteSet) Has3FP1VotesFor(blockHash hash.Hash) bool { blockVotes := vs.mustGetBlockVotes(blockHash) return vs.has3FP1Power(blockVotes.votedPower) } // Has2FP1VotesFor checks whether the given block has received 2f+1 votes. func (vs *BlockVoteSet) Has2FP1VotesFor(blockHash hash.Hash) bool { blockVotes := vs.mustGetBlockVotes(blockHash) return vs.has2FP1Power(blockVotes.votedPower) } // Has1FP1VotesFor checks whether the given block has received f+1 votes. func (vs *BlockVoteSet) Has1FP1VotesFor(blockHash hash.Hash) bool { blockVotes := vs.mustGetBlockVotes(blockHash) return vs.has1FP1Power(blockVotes.votedPower) } // VotedPower returns the total voting power of the votes. func (vs *BlockVoteSet) VotedPower() int64 { return vs.votedPower } ================================================ FILE: consensusv2/voteset/errors.go ================================================ package voteset import ( "errors" "fmt" "github.com/pactus-project/pactus/crypto" ) // ErrDoubleVote is returned when a validator casts multiple different votes. var ErrDoubleVote = errors.New("double vote") // IneligibleVoterError is returned when the voter is not a member of the committee. type IneligibleVoterError struct { Address crypto.Address } func (e IneligibleVoterError) Error() string { return fmt.Sprintf("validator %s is not part of the committee", e.Address) } ================================================ FILE: consensusv2/voteset/vote_box.go ================================================ package voteset import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/vote" ) type voteBox struct { votes map[crypto.Address]*vote.Vote votedPower int64 } func newVoteBox() *voteBox { return &voteBox{ votes: make(map[crypto.Address]*vote.Vote), votedPower: 0, } } func (vs *voteBox) addVote(vote *vote.Vote, power int64) { if vs.votes[vote.Signer()] == nil { vs.votes[vote.Signer()] = vote vs.votedPower += power } } ================================================ FILE: consensusv2/voteset/vote_box_test.go ================================================ package voteset import ( "testing" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestDoubleVote(t *testing.T) { ts := testsuite.NewTestSuite(t) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() signer := ts.RandValAddress() power := ts.RandInt64Max(1000) v := vote.NewPrecommitVote(hash, height, round, signer) vb := newVoteBox() vb.addVote(v, power) vb.addVote(v, power) assert.Equal(t, power, vb.votedPower) } ================================================ FILE: consensusv2/voteset/voteset.go ================================================ package voteset import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type voteSet struct { round types.Round validators map[crypto.Address]*validator.Validator totalPower int64 } func newVoteSet(round types.Round, totalPower int64, validators map[crypto.Address]*validator.Validator, ) *voteSet { return &voteSet{ round: round, validators: validators, totalPower: totalPower, } } // Round returns the round number for the VoteSet. func (vs *voteSet) Round() types.Round { return vs.round } // verifyVote checks if the given vote is valid. // It returns the voting power of if valid, or an error if not. func (vs *voteSet) verifyVote(vote *vote.Vote) (int64, error) { signer := vote.Signer() val := vs.validators[signer] if val == nil { return 0, IneligibleVoterError{ Address: signer, } } if err := vote.Verify(val.PublicKey()); err != nil { return 0, err } return val.Power(), nil } // has3FP1Power checks whether the given power is greater than or equal to 3f+1, // where f is the maximum faulty power. func (vs *BlockVoteSet) has3FP1Power(power int64) bool { return certificate.Has3FP1Power(vs.totalPower, power) } // has2FP1Power checks whether the given power is greater than or equal to 2f+1, // where f is the maximum faulty power. func (vs *voteSet) has2FP1Power(power int64) bool { return certificate.Has2FP1Power(vs.totalPower, power) } // has1FP1Power checks whether the given power is greater than or equal to f+1, // where f is the maximum faulty power. func (vs *voteSet) has1FP1Power(power int64) bool { return certificate.Has1FP1Power(vs.totalPower, power) } ================================================ FILE: consensusv2/voteset/voteset_test.go ================================================ package voteset import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func setupCommittee(ts *testsuite.TestSuite, stakes ...amount.Amount) ( map[crypto.Address]*validator.Validator, []*bls.ValidatorKey, int64, ) { valKeys := make([]*bls.ValidatorKey, 0, len(stakes)) valsMap := map[crypto.Address]*validator.Validator{} totalPower := int64(0) for i, s := range stakes { pub, prv := ts.RandBLSKeyPair() val := validator.NewValidator(pub, int32(i)) val.AddToStake(s) valsMap[val.Address()] = val totalPower += val.Power() valKeys = append(valKeys, bls.NewValidatorKey(prv)) } return valsMap, valKeys, totalPower } func TestAddBlockVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash1 := ts.RandHash() hash2 := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() invKey := ts.RandValKey() valKey := valKeys[0] voteSet := NewPrecommitVoteSet(round, totalPower, valsMap) assert.Equal(t, round, voteSet.Round()) vote1 := vote.NewPrecommitVote(hash1, height, round, invKey.Address()) vote2 := vote.NewPrecommitVote(hash1, height, round, valKey.Address()) vote3 := vote.NewPrecommitVote(hash2, height, round, valKey.Address()) ts.HelperSignVote(invKey, vote1) added, err := voteSet.AddVote(vote1) require.ErrorIs(t, err, IneligibleVoterError{Address: vote1.Signer()}) // unknown validator assert.False(t, added) ts.HelperSignVote(invKey, vote2) added, err = voteSet.AddVote(vote2) require.ErrorIs(t, err, crypto.ErrInvalidSignature) assert.False(t, added) ts.HelperSignVote(valKey, vote2) added, err = voteSet.AddVote(vote2) require.NoError(t, err) // ok assert.True(t, added) added, err = voteSet.AddVote(vote2) // Adding again assert.False(t, added) require.NoError(t, err) ts.HelperSignVote(valKey, vote3) added, err = voteSet.AddVote(vote3) require.ErrorIs(t, err, ErrDoubleVote) assert.True(t, added) } func TestAddBinaryVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash1 := ts.RandHash() hash2 := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cpRound := int16(ts.RandRound()) cpVal := ts.RandIntMax(2) just := &vote.JustInitYes{} invKey := ts.RandValKey() valKey := valKeys[0] voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) vote1 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, invKey.Address()) vote2 := vote.NewCPPreVote(hash1, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) vote3 := vote.NewCPPreVote(hash2, height, round, cpRound, vote.CPValue(cpVal), just, valKey.Address()) ts.HelperSignVote(invKey, vote1) added, err := voteSet.AddVote(vote1) require.ErrorIs(t, err, IneligibleVoterError{Address: vote1.Signer()}) // unknown validator assert.False(t, added) ts.HelperSignVote(invKey, vote2) added, err = voteSet.AddVote(vote2) require.ErrorIs(t, err, crypto.ErrInvalidSignature) assert.False(t, added) ts.HelperSignVote(valKey, vote2) added, err = voteSet.AddVote(vote2) require.NoError(t, err) // ok assert.True(t, added) added, err = voteSet.AddVote(vote2) // Adding again assert.False(t, added) require.NoError(t, err) ts.HelperSignVote(valKey, vote3) added, err = voteSet.AddVote(vote3) require.ErrorIs(t, err, ErrDoubleVote) assert.True(t, added) } func TestDoubleBlockVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash1 := ts.RandHash() hash2 := ts.RandHash() hash3 := ts.RandHash() addr := valKeys[0].Address() voteSet := NewPrecommitVoteSet(0, totalPower, valsMap) correctVote := vote.NewPrecommitVote(hash1, 1, 0, addr) doubleVote1 := vote.NewPrecommitVote(hash2, 1, 0, addr) doubleVote2 := vote.NewPrecommitVote(hash3, 1, 0, addr) // sign the votes ts.HelperSignVote(valKeys[0], correctVote) ts.HelperSignVote(valKeys[0], doubleVote1) ts.HelperSignVote(valKeys[0], doubleVote2) added, err := voteSet.AddVote(correctVote) require.NoError(t, err) assert.True(t, added) added, err = voteSet.AddVote(doubleVote1) require.ErrorIs(t, err, ErrDoubleVote) assert.True(t, added) added, err = voteSet.AddVote(doubleVote2) require.ErrorIs(t, err, ErrDoubleVote) assert.True(t, added) assert.Contains(t, voteSet.AllVotes(), correctVote) assert.NotContains(t, voteSet.AllVotes(), doubleVote1) assert.NotContains(t, voteSet.AllVotes(), doubleVote2) } func TestDoubleBinaryVote(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash1 := ts.RandHash() hash2 := ts.RandHash() hash3 := ts.RandHash() addr := valKeys[0].Address() voteSet := NewCPPreVoteVoteSet(0, totalPower, valsMap) correctVote := vote.NewCPPreVote(hash1, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) doubleVote1 := vote.NewCPPreVote(hash2, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) doubleVote2 := vote.NewCPPreVote(hash3, 1, 0, 0, vote.CPValueYes, &vote.JustInitYes{}, addr) // sign the votes ts.HelperSignVote(valKeys[0], correctVote) ts.HelperSignVote(valKeys[0], doubleVote1) ts.HelperSignVote(valKeys[0], doubleVote2) added, err := voteSet.AddVote(correctVote) require.NoError(t, err) assert.True(t, added) added, err = voteSet.AddVote(doubleVote1) require.ErrorIs(t, err, ErrDoubleVote) assert.True(t, added) added, err = voteSet.AddVote(doubleVote2) require.ErrorIs(t, err, ErrDoubleVote) assert.True(t, added) assert.Contains(t, voteSet.AllVotes(), correctVote) assert.NotContains(t, voteSet.AllVotes(), doubleVote1) assert.NotContains(t, voteSet.AllVotes(), doubleVote2) } func TestAllBlockVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) voteSet := NewPrecommitVoteSet(1, totalPower, valsMap) vote1 := vote.NewPrecommitVote(ts.RandHash(), 1, 1, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(ts.RandHash(), 1, 1, valKeys[1].Address()) vote3 := vote.NewPrecommitVote(ts.RandHash(), 1, 1, valKeys[2].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) assert.Empty(t, voteSet.AllVotes()) _, _ = voteSet.AddVote(vote1) _, _ = voteSet.AddVote(vote2) _, _ = voteSet.AddVote(vote3) assert.Contains(t, voteSet.AllVotes(), vote1) assert.Contains(t, voteSet.AllVotes(), vote2) assert.Contains(t, voteSet.AllVotes(), vote3) } func TestAllBinaryVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) voteSet := NewCPMainVoteVoteSet(1, totalPower, valsMap) vote1 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 0, vote.CPValueNo, &vote.JustInitYes{}, valKeys[0].Address()) vote2 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 1, vote.CPValueYes, &vote.JustInitYes{}, valKeys[1].Address()) vote3 := vote.NewCPMainVote(hash.UndefHash, 1, 1, 2, vote.CPValueAbstain, &vote.JustInitYes{}, valKeys[2].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) assert.Empty(t, voteSet.AllVotes()) _, _ = voteSet.AddVote(vote1) _, _ = voteSet.AddVote(vote2) _, _ = voteSet.AddVote(vote3) assert.Contains(t, voteSet.AllVotes(), vote1) assert.Contains(t, voteSet.AllVotes(), vote2) assert.Contains(t, voteSet.AllVotes(), vote3) ranVote1 := voteSet.GetRandomVote(1, vote.CPValueNo) assert.Nil(t, ranVote1) ranVote2 := voteSet.GetRandomVote(1, vote.CPValueYes) assert.Equal(t, vote2, ranVote2) } func TestBlockQuorumVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) // N = 30 (5+6+8+11) // f = 9 // 1f+1 = 10 // 2f+1 = 19 // 3f+1 = 28 valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) voteSet := NewPrecommitVoteSet(0, totalPower, valsMap) blockHash := ts.RandHash() vote1 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[1].Address()) vote3 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[2].Address()) vote4 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[3].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) ts.HelperSignVote(valKeys[3], vote4) _, _ = voteSet.AddVote(vote1) assert.False(t, voteSet.Has1FP1VotesFor(blockHash)) // Add more votes _, _ = voteSet.AddVote(vote2) assert.True(t, voteSet.Has1FP1VotesFor(blockHash)) assert.False(t, voteSet.Has2FP1VotesFor(blockHash)) // Add more votes _, _ = voteSet.AddVote(vote3) assert.True(t, voteSet.Has2FP1VotesFor(blockHash)) assert.False(t, voteSet.Has3FP1VotesFor(blockHash)) // Add more votes _, _ = voteSet.AddVote(vote4) assert.True(t, voteSet.Has3FP1VotesFor(blockHash)) } func TestBinaryQuorumVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) // N = 30 (5+6+8+11) // f = 9 // 1f+1 = 10 // 2f+1 = 19 // 3f+1 = 28 valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) vote1 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) vote2 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[1].Address()) vote3 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[2].Address()) vote4 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[3].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) ts.HelperSignVote(valKeys[3], vote4) _, _ = voteSet.AddVote(vote1) assert.False(t, voteSet.Has1FP1VotesFor(0, vote.CPValueNo)) assert.False(t, voteSet.Has1FP1VotesFor(0, vote.CPValueYes)) assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueAbstain)) // Add more votes _, _ = voteSet.AddVote(vote2) assert.True(t, voteSet.Has1FP1VotesFor(0, vote.CPValueYes)) assert.False(t, voteSet.Has2FP1VotesFor(0, vote.CPValueYes)) // Add more votes _, _ = voteSet.AddVote(vote3) assert.True(t, voteSet.Has2FP1VotesFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasAllVotesFor(0, vote.CPValueNo)) assert.True(t, voteSet.HasAllVotesFor(0, vote.CPValueYes)) // Add more votes _, _ = voteSet.AddVote(vote4) assert.True(t, voteSet.HasAllVotesFor(0, vote.CPValueYes)) } func TestBlockVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() voteSet := NewPrecommitVoteSet(round, totalPower, valsMap) vote1 := vote.NewPrecommitVote(hash, height, round, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(hash, height, round, valKeys[1].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) _, _ = voteSet.AddVote(vote1) _, _ = voteSet.AddVote(vote2) bv := voteSet.BlockVotes(hash) assert.Contains(t, bv, vote1.Signer()) assert.Contains(t, bv, vote2.Signer()) } func TestBinaryVotes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) vote1 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) vote2 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueNo, just, valKeys[1].Address()) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) _, _ = voteSet.AddVote(vote1) _, _ = voteSet.AddVote(vote2) bv1 := voteSet.BinaryVotes(0, vote.CPValueYes) assert.Contains(t, bv1, vote1.Signer()) assert.NotContains(t, bv1, vote2.Signer()) bv2 := voteSet.BinaryVotes(0, vote.CPValueNo) assert.NotContains(t, bv2, vote1.Signer()) assert.Contains(t, bv2, vote2.Signer()) } func TestDecidedVoteset(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} voteSet := NewCPDecidedVoteSet(round, totalPower, valsMap) vte := vote.NewCPDecidedVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) ts.HelperSignVote(valKeys[0], vte) _, err := voteSet.AddVote(vte) require.NoError(t, err) assert.True(t, voteSet.HasAnyVoteFor(0, vote.CPValueYes)) assert.False(t, voteSet.HasAnyVoteFor(0, vote.CPValueNo)) } func TestBlockVotedPower(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) height := ts.RandHeight() round := ts.RandRound() voteSet := NewPrecommitVoteSet(round, totalPower, valsMap) hash1 := ts.RandHash() hash2 := ts.RandHash() vote1a := vote.NewPrecommitVote(hash1, height, round, valKeys[0].Address()) vote1b := vote.NewPrecommitVote(hash2, height, round, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(hash2, height, round, valKeys[1].Address()) ts.HelperSignVote(valKeys[0], vote1a) ts.HelperSignVote(valKeys[0], vote1b) ts.HelperSignVote(valKeys[1], vote2) _, err := voteSet.AddVote(vote1a) require.NoError(t, err) _, err = voteSet.AddVote(vote1b) // Double vote require.ErrorIs(t, err, ErrDoubleVote) _, err = voteSet.AddVote(vote2) require.NoError(t, err) assert.Equal(t, int64(5+6), voteSet.VotedPower()) } func TestBinaryVotedPower(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) height := ts.RandHeight() round := ts.RandRound() voteSet := NewCPPreVoteVoteSet(1, totalPower, valsMap) just := &vote.JustInitYes{} hash1 := ts.RandHash() hash2 := ts.RandHash() vote1a := vote.NewCPPreVote(hash1, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) vote1b := vote.NewCPPreVote(hash2, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) vote1c := vote.NewCPPreVote(hash1, height, round, 1, vote.CPValueYes, just, valKeys[0].Address()) vote2 := vote.NewCPPreVote(hash1, height, round, 0, vote.CPValueYes, just, valKeys[1].Address()) ts.HelperSignVote(valKeys[0], vote1a) ts.HelperSignVote(valKeys[0], vote1b) ts.HelperSignVote(valKeys[0], vote1c) ts.HelperSignVote(valKeys[1], vote2) _, _err := voteSet.AddVote(vote1a) require.NoError(t, _err) _, _err = voteSet.AddVote(vote1b) // Double vote require.ErrorIs(t, _err, ErrDoubleVote) _, _err = voteSet.AddVote(vote1c) // Next CP:Round require.NoError(t, _err) _, _err = voteSet.AddVote(vote2) require.NoError(t, _err) assert.Equal(t, int64(5+6), voteSet.VotedPower(0)) assert.Equal(t, int64(5), voteSet.VotedPower(1)) } func TestBlockHas2FP1Votes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) voteSet := NewPrecommitVoteSet(0, totalPower, valsMap) blockHash := ts.RandHash() vote0 := vote.NewPrecommitVote(ts.RandHash(), 1, 0, valKeys[0].Address()) // Byzantine vote vote1 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[0].Address()) vote2 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[1].Address()) vote3 := vote.NewPrecommitVote(blockHash, 1, 0, valKeys[2].Address()) ts.HelperSignVote(valKeys[0], vote0) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) _, _ = voteSet.AddVote(vote0) _, _ = voteSet.AddVote(vote1) _, _ = voteSet.AddVote(vote2) assert.False(t, voteSet.Has2FP1Votes()) _, _ = voteSet.AddVote(vote3) assert.True(t, voteSet.Has2FP1Votes()) } func TestBinaryHas3FP1Votes(t *testing.T) { ts := testsuite.NewTestSuite(t) valsMap, valKeys, totalPower := setupCommittee(ts, 5, 6, 8, 11) hash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} voteSet := NewCPPreVoteVoteSet(round, totalPower, valsMap) vote0 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueNo, just, valKeys[0].Address()) // Byzantine vote vote1 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[0].Address()) vote2 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[1].Address()) vote3 := vote.NewCPPreVote(hash, height, round, 0, vote.CPValueYes, just, valKeys[2].Address()) ts.HelperSignVote(valKeys[0], vote0) ts.HelperSignVote(valKeys[0], vote1) ts.HelperSignVote(valKeys[1], vote2) ts.HelperSignVote(valKeys[2], vote3) _, _ = voteSet.AddVote(vote0) _, _ = voteSet.AddVote(vote1) _, _ = voteSet.AddVote(vote2) assert.False(t, voteSet.Has2FP1Votes(0)) _, _ = voteSet.AddVote(vote3) assert.True(t, voteSet.Has2FP1Votes(0)) } ================================================ FILE: crypto/address.go ================================================ package crypto import ( "fmt" "io" "slices" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/encoding" ) // Address format: // hrp + `1` + type + data + checksum const ( SignatureTypeBLS byte = 1 SignatureTypeEd25519 byte = 3 ) const ( AddressSize = 21 treasuryAddressString = "000000000000000000000000000000000000000000" ) var TreasuryAddress = Address{0} type Address [AddressSize]byte // AddressFromString decodes the input string and returns the Address // if the string is a valid bech32m encoding of an address. func AddressFromString(text string) (Address, error) { if text == treasuryAddressString { return TreasuryAddress, nil } // Decode the bech32m encoded address. hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(text) if err != nil { return Address{}, err } // Check if hrp is valid if hrp != AddressHRP { return Address{}, InvalidHRPError(hrp) } // check type is valid validTypes := []AddressType{ AddressTypeValidator, AddressTypeBLSAccount, AddressTypeEd25519Account, } if !slices.Contains(validTypes, AddressType(typ)) { return Address{}, InvalidAddressTypeError(typ) } // check length is valid if len(data) != 20 { return Address{}, InvalidLengthError(len(data) + 1) } var addr Address addr[0] = typ copy(addr[1:], data) return addr, nil } // NewAddress create a new address based. func NewAddress(typ AddressType, data []byte) Address { var addr Address addr[0] = byte(typ) copy(addr[1:], data) return addr } // Bytes returns the 21 bytes of the address data. func (addr Address) Bytes() []byte { return addr[:] } // String returns a human-readable string for the address. func (addr Address) String() string { if addr == TreasuryAddress { return treasuryAddressString } str, _ := bech32m.EncodeFromBase256WithType( AddressHRP, addr[0], addr[1:]) return str } // ShortString returns a shortened string representation of the hash. func (addr Address) ShortString() string { str := addr.String() return fmt.Sprintf("%s-%s", str[:8], str[len(str)-5:]) } // LogString returns a concise string representation intended for use in logs. func (addr Address) LogString() string { return addr.ShortString() } func (addr Address) Type() AddressType { return AddressType(addr[0]) } func (addr Address) Encode(w io.Writer) error { switch typ := addr.Type(); typ { case AddressTypeTreasury: return encoding.WriteElement(w, uint8(0)) case AddressTypeValidator, AddressTypeBLSAccount, AddressTypeEd25519Account: return encoding.WriteElement(w, addr) default: return InvalidAddressTypeError(typ) } } func (addr *Address) Decode(r io.Reader) error { err := encoding.ReadElement(r, &addr[0]) if err != nil { return err } switch typ := addr.Type(); typ { case AddressTypeTreasury: return nil case AddressTypeValidator, AddressTypeBLSAccount, AddressTypeEd25519Account: return encoding.ReadElement(r, addr[1:]) default: return InvalidAddressTypeError(typ) } } // SerializeSize returns the number of bytes it would take to serialize the address. func (addr Address) SerializeSize() int { switch typ := addr.Type(); typ { case AddressTypeTreasury: return 1 case AddressTypeValidator, AddressTypeBLSAccount, AddressTypeEd25519Account: return AddressSize default: return 0 } } func (addr Address) IsTreasuryAddress() bool { return addr.Type() == AddressTypeTreasury } func (addr Address) IsAccountAddress() bool { return addr.Type() == AddressTypeTreasury || addr.Type() == AddressTypeBLSAccount || addr.Type() == AddressTypeEd25519Account } func (addr Address) IsValidatorAddress() bool { return addr.Type() == AddressTypeValidator } ================================================ FILE: crypto/address_test.go ================================================ package crypto_test import ( "bytes" "encoding/hex" "io" "strings" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/bech32m" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTreasuryAddressType(t *testing.T) { treasury := crypto.TreasuryAddress assert.False(t, treasury.IsValidatorAddress()) assert.True(t, treasury.IsAccountAddress()) assert.True(t, treasury.IsTreasuryAddress()) } func TestAddressType(t *testing.T) { tests := []struct { address string account bool validator bool }{ {address: "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp", account: false, validator: true}, {address: "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", account: true, validator: false}, {address: "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", account: true, validator: false}, } for _, tt := range tests { addr, _ := crypto.AddressFromString(tt.address) assert.Equal(t, tt.account, addr.IsAccountAddress()) assert.Equal(t, tt.validator, addr.IsValidatorAddress()) } } func TestFromString(t *testing.T) { tests := []struct { encoded string err error bytes []byte addrType crypto.AddressType }{ { "000000000000000000000000000000000000000000", nil, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, crypto.AddressTypeTreasury, }, { "00", bech32m.InvalidLengthError(2), nil, 0, }, { "", bech32m.InvalidLengthError(0), nil, 0, }, { "not_proper_encoded", bech32m.InvalidSeparatorIndexError(-1), nil, 0, }, { "pc1ioiooi", bech32m.NonCharsetCharError(105), nil, 0, }, { "pc19p72rf", bech32m.InvalidLengthError(0), nil, 0, }, { "qc1z0hrct7eflrpw4ccrttxzs4qud2axex4dh8zz75", crypto.InvalidHRPError("qc"), nil, 0, }, { "pc1p0hrct7eflrpw4ccrttxzs4qud2axex4dg8xaf5", bech32m.InvalidChecksumError{Expected: "cdzdfr", Actual: "g8xaf5"}, nil, 0, }, { "pc1p0hrct7eflrpw4ccrttxzs4qud2axexs2dhdk8", crypto.InvalidLengthError(20), nil, 0, }, { "pc1y0hrct7eflrpw4ccrttxzs4qud2axex4dksmred", crypto.InvalidAddressTypeError(4), nil, 0, }, { "PC1P0HRCT7EFLRPW4CCRTTXZS4QUD2AXEX4DCDZDFR", // UPPERCASE nil, []byte{ 0x01, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, 0x03, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad, }, crypto.AddressTypeValidator, }, { "pc1p0hrct7eflrpw4ccrttxzs4qud2axex4dcdzdfr", nil, []byte{ 0x01, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, 0x03, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad, }, crypto.AddressTypeValidator, }, { "pc1zzqkzzu4vyddss052as6c37qrdcfptegquw826x", nil, []byte{ 0x02, 0x10, 0x2c, 0x21, 0x72, 0xac, 0x23, 0x5b, 0x08, 0x3e, 0x8a, 0xec, 0x35, 0x88, 0xf8, 0x03, 0x6e, 0x12, 0x15, 0xe5, 0x00, }, crypto.AddressTypeBLSAccount, }, { "pc1rspm7ps49gar9ft5g0tkl6lhxs8ygeakq87quh3", nil, []byte{ 0x03, 0x80, 0x77, 0xe0, 0xc2, 0xa5, 0x47, 0x46, 0x54, 0xae, 0x88, 0x7a, 0xed, 0xfd, 0x7e, 0xe6, 0x81, 0xc8, 0x8c, 0xf6, 0xc0, }, crypto.AddressTypeEd25519Account, }, } for no, tt := range tests { addr, err := crypto.AddressFromString(tt.encoded) if tt.err == nil { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.bytes, addr.Bytes(), "test %v: invalid result", no) assert.Equal(t, strings.ToLower(tt.encoded), addr.String(), "test %v: invalid encode", no) assert.Equal(t, tt.addrType, addr.Type(), "test %v: invalid type", no) } else { require.ErrorIs(t, err, tt.err, "test %v: invalid error", no) } } } func TestAddressDecoding(t *testing.T) { tests := []struct { size int hex string err error }{ { 1, "00", nil, }, { 0, "040000000000000000000000000000000000000000", crypto.InvalidAddressTypeError(4), }, { 0, "04000102030405060708090a0b0c0d0e0f0001020304", crypto.InvalidAddressTypeError(4), }, { 21, "0100", io.ErrUnexpectedEOF, }, { 21, "01000102030405060708090a0b0c0d0e0f000102", io.ErrUnexpectedEOF, }, { 21, "01000102030405060708090a0b0c0d0e0f00010203", nil, }, { 21, "02000102030405060708090a0b0c0d0e0f00010203", nil, }, { 21, "03000102030405060708090a0b0c0d0e0f00010203", nil, }, } for no, tt := range tests { data, _ := hex.DecodeString(tt.hex) buf := bytes.NewBuffer(data) addr := new(crypto.Address) err := addr.Decode(buf) if tt.err != nil { require.ErrorIs(t, err, tt.err, "test %v: error not matched", no) assert.Equal(t, tt.size, addr.SerializeSize(), "test %v invalid size", no) } else { require.NoError(t, err, "test %v expected no error", no) assert.Equal(t, tt.size, addr.SerializeSize(), "test %v invalid size", no) length := addr.SerializeSize() for i := 0; i < length; i++ { w := util.NewFixedWriter(i) require.Error(t, addr.Encode(w), "encode test %v failed", i) } w := util.NewFixedWriter(length) require.NoError(t, addr.Encode(w)) assert.Equal(t, data, w.Bytes()) } } } func TestShortString(t *testing.T) { h, err := crypto.AddressFromString("pc1p0hrct7eflrpw4ccrttxzs4qud2axex4dcdzdfr") require.NoError(t, err) assert.Equal(t, "pc1p0hrc-dzdfr", h.ShortString()) assert.Equal(t, h.ShortString(), h.LogString()) } ================================================ FILE: crypto/address_type.go ================================================ package crypto type AddressType byte const ( AddressTypeTreasury AddressType = 0 AddressTypeValidator AddressType = 1 AddressTypeBLSAccount AddressType = 2 AddressTypeEd25519Account AddressType = 3 ) func (t AddressType) String() string { switch t { case AddressTypeTreasury: return "treasury" case AddressTypeBLSAccount: return "bls_account" case AddressTypeEd25519Account: return "ed25519_account" case AddressTypeValidator: return "validator" default: return "unknown-address-type" } } ================================================ FILE: crypto/bls/bls.go ================================================ // Package bls implements BLS signatures over the BLS12-381 pairing-friendly curve. // // This package uses the gnark-crypto BLS12-381 implementation and provides // the main primitives used across Pactus: PrivateKey, PublicKey, and // Signature. It also exposes helpers for aggregating signatures and public // keys when multiple participants are involved. // // The ciphersuite/domain separation follows `BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_`. package bls import ( "errors" bls12381 "github.com/consensys/gnark-crypto/ecc/bls12-381" ) // Ciphersuite for basic mode as defined in: // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-4.2.1 var ( dst = []byte("BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_") gen2Aff bls12381.G2Affine gen2Jac bls12381.G2Jac ) func init() { _, gen2Jac, _, gen2Aff = bls12381.Generators() } // SignatureAggregate aggregates one or more BLS signatures into a single // signature. It returns an error if no signatures are provided or if any // signature fails to decode to a valid point. func SignatureAggregate(sigs ...*Signature) (*Signature, error) { if len(sigs) == 0 { return nil, errors.New("no signatures provided") } grp1 := new(bls12381.G1Affine) aggPointG1, err := sigs[0].PointG1() if err != nil { return nil, err } for i := 1; i < len(sigs); i++ { pointG1, err := sigs[i].PointG1() if err != nil { return nil, err } aggPointG1 = grp1.Add(aggPointG1, pointG1) } data := aggPointG1.Bytes() return &Signature{ data: data[:], pointG1: aggPointG1, }, nil } // PublicKeyAggregate aggregates one or more BLS public keys into a single // public key. It returns an error if no public keys are provided or if any // public key fails to decode to a valid point. func PublicKeyAggregate(pubs ...*PublicKey) (*PublicKey, error) { if len(pubs) == 0 { return nil, errors.New("no public keys provided") } grp2 := new(bls12381.G2Affine) aggPointG2, err := pubs[0].PointG2() if err != nil { return nil, err } for i := 1; i < len(pubs); i++ { pointG2, err := pubs[i].PointG2() if err != nil { return nil, err } aggPointG2 = grp2.Add(aggPointG2, pointG2) } data := aggPointG2.Bytes() return &PublicKey{ data: data[:], pointG2: aggPointG2, }, nil } ================================================ FILE: crypto/bls/bls_bench_test.go ================================================ package bls_test import ( "crypto/rand" "testing" "github.com/pactus-project/pactus/crypto/bls" ) func BenchmarkEncode(b *testing.B) { b.ReportAllocs() buf := make([]byte, bls.PrivateKeySize) _, _ = rand.Read(buf) prv, _ := bls.PrivateKeyFromBytes(buf) pub := prv.PublicKeyNative() for b.Loop() { _ = pub.Bytes() } } func BenchmarkDecodeSign(b *testing.B) { b.ReportAllocs() buf := make([]byte, bls.PrivateKeySize) _, _ = rand.Read(buf) prv, _ := bls.PrivateKeyFromBytes(buf) bufMsg := []byte("pactus") sig := prv.Sign(bufMsg) sigBytes := sig.Bytes() for b.Loop() { _, _ = bls.SignatureFromBytes(sigBytes) } } func BenchmarkVerify(b *testing.B) { b.ReportAllocs() buf := make([]byte, bls.PrivateKeySize) _, _ = rand.Read(buf) prv, _ := bls.PrivateKeyFromBytes(buf) pub := prv.PublicKeyNative() bufMsg := []byte("pactus") sig1 := prv.Sign(bufMsg) for b.Loop() { _ = pub.Verify(bufMsg, sig1) } } func BenchmarkDecode(b *testing.B) { b.ReportAllocs() buf := make([]byte, bls.PrivateKeySize) _, _ = rand.Read(buf) prv, _ := bls.PrivateKeyFromBytes(buf) pub := prv.PublicKeyNative() pubBytes := pub.Bytes() for b.Loop() { _, _ = bls.PublicKeyFromBytes(pubBytes) } } ================================================ FILE: crypto/bls/bls_test.go ================================================ package bls_test import ( "encoding/hex" "testing" bls12381 "github.com/consensys/gnark-crypto/ecc/bls12-381" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSigning(t *testing.T) { msg := []byte("pactus") prv, _ := bls.PrivateKeyFromString( "SECRET1P9QAUKRJAU7SQ7AT6ZZ6HXHYLMKPQSQYTGDL2VMH5Q5N0P5Q2QW0QL45AY3") pub, _ := bls.PublicKeyFromString( "public1p5dwsgfwmacjpuhaxhy0522j87qc5390v56ndh92f7flxge7vt3zfuxlvuwpnk7tdeed4s4l2r5nj" + "5zuyjfh0uzjmvrauf4t5xfvff5cpljvpqqpk7pzhv0hxfhf9gt5896vnllsf89ux8kc7anqlu7nxvvxcclw7") sig, _ := bls.SignatureFromString( "8c3ba687e8e4c016293a2c369493faa565065987544a59baba7aadae3f17ada07883552b6c7d1d7eb49f46fbdf0975c4") accAddr, _ := crypto.AddressFromString("pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf") valAddr, _ := crypto.AddressFromString("pc1p0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpf5uf6u5") sig1 := prv.Sign(msg) assert.Equal(t, sig.Bytes(), sig1.Bytes()) require.NoError(t, pub.Verify(msg, sig)) assert.Equal(t, pub, prv.PublicKey()) assert.Equal(t, valAddr, pub.ValidatorAddress()) assert.Equal(t, accAddr, pub.AccountAddress()) } func TestSignatureAggregate(t *testing.T) { msg := []byte("pactus") prv1, _ := bls.PrivateKeyFromString( "SECRET1P9QAUKRJAU7SQ7AT6ZZ6HXHYLMKPQSQYTGDL2VMH5Q5N0P5Q2QW0QL45AY3") prv2, _ := bls.PrivateKeyFromString( "SECRET1PVJHEKQ3F4NX5CA9L69CSLLNWMYWPAXDQ64ZLEQHFSV4JLFGXMXWQPDPHR0") sig1 := prv1.SignNative(msg) sig2 := prv2.SignNative(msg) agg, _ := bls.SignatureAggregate(sig1, sig2) aggExpected, _ := bls.SignatureFromString( "a74f05102c6217d06527cfcd1854ba6c38f4047f75a74958ad01fe66a5120c77c5416bfd875669588566670dc61f1168") assert.True(t, agg.EqualsTo(aggExpected)) } func TestAggregateFailed(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, prv1 := ts.RandBLSKeyPair() pub2, prv2 := ts.RandBLSKeyPair() pub3, prv3 := ts.RandBLSKeyPair() pub4, prv4 := ts.RandBLSKeyPair() msg1 := ts.RandBytes(14) msg2 := ts.RandBytes(16) sig1 := prv1.Sign(msg1).(*bls.Signature) sig11 := prv1.Sign(msg2).(*bls.Signature) sig2 := prv2.Sign(msg1).(*bls.Signature) sig3 := prv3.Sign(msg1).(*bls.Signature) sig4 := prv4.Sign(msg1).(*bls.Signature) agg1, _ := bls.SignatureAggregate(sig1, sig2, sig3) agg2, _ := bls.SignatureAggregate(sig1, sig2, sig4) agg3, _ := bls.SignatureAggregate(sig11, sig2, sig3) agg4, _ := bls.SignatureAggregate(sig1, sig2) agg5, _ := bls.SignatureAggregate(sig3, sig2, sig1) pubs1 := []*bls.PublicKey{pub1, pub2, pub3} pubs2 := []*bls.PublicKey{pub1, pub2, pub4} pubs3 := []*bls.PublicKey{pub1, pub2} pubs4 := []*bls.PublicKey{pub3, pub2, pub1} pubAgg1, _ := bls.PublicKeyAggregate(pubs1...) pubAgg2, _ := bls.PublicKeyAggregate(pubs2...) pubAgg3, _ := bls.PublicKeyAggregate(pubs3...) pubAgg4, _ := bls.PublicKeyAggregate(pubs4...) require.NoError(t, pub1.Verify(msg1, sig1)) require.NoError(t, pub2.Verify(msg1, sig2)) require.NoError(t, pub3.Verify(msg1, sig3)) require.Error(t, pub2.Verify(msg1, sig1)) require.Error(t, pub3.Verify(msg1, sig1)) require.Error(t, pub1.Verify(msg1, agg1)) require.Error(t, pub2.Verify(msg1, agg1)) require.Error(t, pub3.Verify(msg1, agg1)) require.NoError(t, pubAgg1.Verify(msg1, agg1)) require.Error(t, pubAgg1.Verify(msg2, agg1)) require.Error(t, pubAgg1.Verify(msg1, agg2)) require.Error(t, pubAgg2.Verify(msg1, agg1)) require.NoError(t, pubAgg2.Verify(msg1, agg2)) require.Error(t, pubAgg2.Verify(msg2, agg2)) require.Error(t, pubAgg1.Verify(msg1, agg3)) require.Error(t, pubAgg1.Verify(msg2, agg3)) require.Error(t, pubAgg1.Verify(msg1, agg4)) require.Error(t, pubAgg3.Verify(msg1, agg1)) require.NoError(t, pubAgg1.Verify(msg1, agg5)) require.NoError(t, pubAgg4.Verify(msg1, agg1)) } func TestAggregateOnlyOneSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv1 := ts.RandBLSKeyPair() msg1 := []byte("pactus") sig1 := prv1.Sign(msg1).(*bls.Signature) agg1, _ := bls.SignatureAggregate(sig1) assert.True(t, agg1.EqualsTo(sig1)) } func TestAggregateOnlyOnePublicKey(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandBLSKeyPair() agg1, _ := bls.PublicKeyAggregate(pub1) assert.True(t, agg1.EqualsTo(pub1)) } // TODO: should we check for duplication here? func TestDuplicatedAggregate(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, prv1 := ts.RandBLSKeyPair() pub2, prv2 := ts.RandBLSKeyPair() msg1 := []byte("pactus") sig1 := prv1.Sign(msg1).(*bls.Signature) sig2 := prv2.Sign(msg1).(*bls.Signature) agg1, _ := bls.SignatureAggregate(sig1, sig2, sig1) agg2, _ := bls.SignatureAggregate(sig1, sig2) assert.False(t, agg1.EqualsTo(agg2)) pubs1 := []*bls.PublicKey{pub1, pub2} pubs2 := []*bls.PublicKey{pub1, pub2, pub1} pubAgg1, _ := bls.PublicKeyAggregate(pubs1...) pubAgg2, _ := bls.PublicKeyAggregate(pubs2...) assert.False(t, pubAgg1.EqualsTo(pubAgg2)) } // TestHashToCurve ensures that the hash-to-curve function in kilic/bls12-381 // works as intended and is compatible with the spec. // test vectors can be found here: // https://datatracker.ietf.org/doc/html/rfc9380 func TestHashToCurve(t *testing.T) { domain := []byte("QUUX-V01-CS02-with-BLS12381G1_XMD:SHA-256_SSWU_RO_") tests := []struct { msg string expected string }{ { "", "052926add2207b76ca4fa57a8734416c8dc95e24501772c814278700eed6d1e4e8cf62d9c09db0fac349612b759e79a1" + "08ba738453bfed09cb546dbb0783dbb3a5f1f566ed67bb6be0e8c67e2e81a4cc68ee29813bb7994998f3eae0c9c6a265", }, { "abc", "03567bc5ef9c690c2ab2ecdf6a96ef1c139cc0b2f284dca0a9a7943388a49a3aee664ba5379a7655d3c68900be2f6903" + "0b9c15f3fe6e5cf4211f346271d7b01c8f3b28be689c8429c85b67af215533311f0b8dfaaa154fa6b88176c229f2885d", }, { "abcdef0123456789", "11e0b079dea29a68f0383ee94fed1b940995272407e3bb916bbf268c263ddd57a6a27200a784cbc248e84f357ce82d98" + "03a87ae2caf14e8ee52e51fa2ed8eefe80f02457004ba4d486d6aa1f517c0889501dc7413753f9599b099ebcbbd2d709", }, { "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", "15f68eaa693b95ccb85215dc65fa81038d69629f70aeee0d0f677cf22285e7bf58d7cb86eefe8f2e9bc3f8cb84fac488" + "1807a1d50c29f430b8cafc4f8638dfeeadf51211e1602a5f184443076715f91bb90a48ba1e370edce6ae1062f5e6dd38", }, { "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "082aabae8b7dedb0e78aeb619ad3bfd9277a2f77ba7fad20ef6aabdc6c31d19ba5a6d12283553294c1825c4b3ca2dcfe" + "05b84ae5a942248eea39e1d91030458c40153f3b654ab7872d779ad1e942856a20c438e8d99bc8abfbf74729ce1f7ac8", }, } for no, tt := range tests { mappedPoint, _ := bls12381.HashToG1([]byte(tt.msg), domain) d, _ := hex.DecodeString(tt.expected) expectedPoint := bls12381.G1Affine{} err := expectedPoint.Unmarshal(d) require.NoError(t, err) assert.Equal(t, expectedPoint, mappedPoint, "test %v: not match", no) } } // TestSignatureAggregateErrorHandling tests error scenarios for SignatureAggregate. func TestSignatureAggregateErrorHandling(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("EmptyInput", func(t *testing.T) { aggSig, err := bls.SignatureAggregate() require.Error(t, err) assert.Nil(t, aggSig) assert.Contains(t, err.Error(), "no signatures provided") }) t.Run("InvalidSignature", func(t *testing.T) { // Point at infinity invalidSig, err := bls.SignatureFromString( "C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") require.NoError(t, err) aggSig, err := bls.SignatureAggregate(invalidSig) require.Error(t, err) assert.Nil(t, aggSig) }) t.Run("MixedValidAndInvalid", func(t *testing.T) { validSig := ts.RandBLSSignature() invalidSig, err := bls.SignatureFromString( "C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") require.NoError(t, err) aggSig, err := bls.SignatureAggregate(validSig, invalidSig) require.Error(t, err) assert.Nil(t, aggSig) }) } // TestPublicKeyAggregateErrorHandling tests error scenarios for PublicKeyAggregate. func TestPublicKeyAggregateErrorHandling(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("EmptyInput", func(t *testing.T) { aggPub, err := bls.PublicKeyAggregate() require.Error(t, err) assert.Nil(t, aggPub) assert.Contains(t, err.Error(), "no public keys provided") }) t.Run("InvalidPublicKeyData", func(t *testing.T) { // Point at infinity invalidPub, err := bls.PublicKeyFromString( "public1pcqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqglnhh9") require.NoError(t, err) aggPub, err := bls.PublicKeyAggregate(invalidPub) require.Error(t, err) assert.Nil(t, aggPub) }) t.Run("MixedValidAndInvalid", func(t *testing.T) { validPub, _ := ts.RandBLSKeyPair() invalidPub, err := bls.PublicKeyFromString( "public1pcqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqglnhh9") require.NoError(t, err) aggPub, err := bls.PublicKeyAggregate(validPub, invalidPub) require.Error(t, err) assert.Nil(t, aggPub) }) } ================================================ FILE: crypto/bls/errors.go ================================================ package bls ================================================ FILE: crypto/bls/hdkeychain/errors.go ================================================ package hdkeychain import ( "errors" "fmt" ) var ( // ErrDeriveHardFromPublic describes an error in which the caller // attempted to derive a hardened extended key from a public key. ErrDeriveHardFromPublic = errors.New("cannot derive a hardened key " + "from a public key") // ErrNotPrivExtKey describes an error in which the caller attempted // to extract a private key from a public extended key. ErrNotPrivExtKey = errors.New("unable to create private keys from a " + "public extended key") // ErrUnusableSeed describes an error in which the provided seed is not // usable due to the derived key falling outside of the valid range for // BLS private keys. This error indicates the caller must choose // another seed. ErrUnusableSeed = errors.New("unusable seed") // ErrInvalidSeedLen describes an error in which the provided seed or // seed length is not in the allowed range. ErrInvalidSeedLen = fmt.Errorf("seed length must be between %d and %d "+ "bits", MinSeedBytes*8, MaxSeedBytes*8) // ErrInvalidKeyData describes an error in which the provided key is // not valid. ErrInvalidKeyData = errors.New("key data is invalid") // ErrInvalidHRP describes an error in which the HRP is not valid. ErrInvalidHRP = errors.New("HRP is invalid") ) ================================================ FILE: crypto/bls/hdkeychain/extendedkey.go ================================================ package hdkeychain // References: // PIP-11: Deterministic key hierarchy for BLS12-381 curve // https://pips.pactus.org/PIPs/pip-11 import ( "bytes" "crypto/hmac" "crypto/rand" "crypto/sha512" "encoding/binary" "math/big" "strings" bls12381 "github.com/kilic/bls12-381" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/encoding" ) const ( // hardenedKeyStart is the index at which a hardened key starts. Each // extended key has 2^31 normal child keys and 2^31 hardened child keys. // Thus the range for normal child keys is [0, 2^31 - 1] and the range // for hardened child keys is [2^31, 2^32 - 1]. hardenedKeyStart = uint32(0x80000000) // 2^31 // MinSeedBytes is the minimum number of bytes allowed for a seed to // a master node. MinSeedBytes = 16 // 128 bits // MaxSeedBytes is the maximum number of bytes allowed for a seed to // a master node. MaxSeedBytes = 64 // 512 bits ) // ExtendedKey houses all the information needed to support a hierarchical // deterministic extended key. type ExtendedKey struct { key []byte // This will be the bytes of extended public or private key chainCode []byte path []uint32 isPrivate bool pubOnG1 bool } // newExtendedKey returns a new instance of an extended key with the given // fields. No error checking is performed here as it's only intended to be a // convenience method used to create a populated struct. func newExtendedKey(key, chainCode []byte, path []uint32, isPrivate, pubOnG1 bool) *ExtendedKey { return &ExtendedKey{ key: key, chainCode: chainCode, path: path, isPrivate: isPrivate, pubOnG1: pubOnG1, } } // pubKeyBytes returns bytes for the serialized public key associated with this // extended key. // // When the extended key is already a public key, the key is simply returned as // is since it's already in the correct form. However, when the extended key is // a private key, the public key will be calculated. func (k *ExtendedKey) pubKeyBytes() []byte { // Just return the key if it's already an extended public key. if !k.isPrivate { return k.key } grp1 := bls12381.NewG1() privKey := bls12381.NewFr() privKey.FromBytes(k.key) if k.pubOnG1 { pub := new(bls12381.PointG1) grp1.MulScalar(pub, grp1.One(), privKey) return grp1.ToCompressed(pub) } grp2 := bls12381.NewG2() pub := new(bls12381.PointG2) grp2.MulScalar(pub, grp2.One(), privKey) return grp2.ToCompressed(pub) } // IsPrivate returns whether or not the extended key is a private extended key. // // A private extended key can be used to derive both hardened and non-hardened // child private and public extended keys. A public extended key can only be // used to derive non-hardened child public extended keys. func (k *ExtendedKey) IsPrivate() bool { return k.isPrivate } // DerivePath returns a derived child extended key from this master key at the // given path. func (k *ExtendedKey) DerivePath(path []uint32) (*ExtendedKey, error) { ext := k var err error for _, index := range path { ext, err = ext.Derive(index) if err != nil { return nil, err } } return ext, nil } // Derive returns a derived child extended key at the given index. // // When this extended key is a private extended key (as determined by the IsPrivate // function), a private extended key will be derived. Otherwise, the derived // extended key will be a public extended key. // // When the index is greater to or equal than the hardenedKeyStart constant, the // derived extended key will be a hardened extended key. It is only possible to // derive a hardened extended key from a private extended key. Consequently, // this function will return ErrDeriveHardFromPublic if a hardened child // extended key is requested from a public extended key. // // A hardened extended key is useful since, as previously mentioned, it requires // a parent private extended key to derive. In other words, normal child // extended public keys can be derived from a parent public extended key (no // knowledge of the parent private key) whereas hardened extended keys may not // be. // //nolint:nestif // complexity can't be reduced more. func (k *ExtendedKey) Derive(index uint32) (*ExtendedKey, error) { // There are four scenarios that could happen here: // 1) Private extended key -> Hardened child private extended key // 2) Private extended key -> Non-hardened child private extended key // 3) Public extended key -> Non-hardened child public extended key // 4) Public extended key -> Hardened child public extended key (INVALID!) isChildHardened := index >= hardenedKeyStart // The data used to derive the child key depends on whether or not the // child is hardened. // // For hardened children: // G1: 0x01 || ser256(parentKey) || ser32(i) // G2: 0x00 || ser256(parentKey) || ser32(i) // // For normal children: // G1: serG1(parentPubKey) || ser32(i) // G2: serG2(parentPubKey) || ser32(i) // data := make([]byte, 0, 100) if isChildHardened { // Case #1 and #4. if !k.isPrivate { // Case #4 // // A hardened child extended key may not be created from a public // extended key. return nil, ErrDeriveHardFromPublic } // Case #1 // // When the child is a hardened child, the key is known to be a // private key. // Pad it with a leading zero as required by [BIP32] for deriving the child. if len(k.key) != 32 { return nil, ErrInvalidKeyData } if k.pubOnG1 { data = append(data, 0x01) } else { data = append(data, 0x00) } data = append(data, k.key...) } else { // Case #2 or #3. // // This is either a public or private extended key, but in // either case, the data which is used to derive the child key // starts with the BLS public key bytes. data = append(data, k.pubKeyBytes()...) if k.pubOnG1 && len(data) != 48 { return nil, ErrInvalidKeyData } if !k.pubOnG1 && len(data) != 96 { return nil, ErrInvalidKeyData } } indexData := make([]byte, 4) binary.BigEndian.PutUint32(indexData, index) data = append(data, indexData...) // The order is same for all three groups (g1, g2, and gt). gt := bls12381.NewGT() order := gt.Q() var childChainCode, il []byte for { // Take the HMAC-SHA512 of the current key's chain code and the derived // data: // I = HMAC-SHA512(Key = chainCode, Data = data) hmac512 := hmac.New(sha512.New, k.chainCode) _, _ = hmac512.Write(data) ilr := hmac512.Sum(nil) // Split "I" into two 32-byte sequences Il and Ir where: // Il = intermediate key used to derive the child // Ir = child chain code il = ilr[:len(ilr)/2] childChainCode = ilr[len(ilr)/2:] // If Il greater or equal to the order of the group, or it is zero, // generate a new "I" with data equals to 0x01 || Ir || ser32(i) ilNum := big.Int{} ilNum.SetBytes(il) if ilNum.Cmp(order) == -1 && ilNum.Cmp(big.NewInt(0)) != 0 { break } data = make([]byte, 0, 1+len(childChainCode)+len(indexData)) data = append(data, 0x01) data = append(data, childChainCode...) data = append(data, indexData...) } ilFr := new(bls12381.Fr) ilFr.FromBytes(il) var childKey []byte if k.isPrivate { // Case #1 or #2. // Add the parent private key to the intermediate private key to // derive the final child key. // // childKey = parse256(Il) + parentKey keyNum := new(bls12381.Fr) keyNum.FromBytes(k.key) childKeyNum := bls12381.NewFr() childKeyNum.Add(keyNum, ilFr) childKey = childKeyNum.ToBytes() } else { // Case #3. // Calculate the corresponding intermediate public key for the // intermediate private key. // if k.pubOnG1 { // Public key is in G1 subgroup // // childKey = pointG1(parse256(Il)) + parentKey grp1 := bls12381.NewG1() ilPoint := new(bls12381.PointG1) grp1.MulScalar(ilPoint, grp1.One(), ilFr) pubKey, err := grp1.FromCompressed(k.key) if err != nil { return nil, err } childPubKey := new(bls12381.PointG1) grp1.Add(childPubKey, pubKey, ilPoint) childKey = grp1.ToCompressed(childPubKey) } else { // Public key is in G2 subgroup // // childKey = pointG2(parse256(Il)) + parentKey grp2 := bls12381.NewG2() ilPoint := new(bls12381.PointG2) grp2.MulScalar(ilPoint, grp2.One(), ilFr) pubKey, err := grp2.FromCompressed(k.key) if err != nil { return nil, err } childPubKey := new(bls12381.PointG2) grp2.Add(childPubKey, pubKey, ilPoint) childKey = grp2.ToCompressed(childPubKey) } } newPath := make([]uint32, 0, len(k.path)+1) newPath = append(newPath, k.path...) newPath = append(newPath, index) return newExtendedKey(childKey, childChainCode, newPath, k.isPrivate, k.pubOnG1), nil } // Path returns the path of derived key. // // Path with values between 0 and 2^31-1 are normal child keys, // and those values between 2^31 and 2^32-1 are hardened keys. func (k *ExtendedKey) Path() []uint32 { return k.path } // RawPrivateKey returns the raw bytes of the private key. // As you might imagine this is only possible if the extended key is a private // extended key (as determined by the IsPrivate function). The ErrNotPrivExtKey // error will be returned if this function is called on a public extended key. func (k *ExtendedKey) RawPrivateKey() ([]byte, error) { if !k.isPrivate { return nil, ErrNotPrivExtKey } return k.key, nil } // RawPublicKey returns the raw bytes of the public key. func (k *ExtendedKey) RawPublicKey() []byte { return k.pubKeyBytes() } // Neuter returns a new extended public key from this extended private key. The // same extended key will be returned unaltered if it is already an extended // public key. // // As the name implies, an extended public key does not have access to the // private key, so it is not capable of signing transactions or deriving // child extended private keys. However, it is capable of deriving further // child extended public keys. func (k *ExtendedKey) Neuter() *ExtendedKey { // Already an extended public key. if !k.isPrivate { return k } // Convert it to an extended public key. The key for the new extended // key will simply be the pubkey of the current extended private key. // // This is the function N((k,c)) -> (K, c) from [BIP32]. return newExtendedKey(k.pubKeyBytes(), k.chainCode, k.path, false, k.pubOnG1) } // String returns the extended key as a bech32-encoded string. func (k *ExtendedKey) String() string { // // The serialized format is structured as follows: // +-------+---------+------------+-------+------------+----------+ // | Depth | Path | Chain code | G1/G2 | Key length | Key data | // +-------+---------+------------+-------+------------+----------+ // | 1 | depth*4 | 32 | 1 | 1 | 32/48/96 | // +-------+---------+------------+-------+------------+----------+ // // Description: // - Depth: 1 byte representing the depth of derivation path. // - Path: serialized BIP-32 path; each entry is encoded as 32-bit unsigned integer, least significant byte first // - Chain code: 32 bytes chain code // - G1 or G2: 1 byte to specify the group. // - Key length: 1 byte representing the length of the key data. // - Key data: Can be 32, 48, or 96 bytes. // buf := bytes.NewBuffer(make([]byte, 0)) err := encoding.WriteElement(buf, byte(len(k.path))) if err != nil { return err.Error() } for _, p := range k.path { err := encoding.WriteElement(buf, p) if err != nil { return err.Error() } } err = encoding.WriteVarBytes(buf, k.chainCode) if err != nil { return err.Error() } err = encoding.WriteElement(buf, k.pubOnG1) if err != nil { return err.Error() } err = encoding.WriteVarBytes(buf, k.key) if err != nil { return err.Error() } hrp := crypto.XPublicKeyHRP if k.isPrivate { hrp = crypto.XPrivateKeyHRP } str, err := bech32m.EncodeFromBase256WithType(hrp, crypto.SignatureTypeBLS, buf.Bytes()) if err != nil { return err.Error() } if k.isPrivate { str = strings.ToUpper(str) } return str } // NewKeyFromString returns a new extended key instance from a bech32-encoded string. func NewKeyFromString(str string) (*ExtendedKey, error) { hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(strings.ToLower(str)) if err != nil { return nil, err } if typ != crypto.SignatureTypeBLS { return nil, ErrInvalidKeyData } reader := bytes.NewReader(data) depth := uint8(0) err = encoding.ReadElement(reader, &depth) if err != nil { return nil, err } path := make([]uint32, depth) for i := byte(0); i < depth; i++ { err := encoding.ReadElement(reader, &path[i]) if err != nil { return nil, err } } chainCode, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } var pubOnG1 bool err = encoding.ReadElement(reader, &pubOnG1) if err != nil { return nil, err } key, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } var isPrivate bool switch hrp { case crypto.XPrivateKeyHRP: isPrivate = true case crypto.XPublicKeyHRP: isPrivate = false default: return nil, ErrInvalidHRP } return newExtendedKey(key, chainCode, path, isPrivate, pubOnG1), nil } // NewMaster creates a new master node for use in creating a hierarchical // deterministic key chain. The seed must be between 128 and 512 bits and // should be generated by a cryptographically secure random generation source. func NewMaster(seed []byte, pubOnG1 bool) (*ExtendedKey, error) { // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes]. if len(seed) < MinSeedBytes || len(seed) > MaxSeedBytes { return nil, ErrInvalidSeedLen } // masterKey is the master key used along with a random seed used to generate // the master node in the hierarchical tree. masterKey := []byte("BLS12381 seed") // First take the HMAC-SHA512 of the master key and the seed data: // I = HMAC-SHA512(Key = "BLS12381-HD seed", Data = S) hmac512 := hmac.New(sha512.New, masterKey) _, _ = hmac512.Write(seed) ilr := hmac512.Sum(nil) // Split "I" into two 32-byte sequences Il and Ir where: // Il = master IKM // Ir = master chain code ikm := ilr[:len(ilr)/2] chainCode := ilr[len(ilr)/2:] // Using BLS KeyGen to generate the master private key from the IKM. privKey, err := bls.KeyGen(ikm, nil) if err != nil { return nil, err } return newExtendedKey(privKey.Bytes(), chainCode, []uint32{}, true, pubOnG1), nil } // GenerateSeed returns a cryptographically secure random seed that can be used // as the input for the NewMaster function to generate a new master node. // // The length is in bytes and it must be between 16 and 64 (128 to 512 bits). // The recommended length is 32 (256 bits) as defined by the RecommendedSeedLen // constant. func GenerateSeed(length uint8) ([]byte, error) { // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes]. if length < MinSeedBytes || length > MaxSeedBytes { return nil, ErrInvalidSeedLen } buf := make([]byte, length) _, err := rand.Read(buf) if err != nil { return nil, err } return buf, nil } ================================================ FILE: crypto/bls/hdkeychain/extendedkey_test.go ================================================ package hdkeychain import ( "encoding/hex" "io" "testing" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestNonHardenedDerivation tests derive private key and public key in // non hardened mode. func TestNonHardenedDerivation(t *testing.T) { ts := testsuite.NewTestSuite(t) testSeed := ts.RandBytes(32) path := []uint32{ ts.RandUint32Max(hardenedKeyStart), ts.RandUint32Max(hardenedKeyStart), ts.RandUint32Max(hardenedKeyStart), ts.RandUint32Max(hardenedKeyStart), } checkPublicKeyDerivation := func(masterKey *ExtendedKey, path []uint32) { neuterKey := masterKey.Neuter() extKey1, _ := masterKey.DerivePath(path) extKey2, _ := neuterKey.DerivePath(path) pubKey1 := extKey1.RawPublicKey() pubKey2 := extKey2.RawPublicKey() require.Equal(t, path, extKey1.Path()) require.Equal(t, pubKey1, pubKey2) } masterKeyG1, _ := NewMaster(testSeed, true) masterKeyG2, _ := NewMaster(testSeed, false) checkPublicKeyDerivation(masterKeyG1, path) checkPublicKeyDerivation(masterKeyG2, path) } // TestHardenedDerivation tests derive private key and public key in // hardened mode. func TestHardenedDerivation(t *testing.T) { ts := testsuite.NewTestSuite(t) testSeed := ts.RandBytes(32) path := []uint32{ ts.RandUint32Max(hardenedKeyStart) + hardenedKeyStart, ts.RandUint32Max(hardenedKeyStart) + hardenedKeyStart, ts.RandUint32Max(hardenedKeyStart) + hardenedKeyStart, ts.RandUint32Max(hardenedKeyStart) + hardenedKeyStart, } masterKey, _ := NewMaster(testSeed, false) extKey, _ := masterKey.DerivePath(path) privKey, _ := extKey.RawPrivateKey() blsPrivKey, _ := bls.PrivateKeyFromBytes(privKey) pubKey := extKey.RawPublicKey() assert.Equal(t, path, extKey.Path()) assert.Equal(t, pubKey, blsPrivKey.PublicKey().Bytes()) } // TestDerivation tests derive private keys in hardened and non hardened modes. func TestDerivation(t *testing.T) { testSeed, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f") h := hardenedKeyStart tests := []struct { name string path []uint32 wantPrivG1 string wantPrivG2 string wantPubG1 string wantPubG2 string }{ { name: "derivation path: m", path: []uint32{}, wantPrivG1: "4f55e31ee1c4f58af0840fd3f5e635fd6c07eacd14283c45d7d43729003abb84", wantPrivG2: "4f55e31ee1c4f58af0840fd3f5e635fd6c07eacd14283c45d7d43729003abb84", wantPubG1: "8fbed8842588b629377c0a0d0d9547a9ee17527d5fd6d2c609034a8c3c074dda031e0dfe886b454499bfe0f40a7c4b18", wantPubG2: "b1bad3bf4a4ae87c89dec2c32512603ca08e2db62cfd2254c96bfe75068f5a98e7c4cd7d37cf0496dd6e79703e7c88e5" + "046bdec9c896ef2ad030096bbcf73c6cff17add3da9530f22491901fdf7fd2076c0f08ea35a4fdaa00e7ac6d0a5442e3", }, { name: "derivation path: m/0H", path: []uint32{h}, wantPrivG1: "5f5d7bfae7eabf2cc3faebc12449e1c7116c2777d7e384ead79df299667b8d9a", wantPrivG2: "5695ba5087a27f8c0d7270455104658b2367b8e90ab6f7f57ac7ce22d4a6836c", wantPubG1: "b2826a89a22fec3349d64f4379a1eb5632b0b345b985b738324a5b8db640307421201efe36ae6c8c639d32d4124496ae", wantPubG2: "b37da3080662ceeb7f07289801a56e5c555d413434ad096079c084caa162c8d224891f68816921f5bd1453af7d085bc4" + "00341d61ce496ffb11cd10f8e90522447fada1a5f646c45797e00460925876f0b63f4023bf27e828688f7b4dd833e641", }, { name: "derivation path: m/0H/1", path: []uint32{h, 1}, wantPrivG1: "3bea739c9a2695ba4af566bc3f28e5c62da8e721b977709f9d492f7129b83521", wantPrivG2: "555422bcbffd1d55eea6f87a924ba5d046bb60e2bffe2182daf78bab6a6e179f", wantPubG1: "af5980f4172797c07174a4040eb0b1859b357b05f0a29ac65c35d957730fd722ffd520d861e8fbe3126d26ceb08dbe52", wantPubG2: "b5f783bb1f1173feebb083f146c5a83470e84f26177862c5ab5b8be34ae6e3955d1b324f501a0d2751d971805f0612bc" + "0b5e966c9060eeb08cf38a7e71037863ffb2f6433694e69db59f731dbe55125f995d2d6ccd139d56d5b481d3bce76baa", }, { name: "derivation path: m/0H/1/2H", path: []uint32{h, 1, 2 + h}, wantPrivG1: "221e1f998e9599aecdab1c9671162bea925ee50d5f1c5bca2ed19908ac0f2ddd", wantPrivG2: "39e4906c49c05f5daeed89ced104a32cda82782654dcc116346144424746f871", wantPubG1: "b06503dda77e1408478fc4b2d044a0ce2ab73691e8497a37f99d00e1076782698aacceb8e68fb9c3db6deccb0b8375fe", wantPubG2: "81461b89b446d055ac3bc38b9384363cbabc47cc0a16c97a7c7ea24eeffd70f213daacdfd736a49c45befececcd81832" + "12f04e186bcc9fbf67bfa5de862c57298cff4d36d5409380a166b9e37348b665186019b15498608309936e7ff36a87b5", }, { name: "derivation path: m/0H/1/2H/2", path: []uint32{h, 1, 2 + h, 2}, wantPrivG1: "26a19ca5ff2f6b32871de71aabd87a30ce79cdde3b0556cbb46692295f0aee15", wantPrivG2: "3aa1e19a9bf2bf631d95b401e29d5f042160edd76ced9696e42a98be80b41faa", wantPubG1: "afd589792ba6bcb1866598a673a96fdaef9bf94026ef875a1a3e8d4fd839360f4659c9495afaf24c52577c0aa1fb5d45", wantPubG2: "92b20565b4a02bf82229f32e0ccc6f23446ded5ca2d67067afc70931b5a934f9469651e67e1105b5601cb585a1f44538" + "124fe3529f5b1edb27ab44f0900e59a27f57df87aa03395a70825d02433c2498d8396c90986dad79d5ba9e0fc438bea8", }, { name: "derivation path: m/0H/1/2H/2/1000000000", path: []uint32{h, 1, 2 + h, 2, 1000000000}, wantPrivG1: "44b743b059c2e4cb720378f4f0eda9369a1f02294e140e6a2e444bfdd36b1ad9", wantPrivG2: "2b01ef29730eb62c7114621d9d28ad77cf33f2434572a2bf9b73f1e502fea770", wantPubG1: "99b404130a1ae6b6dd90ddf2a25c692f405536fee11046257ed6ba11629f101ad80658c61c039f0523de4c6e9f58a5c8", wantPubG2: "b05a01a80c3fe465227c23df7e36be1adcf557111f4cc50bf0f00c66c2b084d1e1d96e2f1c754496cb1f83dd1123456e" + "17697e77a9b99ea557a63c9bf29668a966732882e7baebf079a4afad212910deb10e5151e18ae98ee4a57d0e622332aa", }, } masterKeyG1, _ := NewMaster(testSeed, true) masterKeyG2, _ := NewMaster(testSeed, false) for no, tt := range tests { extKeyG1, err := masterKeyG1.DerivePath(tt.path) require.NoError(t, err) extKeyG2, err := masterKeyG2.DerivePath(tt.path) require.NoError(t, err) privKeyG1, err := extKeyG1.RawPrivateKey() require.NoError(t, err) require.Equal(t, tt.wantPrivG1, hex.EncodeToString(privKeyG1), "mismatched serialized private key for test #%v", no+1) privKeyG2, err := extKeyG2.RawPrivateKey() require.NoError(t, err) require.Equal(t, tt.wantPrivG2, hex.EncodeToString(privKeyG2), "mismatched serialized private key for test #%v", no+1) pubKeyG1 := extKeyG1.RawPublicKey() require.Equal(t, tt.wantPubG1, hex.EncodeToString(pubKeyG1), "mismatched serialized public key for test #%v", no+1) pubKeyG2 := extKeyG2.RawPublicKey() require.Equal(t, tt.wantPubG2, hex.EncodeToString(pubKeyG2), "mismatched serialized public key for test #%v", no+1) neuterKeyG1 := extKeyG1.Neuter() neuterKeyG2 := extKeyG2.Neuter() neuterPubKeyG1 := neuterKeyG1.RawPublicKey() neuterPubKeyG2 := neuterKeyG2.RawPublicKey() require.True(t, extKeyG1.IsPrivate()) require.True(t, extKeyG2.IsPrivate()) require.False(t, neuterKeyG1.IsPrivate()) require.False(t, neuterKeyG2.IsPrivate()) require.Equal(t, pubKeyG1, neuterPubKeyG1) require.Equal(t, pubKeyG2, neuterPubKeyG2) require.Equal(t, tt.path, extKeyG1.Path()) require.Equal(t, tt.path, extKeyG2.Path()) require.Equal(t, tt.path, neuterKeyG1.Path()) require.Equal(t, tt.path, neuterKeyG2.Path()) _, err = neuterKeyG1.RawPrivateKey() require.ErrorIs(t, err, ErrNotPrivExtKey) _, err = neuterKeyG2.RawPrivateKey() require.ErrorIs(t, err, ErrNotPrivExtKey) blsPrivKey, _ := bls.PrivateKeyFromBytes(privKeyG2) require.Equal(t, pubKeyG2, blsPrivKey.PublicKey().Bytes()) } } // TestInvalidDerivation tests Derive function for invalid data. func TestInvalidDerivation(t *testing.T) { t.Run("Private key is 31 bytes. It should be 32 bytes", func(t *testing.T) { key := [31]byte{0} chainCode := [32]byte{0} ext := newExtendedKey(key[:], chainCode[:], []uint32{}, true, false) _, err := ext.Derive(hardenedKeyStart) require.ErrorIs(t, err, ErrInvalidKeyData) }) t.Run("Public key on G1 is 96 bytes. It should be 48 bytes", func(t *testing.T) { key := [96]byte{0} chainCode := [32]byte{0} ext := newExtendedKey(key[:], chainCode[:], []uint32{}, false, true) _, err := ext.Derive(0) require.ErrorIs(t, err, ErrInvalidKeyData) }) t.Run("Public key on G2 is 42 bytes. It should be 96 bytes", func(t *testing.T) { key := [95]byte{0} chainCode := [32]byte{0} ext := newExtendedKey(key[:], chainCode[:], []uint32{}, false, false) _, err := ext.Derive(0) require.ErrorIs(t, err, ErrInvalidKeyData) }) t.Run("Invalid key", func(t *testing.T) { key := [95]byte{0} chainCode := [32]byte{0} ext := newExtendedKey(key[:], chainCode[:], []uint32{}, false, false) _, err := ext.Derive(0) require.ErrorIs(t, err, ErrInvalidKeyData) }) t.Run("Derive public key from hardened key", func(t *testing.T) { key := [32]byte{0} chainCode := [32]byte{0} ext := newExtendedKey(key[:], chainCode[:], []uint32{}, false, false) _, err := ext.Derive(hardenedKeyStart) require.ErrorIs(t, err, ErrDeriveHardFromPublic) }) } // TestGenerateSeed ensures the GenerateSeed function works as intended. func TestGenerateSeed(t *testing.T) { tests := []struct { name string length uint8 err error }{ // Test various valid lengths. {name: "16 bytes", length: 16}, {name: "17 bytes", length: 17}, {name: "20 bytes", length: 20}, {name: "32 bytes", length: 32}, {name: "64 bytes", length: 64}, // Test invalid lengths. {name: "15 bytes", length: 15, err: ErrInvalidSeedLen}, {name: "65 bytes", length: 65, err: ErrInvalidSeedLen}, } for no, tt := range tests { seed, err := GenerateSeed(tt.length) require.ErrorIs(t, err, tt.err) if tt.err == nil { assert.Len(t, seed, int(tt.length), "GenerateSeed #%d (%s): length mismatch -- got %d, want %d", no, tt.name, len(seed), tt.length) } } } // TestNewMaster ensures the NewMaster function works as intended. func TestNewMaster(t *testing.T) { tests := []struct { name string seed string privKey string err error }{ // Test various valid seeds. { name: "16 bytes", seed: "000102030405060708090a0b0c0d0e0f", privKey: "4f55e31ee1c4f58af0840fd3f5e635fd6c07eacd14283c45d7d43729003abb84", }, { name: "32 bytes", seed: "3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678", privKey: "4c101174339ffca5cc0afca5d2d8e2538834781318e5e1c8afdabf7e6fb77444", }, { name: "64 bytes", seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7" + "b7875726f6c696663605d5a5754514e4b484542", privKey: "47b660cc8dc2d4dc2cdf8893048bda9d5dc6318eb31f301b272b291b26cb20a1", }, // Test invalid seeds. { name: "empty seed", seed: "", err: ErrInvalidSeedLen, }, { name: "15 bytes", seed: "000000000000000000000000000000", err: ErrInvalidSeedLen, }, { name: "65 bytes", seed: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000", err: ErrInvalidSeedLen, }, } for no, tt := range tests { seed, _ := hex.DecodeString(tt.seed) extKeyG1, err := NewMaster(seed, true) require.ErrorIs(t, err, tt.err) extKeyG2, err := NewMaster(seed, true) require.ErrorIs(t, err, tt.err) if tt.err == nil { privKeyG1, _ := extKeyG1.RawPrivateKey() assert.Equal(t, tt.privKey, hex.EncodeToString(privKeyG1), "NewMaster #%d (%s): privKeyG1 mismatch -- got %x, want %s", no+1, tt.name, privKeyG1, tt.privKey) privKeyG2, _ := extKeyG2.RawPrivateKey() assert.Equal(t, tt.privKey, hex.EncodeToString(privKeyG2), "NewMaster #%d (%s): privKeyG2 mismatch -- got %x, want %s", no+1, tt.name, privKeyG2, tt.privKey) } } } // TestKeyToString ensures the String function works as intended. // //nolint:lll // long extended keys func TestKeyToString(t *testing.T) { testSeed, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f") h := hardenedKeyStart tests := []struct { name string path []uint32 wantXPrivG1 string wantXPrivG2 string wantXPubG1 string wantXPubG2 string }{ { name: "derivation path: m", path: []uint32{}, wantXPrivG1: "XSECRET1PQQSTS7DSJ7AZNY54YZ53MM3FMCWEGWVVJYRK5SJ9HESHQSN96GCVJUSPYP84TCC7U8Z0TZHSSS8A8A0XXH7KCPL2E52ZS0Z96L2RW2GQ82ACG058EDE", wantXPrivG2: "XSECRET1PQQSTS7DSJ7AZNY54YZ53MM3FMCWEGWVVJYRK5SJ9HESHQSN96GCVJUSQYP84TCC7U8Z0TZHSSS8A8A0XXH7KCPL2E52ZS0Z96L2RW2GQ82ACGWGEQEJ", wantXPubG1: "xpublic1pqqsts7dsj7azny54yz53mm3fmcwegwvvjyrk5sj9heshqsn96gcvjuspxz8makyyykytv2fh0s9q6rv4g757u96j040ad5kxpyp54rpuqaxa5qc7phlgs669gjvmlc85pf7ykxqqale8c", wantXPubG2: "xpublic1pqqsts7dsj7azny54yz53mm3fmcwegwvvjyrk5sj9heshqsn96gcvjusqvzcm45alff9wslyfmmpvxfgjvq72pr3dkck06gj5e94luagx3adf3e7ye47n0ncyjmwku7ts8e7g3egyd00vnjykau4dqvqfdw70w0rvlut6m576j5c0yfy3jq0a7l7jqakq7z82xkj0m2squ7kx6zj5gt3snpvg7k", }, { name: "derivation path: m/0H", path: []uint32{h}, wantXPrivG1: "XSECRET1PQYQQQQYQYQDNX9T02WPS2RZ5SYUKE3JPHE8RGDHJMTNU7684679WEQWRN8STWQFQTAWHH7H8A2LJESL6A0QJGJ0PCUGKCFMH6L3CF6KHNHEFJENM3KDQRD8L6L", wantXPrivG2: "XSECRET1PQYQQQQYQYR38R7SGQNLMC6H96CANRN8XE3WVFVLF0V5XW2LE0FDSPYT52FUNSQPQ262M55Y85FLCCRTJWPZ4ZPR93V3K0W8FP2M00AT6CL8Z949XSDKQ5PJCQ7", wantXPubG1: "xpublic1pqyqqqqyqyqdnx9t02wps2rz5syuke3jphe8rgdhjmtnu7684679weqwrn8stwqfsk2px4zdz9lkrxjwkfaphng0t2cetpv69hxzmwwpjffdcmdjqxp6zzgq7lcm2umyvvwwn94qjgjt2u0x45lj", wantXPubG2: "xpublic1pqyqqqqyqyr38r7sgqnlmc6h96canrn8xe3wvfvlf0v5xw2le0fdspyt52funsqrqkd76xzqxvt8wklc89zvqrftwt3246sf5xjksjcreczzv4gtzerfzfzgldzqkjg04h5298tmappdugqp5r4suujt0lvgu6y8cayzjy3rl4ks6tajxc3te0cqyvzf9sahskcl5qgalyl5zs6y00dxasvlxgyepz53e", }, { name: "derivation path: m/0H/1", path: []uint32{h, 1}, wantXPrivG1: "XSECRET1PQGQQQQYQQYQQQQPQ6AXJT5395S9R89ME3E25LJXAP2QVULMX7S3UFNQ2D49Z0RHR38YQZGPMAFEEEX3XJKAY4ATXHSLJ3EWX9K5WWGDEWACFL82F9ACJNWP4YYSJCVL6", wantXPrivG2: "XSECRET1PQGQQQQYQQYQQQQPQFC96AZPJ5LSJKC3SEG5KUFF9Q7A9TEX2XHLYZVMZ7EF9D0G2M0QQQGZ42S3TE0LAR427AFHC02FYHFWSG6AKPC4LLCSC9KHH3W4K5MSHNUXN9SDC", wantXPubG1: "xpublic1pqgqqqqyqqyqqqqpq6axjt5395s9r89me3e25ljxap2qvulmx7s3ufnq2d49z0rhr38yqzv90txq0g9e8jlq8za9yqs8tpvv9nv6hkp0s52dvvhp4m9thxr7hytla2gxcv850hccjd5nvavydhefqvzaww5", wantXPubG2: "xpublic1pqgqqqqyqqyqqqqpqfc96azpj5lsjkc3seg5kuff9q7a9tex2xhlyzvmz7ef9d0g2m0qqqc9477pmk8c3w0lwhvyr79rvt2p5wr5y7fsh0p3vt26m30354ehrj4w3kvj02qdq6f63m9ccqhcxz27qkh5kdjgxpm4s3nec5ln3qdux8laj7epnd98xnk6e7ucahe23yhuet5kkengnn4tdtdyp6w7ww6a2nwzn8e", }, { name: "derivation path: m/0H/1/2H", path: []uint32{h, 1, 2 + h}, wantXPrivG1: "XSECRET1PQVQQQQYQQYQQQQQZQQQGQGXG02G9WGUD336CLQ7L25X4NPNCE75A4247R2A7S3W9S37XQSQ7FQQJQGS7R7VCA9VE4MX6K8YKWYTZH65JTMJS6HCUT09ZA5VEPZKQ7TWAD83EJ6", wantXPrivG2: "XSECRET1PQVQQQQYQQYQQQQQZQQQGQG8PZVKZLK72R0VSGLSAKL4EMX9UW4VL9WZN6G8GXC24877GHGAFKVQZQW0YJPKYNSZLTKHWMZWW6YZ2XTX6SFUZV4XUCYTRGC2YGFR5D7R3N8ZL8R", wantXPubG1: "xpublic1pqvqqqqyqqyqqqqqzqqqgqgxg02g9wgud336clq7l25x4npnce75a4247r2a7s3w9s37xqsq7fqqnpvr9q0w6wls5pprcl39j6pz2pn32kumfr6zf0gmln8gquyrk0qnf32kvaw8x37uu8kmdan9shqm4lcszuz63", wantXPubG2: "xpublic1pqvqqqqyqqyqqqqqzqqqgqg8pzvkzlk72r0vsglsakl4emx9uw4vl9wzn6g8gxc24877ghgafkvqxpq2xrwymg3ks2kkrhsutjwzrv096h3ruczske9a8cl4zfmhl6u8jz0d2eh7hx6jfc3d7lm8vekqcxgf0qnscd0xfl0m8h7jaap3v2u5cel6dxm25pyuq59ntncmnfzmx2xrqrxc4fxrqsvyexmnl7d4g0dgd7v822", }, { name: "derivation path: m/0H/1/2H/2", path: []uint32{h, 1, 2 + h, 2}, wantXPrivG1: "XSECRET1PQSQQQQYQQYQQQQQZQQQGQQSQQQQZPZWYN98T9Y4TWRN08T5M0ZPVEFVXQCKLYSK269XY7U90VNPXEJJZQYSZDGVU5HLJ76EJSUW7WX4TMPARPNNEEH0RKP2KEW6XDY3FTU9WU9GXSKX25", wantXPrivG2: "XSECRET1PQSQQQQYQQYQQQQQZQQQGQQSQQQQZQTZRQ5QNVZ5MDELTWXSKWAXCS7JGA6SNUM44Z06Q5TRL5WE8W9EQQQSR4G0PN2DL90MRRK2MGQ0ZN40SGGTQAHTKEMVKJMJZ4X97SZ6PL2SP66YRM", wantXPubG1: "xpublic1pqsqqqqyqqyqqqqqzqqqgqqsqqqqzpzwyn98t9y4twrn08t5m0zpvefvxqcklysk269xy7u90vnpxejjzqyc2l4vf0y46d093seje3fnn49ha4muml9qzdmu8tgdrar20mqunvr6xt8y5jkh67fx9y4mup2slkh29x3erlu", wantXPubG2: "xpublic1pqsqqqqyqqyqqqqqzqqqgqqsqqqqzqtzrq5qnvz5mdeltwxskwaxcs7jga6snum44z06q5trl5we8w9eqqpsf9vs9vk62q2lcyg5lxtsve3hjx3rda4w294nsv7huwzf3kk5nf72xjeg7vls3qk6kq894skslg3fczf87x55ltv0dkfatgncfqrje5fl40hu84gpnjknssfwsyseuyjvdswtvjzvxmtte6kafur7y8zl2s9y5g8j", }, { name: "derivation path: m/0H/1/2H/2/1000000000", path: []uint32{h, 1, 2 + h, 2, 1000000000}, wantXPrivG1: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJAT3F4D", wantXPrivG2: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS27RYEFRMHGDM0P29ADH63TVTNMRTDS2MF5R23X7T7ULLJS073DTQQYQ4SRMEFWV8TVTR3Z33PM8FG44MU7VLJGDZH9G4LNDELREGZL6NHQCCQPXC", wantXPubG1: "xpublic1pq5qqqqyqqyqqqqqzqqqgqqsqqqqqpj568vs9lz67jkww0p6tqy9ny58lv0pcvrqqtaemkgv6uljns99y68jhcvgpxzvmgpqnpgdwddkajrwl9gjudyh5q4fklms3q3390mtt5ytznugp4kqxtrrpcqulq53aunrwnav2tjqzv47re", wantXPubG2: "xpublic1pq5qqqqyqqyqqqqqzqqqgqqsqqqqqpj568vs27ryefrmhgdm0p29adh63tvtnmrtds2mf5r23x7t7ulljs073dtqqvzc95qdgpsl7gefz0s3a7l3khcddea2hzy05e3gt7rcqcekzkzzdrcwedch3ca2yjm93lq7azy352mshd9l802den6j40f3un0efv69fveej3qh8ht4lq7dy47kjz2gsm6csu523ux9wnrhy547suc3rx24qeppfv3", }, } masterKeyG1, _ := NewMaster(testSeed, true) masterKeyG2, _ := NewMaster(testSeed, false) for no, tt := range tests { extKeyG1, _ := masterKeyG1.DerivePath(tt.path) neuterKeyG1 := extKeyG1.Neuter() extKeyG2, _ := masterKeyG2.DerivePath(tt.path) neuterKeyG2 := extKeyG2.Neuter() require.Equal(t, tt.wantXPrivG1, extKeyG1.String(), "test %d failed", no) require.Equal(t, tt.wantXPubG1, neuterKeyG1.String(), "test %d failed", no) require.Equal(t, tt.wantXPrivG2, extKeyG2.String(), "test %d failed", no) require.Equal(t, tt.wantXPubG2, neuterKeyG2.String(), "test %d failed", no) recoveredExtKeyG1, err := NewKeyFromString(tt.wantXPrivG1) require.NoError(t, err) recoveredExtKeyG2, err := NewKeyFromString(tt.wantXPrivG2) require.NoError(t, err) recoveredNeuterKeyG1, err := NewKeyFromString(tt.wantXPubG1) require.NoError(t, err) recoveredNeuterKeyG2, err := NewKeyFromString(tt.wantXPubG2) require.NoError(t, err) require.Equal(t, extKeyG1, recoveredExtKeyG1) require.Equal(t, extKeyG2, recoveredExtKeyG2) require.Equal(t, neuterKeyG1, recoveredNeuterKeyG1) require.Equal(t, neuterKeyG2, recoveredNeuterKeyG2) require.Equal(t, tt.path, recoveredExtKeyG1.path) require.Equal(t, tt.path, recoveredExtKeyG2.path) require.Equal(t, tt.path, recoveredNeuterKeyG1.path) require.Equal(t, tt.path, recoveredNeuterKeyG2.path) } } // TestInvalidString checks errors corresponding to the invalid strings // //nolint:lll // long extended private keys func TestInvalidString(t *testing.T) { tests := []struct { desc string str string expectedError error }{ { desc: "invalid checksum", str: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJAT3FD4", expectedError: bech32m.InvalidChecksumError{Expected: "at3f4d", Actual: "at3fd4"}, }, { desc: "no depth", str: "XSECRET1P6NTYTF", expectedError: io.EOF, }, { desc: "wrong path", str: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQESEG08", expectedError: io.EOF, }, { desc: "no chain code", str: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568V5G6A4P", expectedError: io.EOF, }, { desc: "no group", str: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGS579U6", expectedError: io.EOF, }, { desc: "no key", str: "XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPJCMNNE", expectedError: io.EOF, }, { desc: "invalid type", str: "XSECRET1ZQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJPJKVRX", expectedError: ErrInvalidKeyData, }, { desc: "invalid type", str: "XPUBLIC1ZQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJ3HALEC", expectedError: ErrInvalidKeyData, }, { desc: "invalid hrp", str: "SECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJ98PYV5", expectedError: ErrInvalidHRP, }, { desc: "invalid hrp", str: "PUBLIC1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJ4Z2HK2", expectedError: ErrInvalidHRP, }, } for no, tt := range tests { _, err := NewKeyFromString(tt.str) require.ErrorIs(t, err, tt.expectedError, "test %d error is not matched", no) } } // TestNeuter ensures the Neuter function works as intended. // //nolint:lll // Long extended private key func TestNeuter(t *testing.T) { extKey, _ := NewKeyFromString("XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJAT3F4D") neuterKey := extKey.Neuter() assert.Equal(t, "xpublic1pq5qqqqyqqyqqqqqzqqqgqqsqqqqqpj568vs9lz67jkww0p6tqy9ny58lv0pcvrqqtaemkgv6uljns99y68jhcvgpxzvmgpqnpgdwddkajrwl9gjudyh5q4fklms3q3390mtt5ytznugp4kqxtrrpcqulq53aunrwnav2tjqzv47re", neuterKey.String()) assert.Equal(t, neuterKey, neuterKey.Neuter()) } ================================================ FILE: crypto/bls/private_key.go ================================================ package bls import ( "crypto/sha256" "errors" "math/big" "strings" bls12381 "github.com/consensys/gnark-crypto/ecc/bls12-381" "github.com/consensys/gnark-crypto/ecc/bls12-381/fr" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/bech32m" "golang.org/x/crypto/hkdf" ) var _ crypto.PrivateKey = &PrivateKey{} const PrivateKeySize = 32 type PrivateKey struct { scalar *big.Int } // PrivateKeyFromString decodes the input string and returns the PrivateKey // if the string is a valid bech32m encoding of a BLS public key. func PrivateKeyFromString(text string) (*PrivateKey, error) { // Decode the bech32m encoded private key. hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(text) if err != nil { return nil, err } // Check if hrp is valid if hrp != crypto.PrivateKeyHRP { return nil, crypto.InvalidHRPError(hrp) } if typ != crypto.SignatureTypeBLS { return nil, crypto.InvalidSignatureTypeError(typ) } return PrivateKeyFromBytes(data) } // KeyGen generates a private key deterministically from a secret octet string // IKM and an optional octet string keyInfo. // Based on https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-2.3 func KeyGen(ikm, keyInfo []byte) (*PrivateKey, error) { // L is `ceil((3 * ceil(log2(r))) / 16) = 48`, // where `r` is the order of the BLS 12-381 curve // r: 0x73eda753 299d7d48 3339d808 09a1d805 53bda402 fffe5bfe ffffffff 00000001 // https://datatracker.ietf.org/doc/html/draft-yonezawa-pairing-friendly-curves-02#section-4.2.2 // if len(ikm) < 32 { return nil, errors.New("ikm is too short") } secret := make([]byte, 0, len(ikm)+1) secret = append(secret, ikm...) secret = append(secret, util.I2OSP(big.NewInt(0), 1)...) l := int64(48) pseudoRandomKey := make([]byte, 0, len(keyInfo)+2) pseudoRandomKey = append(pseudoRandomKey, keyInfo...) pseudoRandomKey = append(pseudoRandomKey, util.I2OSP(big.NewInt(l), 2)...) salt := []byte("BLS-SIG-KEYGEN-SALT-") num := big.NewInt(0) for num.Sign() == 0 { hash := sha256.Sum256(salt) salt = hash[:] okm := make([]byte, l) prk := hkdf.Extract(sha256.New, secret, salt) reader := hkdf.Expand(sha256.New, prk, pseudoRandomKey) _, _ = reader.Read(okm) order := fr.Modulus() num = new(big.Int).Mod(util.OS2IP(okm), order) } sk := make([]byte, 32) num.FillBytes(sk) return PrivateKeyFromBytes(sk) } // PrivateKeyFromBytes constructs a BLS private key from the raw bytes. func PrivateKeyFromBytes(data []byte) (*PrivateKey, error) { if len(data) != PrivateKeySize { return nil, crypto.InvalidLengthError(len(data)) } scalar := new(big.Int) scalar = scalar.SetBytes(data) return &PrivateKey{scalar: scalar}, nil } // String returns a human-readable string for the BLS private key. func (prv *PrivateKey) String() string { str, _ := bech32m.EncodeFromBase256WithType( crypto.PrivateKeyHRP, crypto.SignatureTypeBLS, prv.Bytes()) return strings.ToUpper(str) } // Bytes return the raw bytes of the private key. func (prv *PrivateKey) Bytes() []byte { data := prv.scalar.Bytes() data = util.PadToLeft(data, PrivateKeySize) return data } // Sign calculates the signature from the private key and given message. // It's defined in section 2.6 of the spec: CoreSign. func (prv *PrivateKey) Sign(msg []byte) crypto.Signature { return prv.SignNative(msg) } func (prv *PrivateKey) SignNative(msg []byte) *Signature { qAffine, err := bls12381.HashToG1(msg, dst) if err != nil { panic(err) } qJac := new(bls12381.G1Jac).FromAffine(&qAffine) sigJac := qJac.ScalarMultiplication(qJac, prv.scalar) sigAffine := new(bls12381.G1Affine).FromJacobian(sigJac) data := sigAffine.Bytes() return &Signature{ data: data[:], pointG1: sigAffine, } } func (prv *PrivateKey) PublicKeyNative() *PublicKey { pkJac := new(bls12381.G2Jac).ScalarMultiplication(&gen2Jac, prv.scalar) pkAffine := new(bls12381.G2Affine).FromJacobian(pkJac) data := pkAffine.Bytes() return &PublicKey{ data: data[:], pointG2: pkAffine, } } func (prv *PrivateKey) PublicKey() crypto.PublicKey { return prv.PublicKeyNative() } func (prv *PrivateKey) EqualsTo(x crypto.PrivateKey) bool { xBLS, ok := x.(*PrivateKey) if !ok { return false } return prv.scalar.Cmp(xBLS.scalar) == 0 } ================================================ FILE: crypto/bls/private_key_test.go ================================================ package bls_test import ( "encoding/hex" "strings" "testing" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPrivateKeyEqualsTo(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv1 := ts.RandBLSKeyPair() _, prv2 := ts.RandBLSKeyPair() _, prv3 := ts.RandEd25519KeyPair() assert.True(t, prv1.EqualsTo(prv1)) assert.False(t, prv1.EqualsTo(prv2)) assert.False(t, prv1.EqualsTo(prv3)) } func TestPrivateKeyFromString(t *testing.T) { tests := []struct { errMsg string encoded string valid bool result []byte }{ { "invalid separator index -1", "not_proper_encoded", false, nil, }, { "invalid bech32 string length 0", "", false, nil, }, { "invalid character not part of charset: 105", "SECRET1IOIOOI", false, nil, }, { "invalid bech32 string length 0", "SECRET1HPZZU9", false, nil, }, { "invalid HRP: xxx", "XXX1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQMUUMJT", false, nil, }, { "invalid checksum (expected qjvk67 got qjvk68)", "SECRET1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQQJVK68", false, nil, }, { "invalid length: 31", "SECRET1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CCZ0EU7Z", false, nil, }, { "invalid signature type: 2", "SECRET1ZDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQG04E54", false, nil, }, { "", "secret1pdrwtlp5px0fahdx39gxzjp7fkzfalml0d5u9tt9kvqhduc99cmgqqjvk67", // lowercase true, []byte{ 0x68, 0xdc, 0xbf, 0x86, 0x81, 0x33, 0xd3, 0xdb, 0xb4, 0xd1, 0x2a, 0xc, 0x29, 0x7, 0xc9, 0xb0, 0x93, 0xdf, 0xef, 0xef, 0x6d, 0x38, 0x55, 0xac, 0xb6, 0x60, 0x2e, 0xde, 0x60, 0xa5, 0xc6, 0xd0, }, }, { "", "SECRET1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQQJVK67", true, []byte{ 0x68, 0xdc, 0xbf, 0x86, 0x81, 0x33, 0xd3, 0xdb, 0xb4, 0xd1, 0x2a, 0xc, 0x29, 0x7, 0xc9, 0xb0, 0x93, 0xdf, 0xef, 0xef, 0x6d, 0x38, 0x55, 0xac, 0xb6, 0x60, 0x2e, 0xde, 0x60, 0xa5, 0xc6, 0xd0, }, }, } for no, tt := range tests { prv, err := bls.PrivateKeyFromString(tt.encoded) if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.result, prv.Bytes(), "test %v: invalid bytes", no) assert.Equal(t, strings.ToUpper(tt.encoded), prv.String(), "test %v: invalid encoded", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } // TestKeyGen ensures the KeyGen function works as intended. func TestKeyGen(t *testing.T) { tests := []struct { ikm string sk string }{ { "", "Err", }, { "00000000000000000000000000000000000000000000000000000000000000", "Err", }, { "0000000000000000000000000000000000000000000000000000000000000000", "4d129a19df86a0f5345bad4cc6f249ec2a819ccc3386895beb4f7d98b3db6235", }, { "2b1eb88002e83a622792d0b96d4f0695e328f49fdd32480ec0cf39c2c76463af", "0000f678e80740072a4a7fe8c7344db88a00ccc7db36aa51fa51f9c68e561584", }, // The test vectors from EIP-2333 // https://github.com/ethereum/EIPs/blob/784107449bd83a9327b54f82aba96de28d72b89a/EIPS/eip-2333.md#test-cases { "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e5349553" + "1f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04", "0d7359d57963ab8fbbde1852dcf553fedbc31f464d80ee7d40ae683122b45070", }, { "3141592653589793238462643383279502884197169399375105820974944592", "41c9e07822b092a93fd6797396338c3ada4170cc81829fdfce6b5d34bd5e7ec7", }, { "0099FF991111002299DD7744EE3355BBDD8844115566CC55663355668888CC00", "3cfa341ab3910a7d00d933d8f7c4fe87c91798a0397421d6b19fd5b815132e80", }, { "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", "2a0e28ffa5fbbe2f8e7aad4ed94f745d6bf755c51182e119bb1694fe61d3afca", }, } for no, tt := range tests { ikm, _ := hex.DecodeString(tt.ikm) prv, err := bls.KeyGen(ikm, nil) if tt.sk == "Err" { require.Error(t, err, "test '%v' failed. no error", no) } else { require.NoError(t, err, "test'%v' failed. has error", no) assert.Equal(t, tt.sk, hex.EncodeToString(prv.Bytes()), "test '%v' failed. not equal", no) } } } ================================================ FILE: crypto/bls/public_key.go ================================================ package bls import ( "bytes" "crypto/subtle" "io" bls12381 "github.com/consensys/gnark-crypto/ecc/bls12-381" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/encoding" ) var _ crypto.PublicKey = &PublicKey{} const PublicKeySize = 96 type PublicKey struct { pointG2 *bls12381.G2Affine // Lazily initialized point on G2. data []byte // Raw public key data. } // PublicKeyFromString decodes the input string and returns the PublicKey // if the string is a valid bech32m encoding of a BLS public key. func PublicKeyFromString(text string) (*PublicKey, error) { // Decode the bech32m encoded public key. hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(text) if err != nil { return nil, err } // Check if hrp is valid if hrp != crypto.PublicKeyHRP { return nil, crypto.InvalidHRPError(hrp) } if typ != crypto.SignatureTypeBLS { return nil, crypto.InvalidSignatureTypeError(typ) } return PublicKeyFromBytes(data) } // PublicKeyFromBytes constructs a BLS public key from the raw bytes. func PublicKeyFromBytes(data []byte) (*PublicKey, error) { if len(data) != PublicKeySize { return nil, crypto.InvalidLengthError(len(data)) } return &PublicKey{data: data}, nil } // Bytes returns the raw byte representation of the public key. func (pub *PublicKey) Bytes() []byte { return pub.data } // String returns a human-readable string for the BLS public key. func (pub *PublicKey) String() string { str, _ := bech32m.EncodeFromBase256WithType( crypto.PublicKeyHRP, crypto.SignatureTypeBLS, pub.Bytes()) return str } // MarshalCBOR encodes the public key into CBOR format. func (pub *PublicKey) MarshalCBOR() ([]byte, error) { return cbor.Marshal(pub.Bytes()) } // UnmarshalCBOR decodes the public key from CBOR format. func (pub *PublicKey) UnmarshalCBOR(bs []byte) error { var data []byte if err := cbor.Unmarshal(bs, &data); err != nil { return err } return pub.Decode(bytes.NewReader(data)) } // Encode writes the raw bytes of the public key to the provided writer. func (pub *PublicKey) Encode(w io.Writer) error { return encoding.WriteElements(w, pub.Bytes()) } // Decode reads the raw bytes of the public key from the provided reader and initializes the public key. func (pub *PublicKey) Decode(r io.Reader) error { data := make([]byte, PublicKeySize) err := encoding.ReadElements(r, data) if err != nil { return err } p, _ := PublicKeyFromBytes(data) *pub = *p return nil } // Verify checks that a signature is valid for the given message and public key. // It's defined in section 2.6 of the spec: CoreVerify. func (pub *PublicKey) Verify(msg []byte, sig crypto.Signature) error { if sig == nil { return crypto.ErrInvalidPublicKey } r := sig.(*Signature) pointG1, err := r.PointG1() if err != nil { return err } pointG2, err := pub.PointG2() if err != nil { return err } qAffine, err := bls12381.HashToG1(msg, dst) if err != nil { panic(err) } var negP bls12381.G2Affine negP.Neg(&gen2Aff) check, _ := bls12381.PairingCheck( []bls12381.G1Affine{qAffine, *pointG1}, []bls12381.G2Affine{*pointG2, negP}) if !check { return crypto.ErrInvalidSignature } return nil } func (*PublicKey) SerializeSize() int { return PublicKeySize } // EqualsTo checks if the current public key is equal to another public key. func (pub *PublicKey) EqualsTo(x crypto.PublicKey) bool { xBLS, ok := x.(*PublicKey) if !ok { return false } return subtle.ConstantTimeCompare(pub.data, xBLS.data) == 1 } // AccountAddress returns the account address derived from the public key. func (pub *PublicKey) AccountAddress() crypto.Address { data := hash.Hash160(hash.Hash256(pub.Bytes())) addr := crypto.NewAddress(crypto.AddressTypeBLSAccount, data) return addr } // ValidatorAddress returns the validator address derived from the public key. func (pub *PublicKey) ValidatorAddress() crypto.Address { data := hash.Hash160(hash.Hash256(pub.Bytes())) addr := crypto.NewAddress(crypto.AddressTypeValidator, data) return addr } // VerifyAddress checks if the provided address matches the derived address from the public key. func (pub *PublicKey) VerifyAddress(addr crypto.Address) error { if addr.IsValidatorAddress() { if addr != pub.ValidatorAddress() { return crypto.AddressMismatchError{ Expected: pub.ValidatorAddress(), Got: addr, } } } else { if addr != pub.AccountAddress() { return crypto.AddressMismatchError{ Expected: pub.AccountAddress(), Got: addr, } } } return nil } // PointG2 returns the point on G2 for the public key. func (pub *PublicKey) PointG2() (*bls12381.G2Affine, error) { if pub.pointG2 != nil { return pub.pointG2, nil } g2Aff := new(bls12381.G2Affine) err := g2Aff.Unmarshal(pub.data) if err != nil { return nil, err } if g2Aff.IsInfinity() || !g2Aff.IsInSubGroup() { return nil, crypto.ErrInvalidPublicKey } pub.pointG2 = g2Aff return g2Aff, nil } ================================================ FILE: crypto/bls/public_key_test.go ================================================ package bls_test import ( "encoding/hex" "strings" "testing" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPublicKeyCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandBLSKeyPair() pub2 := new(bls.PublicKey) bs, err := pub1.MarshalCBOR() require.NoError(t, err) require.NoError(t, pub2.UnmarshalCBOR(bs)) assert.True(t, pub1.EqualsTo(pub2)) require.Error(t, pub2.UnmarshalCBOR([]byte("abcd"))) inv, _ := hex.DecodeString(strings.Repeat("ff", bls.PublicKeySize)) data, _ := cbor.Marshal(inv) require.NoError(t, pub2.UnmarshalCBOR(data)) _, err = pub2.PointG2() require.Error(t, err) } func TestPublicKeyEqualsTo(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() pub3, _ := ts.RandEd25519KeyPair() assert.True(t, pub1.EqualsTo(pub1)) assert.False(t, pub1.EqualsTo(pub2)) assert.False(t, pub1.EqualsTo(pub3)) } func TestPublicKeyEncoding(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandBLSKeyPair() fw1 := util.NewFixedWriter(20) require.Error(t, pub.Encode(fw1)) fw2 := util.NewFixedWriter(bls.PublicKeySize) require.NoError(t, pub.Encode(fw2)) fr1 := util.NewFixedReader(20, fw2.Bytes()) require.Error(t, pub.Decode(fr1)) fr2 := util.NewFixedReader(bls.PublicKeySize, fw2.Bytes()) require.NoError(t, pub.Decode(fr2)) assert.Equal(t, bls.PublicKeySize, pub.SerializeSize()) } func TestPublicKeyVerifyAddress(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() err := pub1.VerifyAddress(pub1.AccountAddress()) require.NoError(t, err) err = pub1.VerifyAddress(pub1.ValidatorAddress()) require.NoError(t, err) err = pub1.VerifyAddress(pub2.AccountAddress()) assert.Equal(t, crypto.AddressMismatchError{ Expected: pub1.AccountAddress(), Got: pub2.AccountAddress(), }, err) err = pub1.VerifyAddress(pub2.ValidatorAddress()) assert.Equal(t, crypto.AddressMismatchError{ Expected: pub1.ValidatorAddress(), Got: pub2.ValidatorAddress(), }, err) } func TestNilPublicKey(t *testing.T) { ts := testsuite.NewTestSuite(t) pub := &bls.PublicKey{} randSig := ts.RandBLSSignature() require.Error(t, pub.VerifyAddress(ts.RandAccAddress())) require.Error(t, pub.VerifyAddress(ts.RandValAddress())) require.Error(t, pub.Verify(nil, nil)) require.Error(t, pub.Verify(nil, &bls.Signature{})) require.Error(t, pub.Verify(nil, randSig)) } func TestNilSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandBLSKeyPair() require.Error(t, pub.Verify(nil, nil)) require.Error(t, pub.Verify(nil, &bls.Signature{})) } func TestPublicKeyFromString(t *testing.T) { tests := []struct { errMsg string encoded string valid bool result []byte }{ { "invalid separator index -1", "not_proper_encoded", false, nil, }, { "invalid bech32 string length 0", "", false, nil, }, { "invalid character not part of charset: 105", "public1ioiooi", false, nil, }, { "invalid bech32 string length 0", "public134jkgz", false, nil, }, { "invalid HRP: xxx", "xxx1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjrvqc" + "vf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5evslaq", false, nil, }, { "invalid checksum (expected jhx47a got jhx470)", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5jhx470", false, nil, }, { "invalid length: 95", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg73y98kl", false, nil, }, { "invalid signature type: 2", "public1z372l5frmm5e7cn7ewfjdkx5t7y62kztqr82rtatat70cl8p8ng3rdzr02mzpwcfl6s2v26kry6mwg" + "xpqy92ywx9wtff80mc9p3kr4cmhgekj048gavx2zdh78tsnh7eg5jzdw6s3et6c0dqyp22vslcgkukxh4l4", false, nil, }, { "", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5jhx47a", true, []byte{ 0xaf, 0x0f, 0x74, 0x91, 0x7f, 0x50, 0x65, 0xaf, 0x94, 0x72, 0x7a, 0xe9, 0x54, 0x1b, 0x0d, 0xdc, 0xfb, 0x5b, 0x82, 0x8a, 0x9e, 0x01, 0x6b, 0x02, 0x49, 0x8f, 0x47, 0x7e, 0xd3, 0x7f, 0xb4, 0x4d, 0x5d, 0x88, 0x24, 0x95, 0xaf, 0xb6, 0xfd, 0x4f, 0x97, 0x73, 0xe4, 0xea, 0x9d, 0xee, 0xe4, 0x36, 0x03, 0x0c, 0x4d, 0x61, 0xc6, 0xe3, 0xa1, 0x15, 0x15, 0x85, 0xe1, 0xd8, 0x38, 0xca, 0xe1, 0x44, 0x4a, 0x43, 0x8d, 0x08, 0x9c, 0xe7, 0x7e, 0x10, 0xc4, 0x92, 0xa5, 0x5f, 0x69, 0x08, 0x12, 0x5c, 0x5b, 0xe9, 0xb2, 0x36, 0xa2, 0x46, 0xe4, 0x08, 0x2d, 0x08, 0xde, 0x56, 0x4e, 0x11, 0x1e, 0x65, }, }, } for no, tt := range tests { pub, err := bls.PublicKeyFromString(tt.encoded) if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.result, pub.Bytes(), "test %v: invalid bytes", no) assert.Equal(t, tt.encoded, pub.String(), "test %v: invalid encoded", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } func TestPointG2(t *testing.T) { tests := []struct { errMsg string encoded string valid bool }{ { "short buffer", "public1pqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqjzu9w8", false, }, { "invalid point encoding", "public1pllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll" + "llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllluhpuzyf", false, }, { "invalid public key", "public1pcqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqglnhh9", false, }, { "", "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5jhx47a", true, }, } for no, tt := range tests { pub, err := bls.PublicKeyFromString(tt.encoded) require.NoError(t, err) _, err = pub.PointG2() if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } ================================================ FILE: crypto/bls/signature.go ================================================ package bls import ( "bytes" "crypto/subtle" "encoding/hex" "io" bls12381 "github.com/consensys/gnark-crypto/ecc/bls12-381" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util/encoding" ) var _ crypto.Signature = &Signature{} const SignatureSize = 48 type Signature struct { pointG1 *bls12381.G1Affine // Lazily initialized point on G1. data []byte // Raw signature data. } // SignatureFromString decodes the input string and returns the Signature // if the string is a valid hexadecimal encoding of a BLS signature. func SignatureFromString(text string) (*Signature, error) { data, err := hex.DecodeString(text) if err != nil { return nil, err } return SignatureFromBytes(data) } // SignatureFromBytes constructs a BLS signature from the raw bytes. func SignatureFromBytes(data []byte) (*Signature, error) { if len(data) != SignatureSize { return nil, crypto.InvalidLengthError(len(data)) } return &Signature{data: data}, nil } // Bytes returns the raw byte representation of the signature. func (sig *Signature) Bytes() []byte { return sig.data } // String returns the hex-encoded string representation of the signature. func (sig *Signature) String() string { return hex.EncodeToString(sig.Bytes()) } // MarshalCBOR encodes the signature into CBOR format. func (sig *Signature) MarshalCBOR() ([]byte, error) { return cbor.Marshal(sig.Bytes()) } // UnmarshalCBOR decodes the signature from CBOR format. func (sig *Signature) UnmarshalCBOR(bs []byte) error { var data []byte if err := cbor.Unmarshal(bs, &data); err != nil { return err } return sig.Decode(bytes.NewReader(data)) } // Encode writes the raw bytes of the signature to the provided writer. func (sig *Signature) Encode(w io.Writer) error { return encoding.WriteElements(w, sig.Bytes()) } // Decode reads the raw bytes of the signature from the provided reader and initializes the signature. func (sig *Signature) Decode(r io.Reader) error { data := make([]byte, SignatureSize) err := encoding.ReadElements(r, data) if err != nil { return err } s, _ := SignatureFromBytes(data) *sig = *s return nil } func (*Signature) SerializeSize() int { return SignatureSize } // EqualsTo checks if the current signature is equal to another signature. func (sig *Signature) EqualsTo(x crypto.Signature) bool { xBLS, ok := x.(*Signature) if !ok { return false } return subtle.ConstantTimeCompare(sig.data, xBLS.data) == 1 } // PointG1 returns the point on G1 for the signature. func (sig *Signature) PointG1() (*bls12381.G1Affine, error) { if sig.pointG1 != nil { return sig.pointG1, nil } g1Aff := new(bls12381.G1Affine) err := g1Aff.Unmarshal(sig.data) if err != nil { return nil, err } if g1Aff.IsInfinity() || !g1Aff.IsInSubGroup() { return nil, crypto.ErrInvalidPublicKey } sig.pointG1 = g1Aff return g1Aff, nil } ================================================ FILE: crypto/bls/signature_test.go ================================================ package bls_test import ( "encoding/hex" "strings" "testing" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSignatureCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv := ts.RandBLSKeyPair() sig1 := prv.Sign(ts.RandBytes(16)) sig2 := new(bls.Signature) bs, err := sig1.MarshalCBOR() require.NoError(t, err) require.NoError(t, sig2.UnmarshalCBOR(bs)) assert.True(t, sig1.EqualsTo(sig2)) require.Error(t, sig2.UnmarshalCBOR([]byte("abcd"))) inv, _ := hex.DecodeString(strings.Repeat("ff", bls.SignatureSize)) data, _ := cbor.Marshal(inv) require.NoError(t, sig2.UnmarshalCBOR(data)) _, err = sig2.PointG1() require.Error(t, err) } func TestSignatureEqualsTo(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv1 := ts.RandBLSKeyPair() _, prv2 := ts.RandBLSKeyPair() _, prv3 := ts.RandEd25519KeyPair() sig1 := prv1.Sign([]byte("foo")) sig2 := prv2.Sign([]byte("foo")) sig3 := prv3.Sign([]byte("foo")) assert.True(t, sig1.EqualsTo(sig1)) assert.False(t, sig1.EqualsTo(sig2)) assert.False(t, sig1.EqualsTo(sig3)) } func TestSignatureEncoding(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv := ts.RandBLSKeyPair() sig := prv.Sign(ts.RandBytes(16)) fw1 := util.NewFixedWriter(20) require.Error(t, sig.Encode(fw1)) fw2 := util.NewFixedWriter(bls.SignatureSize) require.NoError(t, sig.Encode(fw2)) fr1 := util.NewFixedReader(20, fw2.Bytes()) require.Error(t, sig.Decode(fr1)) fr2 := util.NewFixedReader(bls.SignatureSize, fw2.Bytes()) require.NoError(t, sig.Decode(fr2)) assert.Equal(t, bls.SignatureSize, sig.SerializeSize()) } func TestVerifyingSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) msg := []byte("pactus") pb1, pv1 := ts.RandBLSKeyPair() pb2, pv2 := ts.RandBLSKeyPair() sig1 := pv1.Sign(msg) sig2 := pv2.Sign(msg) assert.False(t, sig1.EqualsTo(sig2)) require.NoError(t, pb1.Verify(msg, sig1)) require.NoError(t, pb2.Verify(msg, sig2)) require.ErrorIs(t, pb1.Verify(msg, sig2), crypto.ErrInvalidSignature) require.ErrorIs(t, pb2.Verify(msg, sig1), crypto.ErrInvalidSignature) require.ErrorIs(t, pb1.Verify(msg[1:], sig1), crypto.ErrInvalidSignature) } func TestSignatureFromString(t *testing.T) { tests := []struct { errMsg string encoded string valid bool bytes []byte }{ { "encoding/hex: invalid byte: U+006E 'n'", "not_proper_encoded", false, nil, }, { "invalid length: 0", "", false, nil, }, { "encoding/hex: odd length hex string", "0", false, nil, }, { "invalid length: 1", "00", false, nil, }, { "", "ad0f88cec815e9b8af3f0136297cb242ed8b6369af723fbdac077fa927f5780db7df47c77fb53f3a22324673f000c792", true, []byte{ 0xad, 0x0f, 0x88, 0xce, 0xc8, 0x15, 0xe9, 0xb8, 0xaf, 0x3f, 0x01, 0x36, 0x29, 0x7c, 0xb2, 0x42, 0xed, 0x8b, 0x63, 0x69, 0xaf, 0x72, 0x3f, 0xbd, 0xac, 0x07, 0x7f, 0xa9, 0x27, 0xf5, 0x78, 0x0d, 0xb7, 0xdf, 0x47, 0xc7, 0x7f, 0xb5, 0x3f, 0x3a, 0x22, 0x32, 0x46, 0x73, 0xf0, 0x00, 0xc7, 0x92, }, }, } for no, tt := range tests { sig, err := bls.SignatureFromString(tt.encoded) if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.bytes, sig.Bytes(), "test %v: invalid bytes", no) assert.Equal(t, tt.encoded, sig.String(), "test %v: invalid encode", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } func TestPointG1(t *testing.T) { tests := []struct { errMsg string encoded string valid bool }{ { "short buffer", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", false, }, { "invalid point encoding", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", false, }, { "invalid public key", "c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", false, }, { "", "ad0f88cec815e9b8af3f0136297cb242ed8b6369af723fbdac077fa927f5780db7df47c77fb53f3a22324673f000c792", true, }, } for no, tt := range tests { sig, err := bls.SignatureFromString(tt.encoded) require.NoError(t, err) _, err = sig.PointG1() if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } ================================================ FILE: crypto/bls/validator_key.go ================================================ package bls import ( "github.com/pactus-project/pactus/crypto" ) // ValidatorKey wraps a BLS private key, caching its public key and validator address. type ValidatorKey struct { address crypto.Address publicKey *PublicKey privateKey *PrivateKey } func NewValidatorKey(prv *PrivateKey) *ValidatorKey { pub := prv.PublicKeyNative() return &ValidatorKey{ privateKey: prv, publicKey: pub, address: pub.ValidatorAddress(), } } func (key *ValidatorKey) Address() crypto.Address { return key.address } func (key *ValidatorKey) PublicKey() *PublicKey { return key.publicKey } func (key *ValidatorKey) PrivateKey() *PrivateKey { return key.privateKey } func (key *ValidatorKey) Sign(data []byte) *Signature { return key.privateKey.SignNative(data) } ================================================ FILE: crypto/bls/validator_key_test.go ================================================ package bls_test import ( "testing" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestValidatorKey(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, prv := ts.RandBLSKeyPair() valKey := bls.NewValidatorKey(prv) sig := valKey.Sign([]byte("foo")) assert.Equal(t, prv, valKey.PrivateKey()) assert.Equal(t, pub, valKey.PublicKey()) assert.Equal(t, pub.ValidatorAddress(), valKey.Address()) require.NoError(t, pub.Verify([]byte("foo"), sig)) } ================================================ FILE: crypto/crypto.go ================================================ package crypto var ( // AddressHRP is the Human Readable Part (HRP) for address. AddressHRP = "pc" // PublicKeyHRP is the Human Readable Part (HRP) for public key. PublicKeyHRP = "public" // PrivateKeyHRP is the Human Readable Part (HRP) for private key. PrivateKeyHRP = "secret" // XPublicKeyHRP is the Human Readable Part (HRP) for extended public key. XPublicKeyHRP = "xpublic" // XPrivateKeyHRP is the Human Readable Part (HRP) for extended private key. XPrivateKeyHRP = "xsecret" ) // ToTestnetHRP makes HRPs testnet specified. func ToTestnetHRP() { AddressHRP = "tpc" PublicKeyHRP = "tpublic" PrivateKeyHRP = "tsecret" XPublicKeyHRP = "txpublic" XPrivateKeyHRP = "txsecret" } // ToMainnetHRP makes HRPs mainnet specified. func ToMainnetHRP() { AddressHRP = "pc" PublicKeyHRP = "public" PrivateKeyHRP = "secret" XPublicKeyHRP = "xpublic" XPrivateKeyHRP = "xsecret" } ================================================ FILE: crypto/ed25519/ed25519.go ================================================ // Package ed25519 provides Ed25519 signature primitives for Pactus. // // It implements EdDSA over the Twisted Edwards curve Ed25519 as specified in // RFC 8032. The package exposes PrivateKey, PublicKey, and Signature types as // the main API, along with deterministic signing and verification. package ed25519 ================================================ FILE: crypto/ed25519/ed25519_test.go ================================================ package ed25519_test import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSigning(t *testing.T) { msg := []byte("pactus") prv, _ := ed25519.PrivateKeyFromString( "SECRET1R3K02X58V70X9RFVWN5QUN0CKHKYXWD7R40G3HX47L8W9HXJQHMASKGEPH2") pub, _ := ed25519.PublicKeyFromString( "public1rd5p573yq3j5wkvnasslqa7ne5vw87qcj5a0wlwxcj2t2xlaca9lstzm8u5") sig, _ := ed25519.SignatureFromString( "d444363761156890e781e73ae545951826d640a9d5ba44effa67fd5a77fad92a" + "fb3d46f82a86c7d283d7713e72bbd8ed39e7ac505d996f4f214e39b0a3b95f0a") addr, _ := crypto.AddressFromString("pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3") sig1 := prv.Sign(msg) assert.Equal(t, sig.Bytes(), sig1.Bytes()) require.NoError(t, pub.Verify(msg, sig)) assert.Equal(t, pub, prv.PublicKey()) assert.Equal(t, addr, pub.AccountAddress()) } // TestEd25519S ensures that the implementation of the Ed25519 signature scheme // conforms to the specifications outlined in RFC8032. We are using test vectors // to verify that the signature generation and verification work as intended: // https://www.rfc-editor.org/rfc/rfc8032.txt func TestEd25519S(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { sk string pk string msg string sig string }{ { "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "", // MESSAGE (length 0 bytes) "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155" + "5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", }, { "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72", // MESSAGE (length 1 byte) "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da" + "085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", }, { "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", "af82", // MESSAGE (length 2 bytes) "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac" + "18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a", }, { "f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5", "278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e", "08b8b2b733424243760fe426a4b54908632110a66c2f6591eabd3345e3e4eb98" + // MESSAGE (length 1023 bytes) "fa6e264bf09efe12ee50f8f54e9f77b1e355f6c50544e23fb1433ddf73be84d8" + "79de7c0046dc4996d9e773f4bc9efe5738829adb26c81b37c93a1b270b20329d" + "658675fc6ea534e0810a4432826bf58c941efb65d57a338bbd2e26640f89ffbc" + "1a858efcb8550ee3a5e1998bd177e93a7363c344fe6b199ee5d02e82d522c4fe" + "ba15452f80288a821a579116ec6dad2b3b310da903401aa62100ab5d1a36553e" + "06203b33890cc9b832f79ef80560ccb9a39ce767967ed628c6ad573cb116dbef" + "efd75499da96bd68a8a97b928a8bbc103b6621fcde2beca1231d206be6cd9ec7" + "aff6f6c94fcd7204ed3455c68c83f4a41da4af2b74ef5c53f1d8ac70bdcb7ed1" + "85ce81bd84359d44254d95629e9855a94a7c1958d1f8ada5d0532ed8a5aa3fb2" + "d17ba70eb6248e594e1a2297acbbb39d502f1a8c6eb6f1ce22b3de1a1f40cc24" + "554119a831a9aad6079cad88425de6bde1a9187ebb6092cf67bf2b13fd65f270" + "88d78b7e883c8759d2c4f5c65adb7553878ad575f9fad878e80a0c9ba63bcbcc" + "2732e69485bbc9c90bfbd62481d9089beccf80cfe2df16a2cf65bd92dd597b07" + "07e0917af48bbb75fed413d238f5555a7a569d80c3414a8d0859dc65a46128ba" + "b27af87a71314f318c782b23ebfe808b82b0ce26401d2e22f04d83d1255dc51a" + "ddd3b75a2b1ae0784504df543af8969be3ea7082ff7fc9888c144da2af58429e" + "c96031dbcad3dad9af0dcbaaaf268cb8fcffead94f3c7ca495e056a9b47acdb7" + "51fb73e666c6c655ade8297297d07ad1ba5e43f1bca32301651339e22904cc8c" + "42f58c30c04aafdb038dda0847dd988dcda6f3bfd15c4b4c4525004aa06eeff8" + "ca61783aacec57fb3d1f92b0fe2fd1a85f6724517b65e614ad6808d6f6ee34df" + "f7310fdc82aebfd904b01e1dc54b2927094b2db68d6f903b68401adebf5a7e08" + "d78ff4ef5d63653a65040cf9bfd4aca7984a74d37145986780fc0b16ac451649" + "de6188a7dbdf191f64b5fc5e2ab47b57f7f7276cd419c17a3ca8e1b939ae49e4" + "88acba6b965610b5480109c8b17b80e1b7b750dfc7598d5d5011fd2dcc5600a3" + "2ef5b52a1ecc820e308aa342721aac0943bf6686b64b2579376504ccc493d97e" + "6aed3fb0f9cd71a43dd497f01f17c0e2cb3797aa2a2f256656168e6c496afc5f" + "b93246f6b1116398a346f1a641f3b041e989f7914f90cc2c7fff357876e506b5" + "0d334ba77c225bc307ba537152f3f1610e4eafe595f6d9d90d11faa933a15ef1" + "369546868a7f3a45a96768d40fd9d03412c091c6315cf4fde7cb68606937380d" + "b2eaaa707b4c4185c32eddcdd306705e4dc1ffc872eeee475a64dfac86aba41c" + "0618983f8741c5ef68d3a101e8a3b8cac60c905c15fc910840b94c00a0b9d0", "0aab4c900501b3e24d7cdf4663326a3a87df5e4843b2cbdb67cbf6e460fec350" + "aa5371b1508f9f4528ecea23c436d94b5e8fcd4f681e30a6ac00a9704a188a03", }, } for _, tt := range tests { privateKey, _ := ed25519.PrivateKeyFromBytes(ts.DecodingHex(tt.sk)) expectedPublicKey, _ := ed25519.PublicKeyFromBytes(ts.DecodingHex(tt.pk)) msg := ts.DecodingHex(tt.msg) expectedSig, _ := ed25519.SignatureFromString(tt.sig) sig := privateKey.Sign(msg) assert.Equal(t, expectedSig, sig) assert.Equal(t, expectedPublicKey, privateKey.PublicKey()) } } ================================================ FILE: crypto/ed25519/errors.go ================================================ package ed25519 ================================================ FILE: crypto/ed25519/hdkeychain/errors.go ================================================ package hdkeychain import ( "errors" "fmt" ) var ( // ErrInvalidSeedLen describes an error in which the provided seed or // seed length is not in the allowed range. ErrInvalidSeedLen = fmt.Errorf("seed length must be between %d and %d "+ "bits", MinSeedBytes*8, MaxSeedBytes*8) // ErrInvalidKeyData describes an error in which the provided key is // not valid. ErrInvalidKeyData = errors.New("key data is invalid") // ErrInvalidHRP describes an error in which the HRP is not valid. ErrInvalidHRP = errors.New("HRP is invalid") // ErrNonHardenedPath is returned when a non-hardened derivation path is used, // which is not supported by ed25519. ErrNonHardenedPath = errors.New("non-hardened derivation not supported") ) ================================================ FILE: crypto/ed25519/hdkeychain/extendedkey.go ================================================ package hdkeychain // References: // SLIP-0010: Universal private key derivation from master private key // https://github.com/satoshilabs/slips/blob/master/slip-0010.md import ( "bytes" "crypto/ed25519" "crypto/hmac" "crypto/rand" "crypto/sha512" "encoding/binary" "strings" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/encoding" ) const ( // hardenedKeyStart is the index at which a hardened key starts. hardenedKeyStart = uint32(0x80000000) // 2^31 // MinSeedBytes is the minimum number of bytes allowed for a seed to // a master node. MinSeedBytes = 16 // 128 bits // MaxSeedBytes is the maximum number of bytes allowed for a seed to // a master node. MaxSeedBytes = 64 // 512 bits ) // ExtendedKey houses all the information needed to support a hierarchical // deterministic extended key. type ExtendedKey struct { key []byte // This will be the bytes of extended public or private key chainCode []byte path []uint32 } // newExtendedKey returns a new instance of an extended key with the given // fields. No error checking is performed here as it's only intended to be a // convenience method used to create a populated struct. func newExtendedKey(key, chainCode []byte, path []uint32) *ExtendedKey { return &ExtendedKey{ key: key, chainCode: chainCode, path: path, } } // DerivePath returns a derived child extended key from this master key at the // given path. func (k *ExtendedKey) DerivePath(path []uint32) (*ExtendedKey, error) { ext := k var err error for _, index := range path { ext, err = ext.Derive(index) if err != nil { return nil, err } } return ext, nil } // Derive returns a derived child extended key at the given index. // // For ed25519 and curve25519 the private keys are no longer multipliers for the group generator; // instead the hash of the private key is the multiplier. // For this reason, our scheme for ed25519 and curve25519 does not support public key derivation and // uses the produced hashes directly as private keys. func (k *ExtendedKey) Derive(index uint32) (*ExtendedKey, error) { isChildHardened := index >= hardenedKeyStart if !isChildHardened { return nil, ErrNonHardenedPath } // Calculate derive Data: // Data = 0x00 || ser_256(k_par) || ser_32(i) indexData := make([]byte, 4) binary.BigEndian.PutUint32(indexData, index) data := make([]byte, 0, 37) data = append(data, 0x00) data = append(data, k.key...) data = append(data, indexData...) // Take the HMAC-SHA512 of the current key's chain code and the derived // data: // I = HMAC-SHA512(Key = chainCode, Data = data) hmac512 := hmac.New(sha512.New, k.chainCode) _, _ = hmac512.Write(data) ilr := hmac512.Sum(nil) // Split I into two 32-byte sequences, IL and IR. // The returned chain code ci is IR. // The returned child key ki is IL. childChainCode := ilr[32:] childKey := ilr[:32] newPath := make([]uint32, 0, len(k.path)+1) newPath = append(newPath, k.path...) newPath = append(newPath, index) return newExtendedKey(childKey, childChainCode, newPath), nil } // Path returns the path of derived key. // // Path values are always between 2^31 and 2^32-1 as they are hardened keys. func (k *ExtendedKey) Path() []uint32 { return k.path } // RawPrivateKey returns the raw bytes of the private key. func (k *ExtendedKey) RawPrivateKey() []byte { return k.key } // RawPublicKey returns the raw bytes of the public key. func (k *ExtendedKey) RawPublicKey() []byte { pub := ed25519.NewKeyFromSeed(k.key).Public() return pub.(ed25519.PublicKey)[:] } // String returns the extended key as a bech32-encoded string. func (k *ExtendedKey) String() string { // // The serialized format is structured as follows: // +-------+---------+------------+----------+------------+----------+ // | Depth | Path | Chain code | Reserved | Key length | Key data | // +-------+---------+------------+----------+------------+----------+ // | 1 | depth*4 | 32 | 1 | 1 | 32 | // +-------+---------+------------+----------+------------+----------+ // // Description: // - Depth: 1 byte representing the depth of derivation path. // - Path: serialized BIP-32 path; each entry is encoded as 32-bit unsigned integer, least significant byte first // - Chain code: 32 bytes chain code // - Reserved: 1 byte reserved and should set to 0. // - Key length: 1 byte representing the length of the key data that is 32. // - Key data: The key data that is 32 bytes. // buf := bytes.NewBuffer(make([]byte, 0)) err := encoding.WriteElement(buf, byte(len(k.path))) if err != nil { return err.Error() } for _, p := range k.path { err := encoding.WriteElement(buf, p) if err != nil { return err.Error() } } err = encoding.WriteVarBytes(buf, k.chainCode) if err != nil { return err.Error() } err = encoding.WriteElement(buf, uint8(0)) if err != nil { return err.Error() } err = encoding.WriteVarBytes(buf, k.key) if err != nil { return err.Error() } str, err := bech32m.EncodeFromBase256WithType(crypto.XPrivateKeyHRP, crypto.SignatureTypeEd25519, buf.Bytes()) if err != nil { return err.Error() } str = strings.ToUpper(str) return str } // NewKeyFromString returns a new extended key instance from a bech32-encoded string. func NewKeyFromString(str string) (*ExtendedKey, error) { hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(strings.ToLower(str)) if err != nil { return nil, err } if typ != crypto.SignatureTypeEd25519 { return nil, ErrInvalidKeyData } if hrp != crypto.XPrivateKeyHRP { return nil, ErrInvalidHRP } reader := bytes.NewReader(data) depth := uint8(0) err = encoding.ReadElement(reader, &depth) if err != nil { return nil, err } path := make([]uint32, depth) for i := byte(0); i < depth; i++ { err := encoding.ReadElement(reader, &path[i]) if err != nil { return nil, err } } chainCode, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } var res uint8 err = encoding.ReadElement(reader, &res) if err != nil { return nil, err } key, err := encoding.ReadVarBytes(reader) if err != nil { return nil, err } return newExtendedKey(key, chainCode, path), nil } // NewMaster creates a new master node for use in creating a hierarchical // deterministic key chain. The seed must be between 128 and 512 bits and // should be generated by a cryptographically secure random generation source. func NewMaster(seed []byte) (*ExtendedKey, error) { // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes]. if len(seed) < MinSeedBytes || len(seed) > MaxSeedBytes { return nil, ErrInvalidSeedLen } // First take the HMAC-SHA512 of the master key and the seed data: // I = HMAC-SHA512(Key = Curve, Data = Seed) curve := []byte("ed25519 seed") hmac512 := hmac.New(sha512.New, curve) _, _ = hmac512.Write(seed) ilr := hmac512.Sum(nil) // Split "I" into two 32-byte sequences Il and Ir where: // Il = master key // Ir = master chain code masterChainCode := ilr[32:] masterKey := ilr[:32] return newExtendedKey(masterKey, masterChainCode, []uint32{}), nil } // GenerateSeed returns a cryptographically secure random seed that can be used // as the input for the NewMaster function to generate a new master node. // // The length is in bytes and it must be between 16 and 64 (128 to 512 bits). // The recommended length is 32 (256 bits) as defined by the RecommendedSeedLen // constant. func GenerateSeed(length uint8) ([]byte, error) { // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes]. if length < MinSeedBytes || length > MaxSeedBytes { return nil, ErrInvalidSeedLen } buf := make([]byte, length) _, err := rand.Read(buf) if err != nil { return nil, err } return buf, nil } ================================================ FILE: crypto/ed25519/hdkeychain/extendedkey_test.go ================================================ package hdkeychain import ( "encoding/hex" "io" "testing" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestNonHardenedDerivation tests deriving a new key in non-hardened mode. // It should return an error. func TestNonHardenedDerivation(t *testing.T) { ts := testsuite.NewTestSuite(t) testSeed := ts.RandBytes(32) path := []uint32{ ts.RandUint32Max(hardenedKeyStart), } masterKey, _ := NewMaster(testSeed) _, err := masterKey.DerivePath(path) require.ErrorIs(t, err, ErrNonHardenedPath) } // TestHardenedDerivation tests derive key in hardened mode. func TestHardenedDerivation(t *testing.T) { ts := testsuite.NewTestSuite(t) testSeed := ts.RandBytes(32) path := []uint32{ ts.RandUint32Max(hardenedKeyStart) + hardenedKeyStart, } masterKey, err := NewMaster(testSeed) require.NoError(t, err) extKey, err := masterKey.DerivePath(path) require.NoError(t, err) assert.Equal(t, path, extKey.Path()) } // TestDerivation verifies the derivation of new keys in hardened mode. // The test cases are based on the SLIP-0010 standard. func TestDerivation(t *testing.T) { testSeed, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f") h := hardenedKeyStart tests := []struct { name string path []uint32 wantPrv string wantPub string }{ { name: "derivation path: m", path: []uint32{}, wantPrv: "2b4be7f19ee27bbf30c667b642d5f4aa69fd169872f8fc3059c08ebae2eb19e7", wantPub: "a4b2856bfec510abab89753fac1ac0e1112364e7d250545963f135f2a33188ed", }, { name: "derivation path: m/0H", path: []uint32{h}, wantPrv: "68e0fe46dfb67e368c75379acec591dad19df3cde26e63b93a8e704f1dade7a3", wantPub: "8c8a13df77a28f3445213a0f432fde644acaa215fc72dcdf300d5efaa85d350c", }, { name: "derivation path: m/0H/1H", path: []uint32{h, 1 + h}, wantPrv: "b1d0bad404bf35da785a64ca1ac54b2617211d2777696fbffaf208f746ae84f2", wantPub: "1932a5270f335bed617d5b935c80aedb1a35bd9fc1e31acafd5372c30f5c1187", }, { name: "derivation path: m/0H/1H/2H", path: []uint32{h, 1 + h, 2 + h}, wantPrv: "92a5b23c0b8a99e37d07df3fb9966917f5d06e02ddbd909c7e184371463e9fc9", wantPub: "ae98736566d30ed0e9d2f4486a64bc95740d89c7db33f52121f8ea8f76ff0fc1", }, { name: "derivation path: m/0H/1H/2H/2H", path: []uint32{h, 1 + h, 2 + h, 2 + h}, wantPrv: "30d1dc7e5fc04c31219ab25a27ae00b50f6fd66622f6e9c913253d6511d1e662", wantPub: "8abae2d66361c879b900d204ad2cc4984fa2aa344dd7ddc46007329ac76c429c", }, { name: "derivation path: m/0H/1H/2H/2H/1000000000H", path: []uint32{h, 1 + h, 2 + h, 2 + h, 1000000000 + h}, wantPrv: "8f94d394a8e8fd6b1bc2f3f49f5c47e385281d5c17e65324b0f62483e37e8793", wantPub: "3c24da049451555d51a7014a37337aa4e12d41e485abccfa46b47dfb2af54b7a", }, } masterKey, _ := NewMaster(testSeed) for no, tt := range tests { extKey, err := masterKey.DerivePath(tt.path) require.NoError(t, err) privKey := extKey.RawPrivateKey() require.Equal(t, tt.wantPrv, hex.EncodeToString(privKey), "mismatched serialized private key for test #%v", no+1) pubKey := extKey.RawPublicKey() require.Equal(t, tt.wantPub, hex.EncodeToString(pubKey), "mismatched serialized public key for test #%v", no+1) require.Equal(t, tt.path, extKey.Path()) } } // TestGenerateSeed ensures the GenerateSeed function works as intended. func TestGenerateSeed(t *testing.T) { tests := []struct { name string length uint8 err error }{ // Test various valid lengths. {name: "16 bytes", length: 16}, {name: "17 bytes", length: 17}, {name: "20 bytes", length: 20}, {name: "32 bytes", length: 32}, {name: "64 bytes", length: 64}, // Test invalid lengths. {name: "15 bytes", length: 15, err: ErrInvalidSeedLen}, {name: "65 bytes", length: 65, err: ErrInvalidSeedLen}, } for no, tt := range tests { seed, err := GenerateSeed(tt.length) require.ErrorIs(t, err, tt.err) if tt.err == nil { assert.Len(t, seed, int(tt.length), "GenerateSeed #%d (%s): length mismatch -- got %d, want %d", no+1, tt.name, len(seed), tt.length) } } } // TestNewMaster ensures the NewMaster function works as intended. func TestNewMaster(t *testing.T) { tests := []struct { name string seed string key string err error }{ // Test various valid seeds. { name: "16 bytes", seed: "000102030405060708090a0b0c0d0e0f", key: "2b4be7f19ee27bbf30c667b642d5f4aa69fd169872f8fc3059c08ebae2eb19e7", }, { name: "32 bytes", seed: "3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678", key: "4b36bc63a15797f4d506074f36f2f3904bc0f10179b5ab91183c167e9c2dcf0e", }, { name: "64 bytes", seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784" + "817e7b7875726f6c696663605d5a5754514e4b484542", key: "171cb88b1b3c1db25add599712e36245d75bc65a1a5c9e18d76f9f2b1eab4012", }, // Test invalid seeds. { name: "empty seed", seed: "", err: ErrInvalidSeedLen, }, { name: "15 bytes", seed: "000000000000000000000000000000", err: ErrInvalidSeedLen, }, { name: "65 bytes", seed: "000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000", err: ErrInvalidSeedLen, }, } for no, tt := range tests { seed, _ := hex.DecodeString(tt.seed) extKey, err := NewMaster(seed) require.ErrorIs(t, err, tt.err) if tt.err == nil { privKey := extKey.RawPrivateKey() assert.Equal(t, tt.key, hex.EncodeToString(privKey), "NewMaster #%d (%s): key mismatch -- got %x, want %s", no+1, tt.name, privKey, tt.key) } } } // TestKeyToString ensures the String function works as intended. // //nolint:lll // long extended keys func TestKeyToString(t *testing.T) { testSeed, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f") h := hardenedKeyStart tests := []struct { name string path []uint32 wantXPriv string }{ { name: "derivation path: m", path: []uint32{}, wantXPriv: "XSECRET1RQQSFQPR2J0098Q989D0Y2QG8FPT86H4Q9WLK2GHE08S9CRVD3J5LL7CQYQ45HEL3NM38H0ESCENMVSK47J4XNLGKNPE03LPST8QGAWHZAVV7WQ3TTQ3", }, { name: "derivation path: m/0H", path: []uint32{h}, wantXPriv: "XSECRET1RQYQQQQYQYZ94N2S38Q9KYN5P2PAZ0LKA5K075MGTW7D80ZGC5T7NTY8PD6WXJQPQDRS0U3KLKELRDRR4X7DVA3V3MTGEMU7DUFHX8WF63ECY78DDU73SSP8VGW", }, { name: "derivation path: m/0H/1H", path: []uint32{h, 1 + h}, wantXPriv: "XSECRET1RQGQQQQYQQYQQPQPQ5VSYYHMH6X6UY5Z6DVDJWWPTXUMGAEJQUD2HCV25Z6QPYS649U2QQG936ZADGP9LXHD8SKNYEGDV2JEXZUS36FMHD9HML7HJPRM5DT5Y7GG0AYKR", }, { name: "derivation path: m/0H/1H/2H", path: []uint32{h, 1 + h, 2 + h}, wantXPriv: "XSECRET1RQVQQQQYQQYQQPQQZQQQGQGPWDXFFUQ944VJS7JWRLVWP9UJJME876TQAHZPCWZ22P7XYE8XDDSQZPY49KG7QHZ5EUD7S0HELHXTXJ9L46PHQ9HDAJZW8UXZRW9RRA87FNLUP3Y", }, { name: "derivation path: m/0H/1H/2H/2H", path: []uint32{h, 1 + h, 2 + h, 2 + h}, wantXPriv: "XSECRET1RQSQQQQYQQYQQPQQZQQQGQQSQQZQZPRMDSLUN6AGWPM7VMGQH6E32RVC6YEHY5M6EJWC47HQLQLM5M4WVQQSRP5WU0E0UQNP3YXDTYK384CQT2RM06ENZ9AHFEYFJ20T9Z8G7VCSW77AAC", }, { name: "derivation path: m/0H/1H/2H/2H/1000000000H", path: []uint32{h, 1 + h, 2 + h, 2 + h, 1000000000 + h}, wantXPriv: "XSECRET1RQ5QQQQYQQYQQPQQZQQQGQQSQQZQQPJ56HVSXS7YEYWSV4SKDTG53W2J8TL57P7C5E44DKKKE3GL6WQENU7H6YVQQYZ8EF5U54R5066CMCTELF86UGL3C22QATST7V5EYKRMZFQLR06REXGPVGYE", }, } masterKey, _ := NewMaster(testSeed) for no, tt := range tests { extKey, _ := masterKey.DerivePath(tt.path) require.Equal(t, tt.wantXPriv, extKey.String(), "test %d failed", no) recoveredExtKey, err := NewKeyFromString(tt.wantXPriv) require.NoError(t, err) require.Equal(t, extKey, recoveredExtKey) require.Equal(t, tt.path, recoveredExtKey.path) } } // TestInvalidString checks errors corresponding to the invalid strings // //nolint:lll // long extended private keys func TestInvalidString(t *testing.T) { tests := []struct { desc string str string expectedError error }{ { desc: "invalid checksum", str: "XSECRET1RQGQQQQYQQYQQPQPQ5VSYYHMH6X6UY5Z6DVDJWWPTXUMGAEJQUD2HCV25Z6QPYS649U2QQG936ZADGP9LXHD8SKNYEGDV2JEXZUS36FMHD9HML7HJPRM5DT5Y7GG0AYRK", expectedError: bech32m.InvalidChecksumError{Expected: "g0aykr", Actual: "g0ayrk"}, }, { desc: "no depth", str: "XSECRET1RFK28CY", expectedError: io.EOF, }, { desc: "wrong path", str: "XSECRET1RQGQQQQYQ6EJ6DE", expectedError: io.EOF, }, { desc: "no chain code", str: "XSECRET1RQGQQQQYQQYQQPQQ98TS98", expectedError: io.EOF, }, { desc: "no reserved", str: "XSECRET1RQGQQQQYQQYQQPQPQ5VSYYHMH6X6UY5Z6DVDJWWPTXUMGAEJQUD2HCV25Z6QPYS649U2Q8GUZZJ", expectedError: io.EOF, }, { desc: "no key", str: "XSECRET1RQGQQQQYQQYQQPQPQ5VSYYHMH6X6UY5Z6DVDJWWPTXUMGAEJQUD2HCV25Z6QPYS649U2QQ85HSJA", expectedError: io.EOF, }, { desc: "invalid type", str: "XSECRET1YQGQQQQYQQYQQPQPQ5VSYYHMH6X6UY5Z6DVDJWWPTXUMGAEJQUD2HCV25Z6QPYS649U2QQG936ZADGP9LXHD8SKNYEGDV2JEXZUS36FMHD9HML7HJPRM5DT5Y7GTKSQQT", expectedError: ErrInvalidKeyData, }, { desc: "invalid hrp", str: "SECRET1RQGQQQQYQQYQQPQPQ5VSYYHMH6X6UY5Z6DVDJWWPTXUMGAEJQUD2HCV25Z6QPYS649U2QQG936ZADGP9LXHD8SKNYEGDV2JEXZUS36FMHD9HML7HJPRM5DT5Y7GYQ7VAT", expectedError: ErrInvalidHRP, }, } for no, tt := range tests { _, err := NewKeyFromString(tt.str) require.ErrorIs(t, err, tt.expectedError, "test %d error is not matched", no) } } ================================================ FILE: crypto/ed25519/private_key.go ================================================ package ed25519 import ( "crypto/ed25519" "strings" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util/bech32m" ) var _ crypto.PrivateKey = &PrivateKey{} const PrivateKeySize = 32 type PrivateKey struct { inner ed25519.PrivateKey } // PrivateKeyFromString decodes the input string and returns the PrivateKey // if the string is a valid bech32m encoding of a Ed25519 public key. func PrivateKeyFromString(text string) (*PrivateKey, error) { // Decode the bech32m encoded private key. hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(text) if err != nil { return nil, err } // Check if hrp is valid if hrp != crypto.PrivateKeyHRP { return nil, crypto.InvalidHRPError(hrp) } if typ != crypto.SignatureTypeEd25519 { return nil, crypto.InvalidSignatureTypeError(typ) } return PrivateKeyFromBytes(data) } // PrivateKeyFromBytes constructs a ED25519 private key from the raw bytes. func PrivateKeyFromBytes(data []byte) (*PrivateKey, error) { if len(data) != PrivateKeySize { return nil, crypto.InvalidLengthError(len(data)) } inner := ed25519.NewKeyFromSeed(data) return &PrivateKey{inner}, nil } // String returns a human-readable string for the ED25519 private key. func (prv *PrivateKey) String() string { str, _ := bech32m.EncodeFromBase256WithType( crypto.PrivateKeyHRP, crypto.SignatureTypeEd25519, prv.Bytes()) return strings.ToUpper(str) } // Bytes return the raw bytes of the private key. func (prv *PrivateKey) Bytes() []byte { return prv.inner[:PrivateKeySize] } // Sign calculates the signature from the private key and given message. // It's defined in section 2.6 of the spec: CoreSign. func (prv *PrivateKey) Sign(msg []byte) crypto.Signature { return prv.SignNative(msg) } func (prv *PrivateKey) SignNative(msg []byte) *Signature { sig := ed25519.Sign(prv.inner, msg) return &Signature{ data: sig, } } func (prv *PrivateKey) PublicKeyNative() *PublicKey { pub := prv.inner.Public() // TODO: fix me, should get from scalar multiplication. return &PublicKey{ inner: pub.(ed25519.PublicKey), } } func (prv *PrivateKey) PublicKey() crypto.PublicKey { return prv.PublicKeyNative() } func (prv *PrivateKey) EqualsTo(x crypto.PrivateKey) bool { xEd25519, ok := x.(*PrivateKey) if !ok { return false } return prv.inner.Equal(xEd25519.inner) } ================================================ FILE: crypto/ed25519/private_key_test.go ================================================ package ed25519_test import ( "strings" "testing" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPrivateKeyEqualsTo(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv1 := ts.RandEd25519KeyPair() _, prv2 := ts.RandEd25519KeyPair() _, prv3 := ts.RandBLSKeyPair() assert.True(t, prv1.EqualsTo(prv1)) assert.False(t, prv1.EqualsTo(prv2)) assert.False(t, prv1.EqualsTo(prv3)) } func TestPrivateKeyFromString(t *testing.T) { tests := []struct { errMsg string encoded string valid bool result []byte }{ { "invalid separator index -1", "not_proper_encoded", false, nil, }, { "invalid checksum (expected uuk3y0 got uuk30y)", "SECRET1RYY62A96X25ZAL4DPL5Z63G83GCSFCCQ7K0CMQD3MFNLYK3A6R26QUUK30Y", false, nil, }, { "invalid HRP: xxx", "XXX1RYY62A96X25ZAL4DPL5Z63G83GCSFCCQ7K0CMQD3MFNLYK3A6R26Q8JXUV6", false, nil, }, { "invalid signature type: 4", "SECRET1YVKPE43FDU9TC4C8LPFD4JY9METET3GEKQE7E7ECK4EJYV20WVAPQZCU0KL", false, nil, }, { "invalid length: 31", "SECRET1RDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CCPV3HNE", false, nil, }, { "", "SECRET1RJ6STNTA7Y3P2QLQF8A6QCX05F2H5TFNE5RSH066KZME4WVFXKE7QW097LG", true, []byte{ 0x96, 0xa0, 0xb9, 0xaf, 0xbe, 0x24, 0x42, 0xa0, 0x7c, 0x09, 0x3f, 0x74, 0x0c, 0x19, 0xf4, 0x4a, 0xaf, 0x45, 0xa6, 0x79, 0xa0, 0xe1, 0x77, 0xeb, 0x56, 0x16, 0xf3, 0x57, 0x31, 0x26, 0xb6, 0x7c, }, }, } for no, tt := range tests { prv, err := ed25519.PrivateKeyFromString(tt.encoded) if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.result, prv.Bytes(), "test %v: invalid bytes", no) assert.Equal(t, strings.ToUpper(tt.encoded), prv.String(), "test %v: invalid encoded", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } ================================================ FILE: crypto/ed25519/public_key.go ================================================ package ed25519 import ( "bytes" "crypto/ed25519" "io" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/util/bech32m" "github.com/pactus-project/pactus/util/encoding" ) var _ crypto.PublicKey = &PublicKey{} const PublicKeySize = 32 type PublicKey struct { inner ed25519.PublicKey } // PublicKeyFromString decodes the input string and returns the PublicKey // if the string is a valid bech32m encoding of a Ed25519 public key. func PublicKeyFromString(text string) (*PublicKey, error) { // Decode the bech32m encoded public key. hrp, typ, data, err := bech32m.DecodeToBase256WithTypeNoLimit(text) if err != nil { return nil, err } // Check if hrp is valid if hrp != crypto.PublicKeyHRP { return nil, crypto.InvalidHRPError(hrp) } if typ != crypto.SignatureTypeEd25519 { return nil, crypto.InvalidSignatureTypeError(typ) } return PublicKeyFromBytes(data) } // PublicKeyFromBytes constructs a Ed25519 public key from the raw bytes. func PublicKeyFromBytes(data []byte) (*PublicKey, error) { if len(data) != PublicKeySize { return nil, crypto.InvalidLengthError(len(data)) } return &PublicKey{data}, nil } // Bytes returns the raw byte representation of the public key. func (pub *PublicKey) Bytes() []byte { return pub.inner } // String returns a human-readable string for the Ed25519 public key. func (pub *PublicKey) String() string { str, _ := bech32m.EncodeFromBase256WithType( crypto.PublicKeyHRP, crypto.SignatureTypeEd25519, pub.Bytes()) return str } // MarshalCBOR encodes the public key into CBOR format. func (pub *PublicKey) MarshalCBOR() ([]byte, error) { return cbor.Marshal(pub.Bytes()) } // UnmarshalCBOR decodes the public key from CBOR format. func (pub *PublicKey) UnmarshalCBOR(bs []byte) error { var data []byte if err := cbor.Unmarshal(bs, &data); err != nil { return err } return pub.Decode(bytes.NewReader(data)) } // Encode writes the raw bytes of the public key to the provided writer. func (pub *PublicKey) Encode(w io.Writer) error { return encoding.WriteElements(w, pub.Bytes()) } // Decode reads the raw bytes of the public key from the provided reader and initializes the public key. func (pub *PublicKey) Decode(r io.Reader) error { data := make([]byte, PublicKeySize) err := encoding.ReadElements(r, data) if err != nil { return err } p, _ := PublicKeyFromBytes(data) *pub = *p return nil } func (*PublicKey) SerializeSize() int { return PublicKeySize } // Verify checks that a signature is valid for the given message and public key. // It's defined in section 2.6 of the spec: CoreVerify. func (pub *PublicKey) Verify(msg []byte, sig crypto.Signature) error { if sig == nil { return crypto.ErrInvalidPublicKey } if !ed25519.Verify(pub.inner, msg, sig.Bytes()) { return crypto.ErrInvalidSignature } return nil } // EqualsTo checks if the current public key is equal to another public key. func (pub *PublicKey) EqualsTo(x crypto.PublicKey) bool { xEd25519, ok := x.(*PublicKey) if !ok { return false } return pub.inner.Equal(xEd25519.inner) } // AccountAddress returns the account address derived from the public key. func (pub *PublicKey) AccountAddress() crypto.Address { data := hash.Hash160(hash.Hash256(pub.Bytes())) addr := crypto.NewAddress(crypto.AddressTypeEd25519Account, data) return addr } // VerifyAddress checks if the provided address matches the derived address from the public key. func (pub *PublicKey) VerifyAddress(addr crypto.Address) error { if addr != pub.AccountAddress() { return crypto.AddressMismatchError{ Expected: pub.AccountAddress(), Got: addr, } } return nil } ================================================ FILE: crypto/ed25519/public_key_test.go ================================================ package ed25519_test import ( "encoding/hex" "strings" "testing" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPublicKeyCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandEd25519KeyPair() pub2 := new(ed25519.PublicKey) bs, err := pub1.MarshalCBOR() require.NoError(t, err) require.NoError(t, pub2.UnmarshalCBOR(bs)) assert.True(t, pub1.EqualsTo(pub2)) require.Error(t, pub2.UnmarshalCBOR([]byte("abcd"))) inv, _ := hex.DecodeString(strings.Repeat("ff", ed25519.PublicKeySize)) data, _ := cbor.Marshal(inv) require.NoError(t, pub2.UnmarshalCBOR(data)) } func TestPublicKeyEqualsTo(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandEd25519KeyPair() pub2, _ := ts.RandEd25519KeyPair() pub3, _ := ts.RandBLSKeyPair() assert.True(t, pub1.EqualsTo(pub1)) assert.False(t, pub1.EqualsTo(pub2)) assert.False(t, pub1.EqualsTo(pub3)) } func TestPublicKeyEncoding(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandEd25519KeyPair() fw1 := util.NewFixedWriter(20) require.Error(t, pub.Encode(fw1)) fw2 := util.NewFixedWriter(ed25519.PublicKeySize) require.NoError(t, pub.Encode(fw2)) fr1 := util.NewFixedReader(20, fw2.Bytes()) require.Error(t, pub.Decode(fr1)) fr2 := util.NewFixedReader(ed25519.PublicKeySize, fw2.Bytes()) require.NoError(t, pub.Decode(fr2)) assert.Equal(t, ed25519.PublicKeySize, pub.SerializeSize()) } func TestPublicKeyVerifyAddress(t *testing.T) { ts := testsuite.NewTestSuite(t) pub1, _ := ts.RandEd25519KeyPair() pub2, _ := ts.RandEd25519KeyPair() err := pub1.VerifyAddress(pub1.AccountAddress()) require.NoError(t, err) err = pub1.VerifyAddress(pub2.AccountAddress()) assert.Equal(t, crypto.AddressMismatchError{ Expected: pub1.AccountAddress(), Got: pub2.AccountAddress(), }, err) } func TestNilPublicKey(t *testing.T) { ts := testsuite.NewTestSuite(t) pub := &ed25519.PublicKey{} randSig := ts.RandEd25519Signature() require.Error(t, pub.VerifyAddress(ts.RandAccAddress())) require.Error(t, pub.VerifyAddress(ts.RandValAddress())) require.Error(t, pub.Verify(nil, nil)) assert.Panics(t, func() { _ = pub.Verify(nil, randSig) }) } func TestNilSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, _ := ts.RandEd25519KeyPair() randSig := ts.RandEd25519Signature() require.Error(t, pub.Verify(nil, nil)) require.Error(t, pub.Verify(nil, randSig)) } func TestPublicKeyFromString(t *testing.T) { tests := []struct { errMsg string encoded string valid bool result []byte }{ { "invalid separator index -1", "not_proper_encoded", false, nil, }, { "invalid checksum (expected ztd56p got ztd5p6)", "public1rafnl324uwngqdq455ax4e52fedmfcvskkwas6wsau0u0nwj4g96qztd5p6", false, nil, }, { "invalid HRP: xxx", "xxx1rafnl324uwngqdq455ax4e52fedmfcvskkwas6wsau0u0nwj4g96qvguamu", false, nil, }, { "invalid length: 31", "public1ruwz86xyvhyehy8g7wg98jsmy07cfkjp6dy8zwxa8hqtdj99hquk7xyus", false, nil, }, { "invalid signature type: 4", "public1yafnl324uwngqdq455ax4e52fedmfcvskkwas6wsau0u0nwj4g96qdnx0mf", false, nil, }, { "", "public1rafnl324uwngqdq455ax4e52fedmfcvskkwas6wsau0u0nwj4g96qztd56p", true, []byte{ 0xea, 0x67, 0xf8, 0xaa, 0xbc, 0x74, 0xd0, 0x06, 0x82, 0xb4, 0xa7, 0x4d, 0x5c, 0xd1, 0x49, 0xcb, 0x76, 0x9c, 0x32, 0x16, 0xb3, 0xbb, 0x0d, 0x3a, 0x1d, 0xe3, 0xf8, 0xf9, 0xba, 0x55, 0x41, 0x74, }, }, } for no, tt := range tests { pub, err := ed25519.PublicKeyFromString(tt.encoded) if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.result, pub.Bytes(), "test %v: invalid bytes", no) assert.Equal(t, tt.encoded, pub.String(), "test %v: invalid encoded", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } ================================================ FILE: crypto/ed25519/signature.go ================================================ package ed25519 import ( "bytes" "crypto/subtle" "encoding/hex" "io" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util/encoding" ) var _ crypto.Signature = &Signature{} const SignatureSize = 64 type Signature struct { data []byte } // SignatureFromString decodes the input string and returns the Signature // if the string is a valid hexadecimal encoding of a Ed25519 signature. func SignatureFromString(text string) (*Signature, error) { data, err := hex.DecodeString(text) if err != nil { return nil, err } return SignatureFromBytes(data) } // SignatureFromBytes constructs a Ed25519 signature from the raw bytes. func SignatureFromBytes(data []byte) (*Signature, error) { if len(data) != SignatureSize { return nil, crypto.InvalidLengthError(len(data)) } return &Signature{data: data}, nil } // Bytes returns the raw byte representation of the signature. func (sig *Signature) Bytes() []byte { return sig.data[:SignatureSize] } // String returns the hex-encoded string representation of the signature. func (sig *Signature) String() string { return hex.EncodeToString(sig.Bytes()) } // MarshalCBOR encodes the signature into CBOR format. func (sig *Signature) MarshalCBOR() ([]byte, error) { return cbor.Marshal(sig.Bytes()) } // UnmarshalCBOR decodes the signature from CBOR format. func (sig *Signature) UnmarshalCBOR(bs []byte) error { var data []byte if err := cbor.Unmarshal(bs, &data); err != nil { return err } return sig.Decode(bytes.NewReader(data)) } // Encode writes the raw bytes of the signature to the provided writer. func (sig *Signature) Encode(w io.Writer) error { return encoding.WriteElements(w, sig.Bytes()) } // Decode reads the raw bytes of the signature from the provided reader and initializes the signature. func (sig *Signature) Decode(r io.Reader) error { data := make([]byte, SignatureSize) err := encoding.ReadElements(r, data) if err != nil { return err } s, _ := SignatureFromBytes(data) *sig = *s return nil } func (*Signature) SerializeSize() int { return SignatureSize } // EqualsTo checks if the current signature is equal to another signature. func (sig *Signature) EqualsTo(x crypto.Signature) bool { xEd25519, ok := x.(*Signature) if !ok { return false } return subtle.ConstantTimeCompare(sig.data, xEd25519.data) == 1 } ================================================ FILE: crypto/ed25519/signature_test.go ================================================ package ed25519_test import ( "encoding/hex" "strings" "testing" cbor "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSignatureCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv := ts.RandEd25519KeyPair() sig1 := prv.Sign(ts.RandBytes(16)) sig2 := new(ed25519.Signature) bs, err := sig1.MarshalCBOR() require.NoError(t, err) require.NoError(t, sig2.UnmarshalCBOR(bs)) assert.True(t, sig1.EqualsTo(sig2)) require.Error(t, sig2.UnmarshalCBOR([]byte("abcd"))) inv, _ := hex.DecodeString(strings.Repeat("ff", ed25519.SignatureSize)) data, _ := cbor.Marshal(inv) require.NoError(t, sig2.UnmarshalCBOR(data)) } func TestSignatureEqualsTo(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv1 := ts.RandEd25519KeyPair() _, prv2 := ts.RandEd25519KeyPair() _, prv3 := ts.RandBLSKeyPair() sig1 := prv1.Sign([]byte("foo")) sig2 := prv2.Sign([]byte("foo")) sig3 := prv3.Sign([]byte("foo")) assert.True(t, sig1.EqualsTo(sig1)) assert.False(t, sig1.EqualsTo(sig2)) assert.False(t, sig1.EqualsTo(sig3)) } func TestSignatureEncoding(t *testing.T) { ts := testsuite.NewTestSuite(t) _, prv := ts.RandEd25519KeyPair() sig := prv.Sign(ts.RandBytes(16)) fw1 := util.NewFixedWriter(20) require.Error(t, sig.Encode(fw1)) fw2 := util.NewFixedWriter(ed25519.SignatureSize) require.NoError(t, sig.Encode(fw2)) fr1 := util.NewFixedReader(20, fw2.Bytes()) require.Error(t, sig.Decode(fr1)) fr2 := util.NewFixedReader(ed25519.SignatureSize, fw2.Bytes()) require.NoError(t, sig.Decode(fr2)) assert.Equal(t, ed25519.SignatureSize, sig.SerializeSize()) } func TestVerifyingSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) msg := []byte("pactus") pb1, pv1 := ts.RandEd25519KeyPair() pb2, pv2 := ts.RandEd25519KeyPair() sig1 := pv1.Sign(msg) sig2 := pv2.Sign(msg) assert.False(t, sig1.EqualsTo(sig2)) require.NoError(t, pb1.Verify(msg, sig1)) require.NoError(t, pb2.Verify(msg, sig2)) require.ErrorIs(t, pb1.Verify(msg, sig2), crypto.ErrInvalidSignature) require.ErrorIs(t, pb2.Verify(msg, sig1), crypto.ErrInvalidSignature) require.ErrorIs(t, pb1.Verify(msg[1:], sig1), crypto.ErrInvalidSignature) } func TestSignatureFromString(t *testing.T) { tests := []struct { errMsg string encoded string valid bool bytes []byte }{ { "encoding/hex: invalid byte: U+006E 'n'", "not_proper_encoded", false, nil, }, { "invalid length: 0", "", false, nil, }, { "", "7d6af02f788422319781b03d7f4ed575b78c4c4dc8060ce145624fc8dc9ad92b" + "ae2d28c70242f03a644f313009ad9cc88b5dc37d501e43279c8fbc40b973af04", true, []byte{ 0x7d, 0x6a, 0xf0, 0x2f, 0x78, 0x84, 0x22, 0x31, 0x97, 0x81, 0xb0, 0x3d, 0x7f, 0x4e, 0xd5, 0x75, 0xb7, 0x8c, 0x4c, 0x4d, 0xc8, 0x06, 0x0c, 0xe1, 0x45, 0x62, 0x4f, 0xc8, 0xdc, 0x9a, 0xd9, 0x2b, 0xae, 0x2d, 0x28, 0xc7, 0x02, 0x42, 0xf0, 0x3a, 0x64, 0x4f, 0x31, 0x30, 0x09, 0xad, 0x9c, 0xc8, 0x8b, 0x5d, 0xc3, 0x7d, 0x50, 0x1e, 0x43, 0x27, 0x9c, 0x8f, 0xbc, 0x40, 0xb9, 0x73, 0xaf, 0x04, }, }, } for no, tt := range tests { sig, err := ed25519.SignatureFromString(tt.encoded) if tt.valid { require.NoError(t, err, "test %v: unexpected error", no) assert.Equal(t, tt.bytes, sig.Bytes(), "test %v: invalid bytes", no) assert.Equal(t, tt.encoded, sig.String(), "test %v: invalid encode", no) } else { assert.Contains(t, err.Error(), tt.errMsg, "test %v: error not matched", no) } } } ================================================ FILE: crypto/errors.go ================================================ package crypto import ( "errors" "fmt" ) // ErrInvalidSignature is returned when a signature is invalid. var ErrInvalidSignature = errors.New("invalid signature") // ErrInvalidPublicKey is returned when a public key is invalid. var ErrInvalidPublicKey = errors.New("invalid public key") // InvalidLengthError is returned when the length of the data // does not match the expected length. type InvalidLengthError int func (e InvalidLengthError) Error() string { return fmt.Sprintf("invalid length: %d", int(e)) } // InvalidHRPError is returned when the provided HRP code // does not match the expected value. type InvalidHRPError string func (e InvalidHRPError) Error() string { return fmt.Sprintf("invalid HRP: %s", string(e)) } // InvalidAddressTypeError is returned when the address type is not recognized or supported. type InvalidAddressTypeError int func (e InvalidAddressTypeError) Error() string { return fmt.Sprintf("invalid address type: %d", int(e)) } // InvalidSignatureTypeError is returned when the signature type is not recognized or supported. type InvalidSignatureTypeError int func (e InvalidSignatureTypeError) Error() string { return fmt.Sprintf("invalid signature type: %d", int(e)) } // AddressMismatchError is returned when the provided address is not derived // from the corresponding public key. type AddressMismatchError struct { Expected Address Got Address } func (e AddressMismatchError) Error() string { return fmt.Sprintf("address mismatch: expected %s, got %s", e.Expected.String(), e.Got.String()) } ================================================ FILE: crypto/hash/errors.go ================================================ package hash import ( "errors" ) // ErrInvalidSQLType is returned when the type of the data // is not supported for SQL database operations. var ErrInvalidSQLType = errors.New("invalid SQL type") ================================================ FILE: crypto/hash/hash.go ================================================ package hash import ( "encoding/hex" "fmt" "golang.org/x/crypto/blake2b" "golang.org/x/crypto/ripemd160" //nolint:all // used to hash the public key to generate the address. ) const HashSize = 32 type Hash [HashSize]byte var UndefHash = Hash{0} func Hash256(data []byte) []byte { h := blake2b.Sum256(data) return h[:] } func Hash160(data []byte) []byte { //nolint:all // used to hash the public key to generate the address. h := ripemd160.New() n, err := h.Write(data) if err != nil { return nil } if n != len(data) { return nil } return h.Sum(nil) } // FromString constructs a new hash from a hex-encoded string. func FromString(str string) (Hash, error) { data, err := hex.DecodeString(str) if err != nil { return Hash{}, err } if len(data) != HashSize { return Hash{}, fmt.Errorf("Hash should be %d bytes, but it is %v bytes", HashSize, len(data)) } return FromBytes(data) } // FromBytes constructs a new hash from raw byte data. func FromBytes(data []byte) (Hash, error) { if len(data) != HashSize { return Hash{}, fmt.Errorf("Hash should be %d bytes, but it is %v bytes", HashSize, len(data)) } var h Hash copy(h[:], data[:HashSize]) return h, nil } func CalcHash(data []byte) Hash { h, _ := FromBytes(Hash256(data)) return h } // Bytes returns the raw byte representation of the hash. func (h Hash) Bytes() []byte { return h[:] } // String returns the hex-encoded string representation of the hash. func (h Hash) String() string { return hex.EncodeToString(h[:]) } // ShortString returns a shortened string representation of the hash. func (h Hash) ShortString() string { return fmt.Sprintf("%x-%x", h[:3], h[29:]) } // LogString returns a concise string representation intended for use in logs. func (h Hash) LogString() string { return h.ShortString() } func (h Hash) IsUndef() bool { return h == UndefHash } ================================================ FILE: crypto/hash/hash_test.go ================================================ package hash_test import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHashFromString(t *testing.T) { ts := testsuite.NewTestSuite(t) hash1 := ts.RandHash() hash2, err := hash.FromString(hash1.String()) require.NoError(t, err) assert.Equal(t, hash1, hash2) _, err = hash.FromString("") require.Error(t, err) _, err = hash.FromString("inv") require.Error(t, err) _, err = hash.FromString("00") require.Error(t, err) } func TestHashEmpty(t *testing.T) { _, err := hash.FromBytes(nil) require.Error(t, err) _, err = hash.FromBytes([]byte{1}) require.Error(t, err) } func TestHash256(t *testing.T) { data := []byte("pactus") h1 := hash.Hash256(data) expected, _ := hex.DecodeString("ea020ace5c968f755dfc1b5921e574191cd9ff438639badae8a69f667e0d5970") assert.Equal(t, expected, h1) } func TestHash160(t *testing.T) { data := []byte("pactus") h := hash.Hash160(data) expected, _ := hex.DecodeString("1e4633f850c9590a97633631eae007e18648e30e") assert.Equal(t, expected, h) } func TestHashBasicCheck(t *testing.T) { h, err := hash.FromString("0000000000000000000000000000000000000000000000000000000000000000") require.NoError(t, err) assert.True(t, h.IsUndef()) assert.Equal(t, hash.UndefHash.Bytes(), h.Bytes()) } func TestShortString(t *testing.T) { h, err := hash.FromString("1234560000000000000000000000000000000000000000000000000000abcdef") require.NoError(t, err) assert.Equal(t, "123456-abcdef", h.ShortString()) assert.Equal(t, h.ShortString(), h.LogString()) } ================================================ FILE: crypto/private_key.go ================================================ package crypto type PrivateKey interface { Bytes() []byte String() string Sign(msg []byte) Signature PublicKey() PublicKey EqualsTo(right PrivateKey) bool } ================================================ FILE: crypto/public_key.go ================================================ package crypto import "io" type PublicKey interface { Bytes() []byte String() string MarshalCBOR() ([]byte, error) UnmarshalCBOR([]byte) error Encode(io.Writer) error Decode(io.Reader) error SerializeSize() int Verify(msg []byte, sig Signature) error VerifyAddress(addr Address) error EqualsTo(right PublicKey) bool } ================================================ FILE: crypto/signature.go ================================================ package crypto import "io" type Signature interface { Bytes() []byte String() string MarshalCBOR() ([]byte, error) UnmarshalCBOR([]byte) error Encode(io.Writer) error Decode(io.Reader) error SerializeSize() int EqualsTo(right Signature) bool } ================================================ FILE: docs/bootstrap.md ================================================ # Bootstrap Nodes As part of the network infrastructure, Bootstrap Nodes play an important role in starting and keeping the network secure. ## What are the Bootstrap Nodes? Bootstrap nodes act as the initial contact points for new nodes in the Pactus network. When a new node starts, it tries to connect to bootstrap nodes. Through these connections, it learns about the entire network and discovers other peers. ## Expectations Bootstrap node operators are essential contributors to the stability and growth of the Pactus blockchain. To ensure a seamless integration, operators are expected to adhere to the following guidelines: ### IP Address and DNS Stability Bootstrap node operators are expected to maintain the stability of their assigned IP or DNS address. It is imperative that these addresses remain unchanged and are not sold or transferred to third parties. ### Security Bootstrap node operators are expected to adhere to best practices in host security and maintain control over the relevant infrastructure. Specifically, they should ensure the security of their "network key". A network key is a private key used to encrypt messages in the P2P network. ### Reliability (Uptime) Bootstrap node operators are expected to maintain a high level of reliability and uptime. They should ensure that their nodes are consistently available with minimal downtime. ### Responsive Bootstrap node operators are expected to be highly responsive, particularly in times of emergencies. ### Software Updates Bootstrap node operators are expected to apply software updates and patches provided by the Pactus development team. ### Documentation Bootstrap node operators are encouraged, but not required, to publicly document the details of their operating practices. ### Monitoring Bootstrap node operators are encouraged, but not required, to implements monitoring tools to track the performance and health of their nodes. ## Inclusion in the Pactus Project Upon meeting the expectations outlined above, Bootstrap node operators can add their node as a Bootstrap node to the list of bootstrap addresses. Each Bootstrap address includes the IP or DNS address and the network ID. The network ID can be obtained from the network log. Once you have provided this information, you can open a pull request to add your node as a bootstrap node in the Pactus blockchain. An example of this pull request can be found [here](https://github.com/pactus-project/pactus/pull/965/files). ## Bootstrap Node Configuration It is recommended to adjust the Bootstrap node configuration as follows: ### Add Moniker A Moniker is a name by which a node can be recognized on the network. ### Increase the Maximum Number of Connections Depending on the server bandwidth, it is recommended to increase the maximum number of connections for the node. ### Enable NAT Service By enabling NAT service, you allow other nodes to examine their connection and determine whether they are behind NAT. ### Enable Relay Service Enabling relay service allows nodes behind NAT to establish connections with each other. ### Disable Relay Since a Bootstrap node has a public IP, it is important to disable the relay on the Bootstrap Node. ### Enable UDP If the Bootstrap node has a reliable UDP connection, you can enable UDP for communication. ================================================ FILE: docs/gtk-gui-development.md ================================================ # Pactus GUI This document is quick guide for developing and updating [the Pactus Core GUI](../cmd/gtk/). ## Requirements The Pactus Core GUI utilizes gtk for desktop GUI. To develop, build and test it you must have these packages installed: ### Linux 1. `libgtk-3-dev` 2. `libcairo2-dev` 3. `libglib2.0-dev` Install using apt: ```bash apt install libgtk-3-dev libcairo2-dev libglib2.0-dev ``` ### Mac OS 1. `gtk+3` Install using brew: ```bash brew install gtk+3 ``` ### Windows 1. `glib2-devel` 2. `mingw-w64-x86_64-go` 3. `mingw-w64-x86_64-gtk3` 4. `mingw-w64-x86_64-glib2` 5. `mingw-w64-x86_64-gcc` 6. `mingw-w64-x86_64-pkg-config` With these packages installed you can build GUI using `make build_gui` command. You can run the GUI like: `./pactus-gui`, `./pactus-gui.exe`. The [Assets](../cmd/gtk/assets/) file includes required images, icons, ui files and custom CSS files. All [`.ui`](../cmd/gtk/assets/ui/) files are used to defined the user interface of GUI, for a proper edit and change on them make sure you have [Glade](https://gitlab.gnome.org/GNOME/glade) installed on your machine. ## Running linter When you make changes on GUI files and try to run linter using `make check`, it won't include [gtk](../cmd/gtk/) in it's checks. So make sure you add gtk build flag like this: ```bash BUILD_TAG=gtk make check ``` ================================================ FILE: docs/install.md ================================================ # Installing Pactus ## Requirements You need to make sure you have installed [Git](https://git-scm.com/downloads) and [Go 1.21 or higher](https://golang.org/) on your machine. If you want to install a GUI application, make sure you have installed [GTK+3](https://www.gtk.org/docs/getting-started/) as well. ## Compiling the code Follow these steps to compile and build Pactus: ```bash git clone https://github.com/pactus-project/pactus.git cd pactus make build ``` This will compile `pactus-daemon`, `pactus-wallet` and `pactus-shell` on your machine. ```bash cd build ./pactus-daemon version ``` If you want to compile the GUI application, run this command in the root folder: ```bash make build_gui ``` To run the tests, use this command: ```bash make test ``` This may take several minutes to finish. ## What is `pactus-daemon`? `pactus-daemon` is a full node implementation of the Pactus blockchain. You can use `pactus-daemon` to run a full node: ```bash ./pactus-daemon init -w= ./pactus-daemon start -w= ``` ### Testnet To join the Testnet, first you need to initialize your node and then start the node: ```bash ./pactus-daemon init -w= --testnet ./pactus-daemon start -w= ``` ### Localnet You can create a local node to set up a local network for development purposes on your machine: ```bash ./pactus-daemon init -w= --localnet ./pactus-daemon start -w= ``` ## What is `pactus-wallet`? `pactus-wallet` is the CLI tool for creating and managing wallets on the Pactus blockchain. ### Getting started To create a new wallet, run this command. The wallet will be encrypted by the provided password. ```bash ./pactus-wallet --path ~/pactus/wallets/wallet_1 create ``` You can create a new address like this: ```bash ./pactus-wallet --path ~/pactus/wallets/wallet_1 address new ``` A list of addresses is available with this command: ```bash ./pactus-wallet --path ~/pactus/wallets/wallet_1 address all ``` To obtain the public key of an address, run this command: ```bash ./pactus-wallet --path ~/pactus/wallets/wallet_1 address pub
``` To send a transaction, use the `send` subcommand. For example, to send a bond transaction: ```bash ./pactus-wallet --path ~/pactus/wallets/wallet_1 send bond ``` You can recover a wallet if you have the seed phrase. ```bash ./pactus-wallet --path ~/pactus/wallets/wallet_2 recover ``` ## What is `pactus-shell`? `pactus-shell` is an interactive command-line client for exploring and calling the Pactus gRPC APIs. Start it against your node (default gRPC address is `localhost:50051`): ```bash ./pactus-shell interactive --server-addr localhost:50051 ``` ## Docker You can run Pactus using a Docker image. Please make sure you have installed [Docker](https://docs.docker.com/engine/install/) on your machine. Pull the image from Docker Hub: ```bash docker pull pactus/pactus:main ``` Let's create a working directory at `~/pactus/testnet` for the testnet: ```bash docker run -it --rm -v ~/pactus/testnet:/root/pactus pactus/pactus:main pactus-daemon init --testnet ``` Now we can run Pactus and join the testnet: ```bash docker run -it -v ~/pactus/testnet:/root/pactus -p 8080:8080 -p 21777:21777 --name pactus-testnet pactus/pactus:main pactus-daemon start ``` Check "[http://localhost:8080](http://localhost:8080)" for the list of APIs. You can stop or start the container: ```bash docker start pactus-testnet docker stop pactus-testnet ``` Or check the logs: ```bash docker logs pactus-testnet --tail 1000 -f ``` ## Profiling with pprof If you need runtime profiling, enable the HTML server with pprof in your node configuration and restart the node. Once running, you can collect and explore a CPU profile with the pprof web UI (replace the host and port with your HTML server address): ```bash go tool pprof -http :3000 "http://localhost:8081/debug/pprof/profile?debug=1" ``` ================================================ FILE: docs/metrics.md ================================================ # Metrics Pactus node offers [Prometheus](https://prometheus.io/) metrics to monitor and analyze various network-related and resource statistics. # Usage To activate this feature, inside the `config.toml`, set the `enable_metrics` parameter to true. Also, ensure that the HTTP module is enabled. You can enable HTTP module under the `[http]` section of the `config.toml` file. Once enabled, the metrics can be accessed at [http://localhost:80/metrics/prometheus](http://localhost:80/metrics/prometheus) (this url going to be use by prometheus). > NOTE: if you are running Pactus with docker image, make sure to expose `:80` port. After these changes, restart the Pactus node; you should now be able to view the metrics. ## Prometheus Configuration Prometheus is an open-source monitoring and alerting tool that facilitates the collection and processing of metrics. A common method of running Prometheus is via Docker containers. To use Prometheus with Docker, follow these steps: 1- Ensure [Docker](https://www.docker.com/) is installed on your system. 2- Pull the Prometheus Docker image: ```text docker pull prom/prometheus ``` 3- Create a configuration file named `prometheus.yml` to define the Prometheus configuration. You can refer to the Prometheus [documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/) for more guidance. As an example, here's a simple configuration: ```yaml scrape_configs: - job_name: "prometheus" scrape_interval: 1m static_configs: - targets: [ "127.0.0.1:9090" ] - job_name: "pactus-metrics" metrics_path: /metrics/prometheus static_configs: - targets: [ "localhost:80" ] ``` > NOTE: you should replace localhost with your server IP if you are running Pactus in server. 4- Start Prometheus as a Docker container: ```text docker run -p 9090:9090 -v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus ``` Replace `/path/to/prometheus.yml` with the actual path to your configuration file. 5- Prometheus should now be up and running. Access the Prometheus web interface by visiting [http://localhost:9090/](http://localhost:9090/) in your web browser. ================================================ FILE: docs/patching.md ================================================ # Patching Process To patch a released version, start by creating a dedicated branch for the patch version, proceed with the required updates, and eventually release the patched branch. Before proceeding with the patching process, ensure that your `origin` remote is set to `git@github.com:pactus-project/pactus.git` and not your local fork. ```bash git remote -vv ``` ## 1. Create a Patch Branch If this is the first patch for a specific major version, you'll need to create a branch for this tag. Replace `` with the appropriate minor version number: ```bash git checkout -b 1..x v1..0 git log git push --set-upstream origin 1..x ``` If you're not creating a new patch branch, switch to the existing patch branch: ```bash git checkout 1..x git pull ``` ## 2. Apply Fixes Now, apply the necessary fixes to the patch branch. You can use [cherry-pick](https://www.atlassian.com/git/tutorials/cherry-pick) to select specific commits from the main branch and apply them to the patch branch: ```bash git cherry-pick git push ``` Don't forget to update the patch version inside the [version.json](../version/version.json) file. ## 3. Set Environment Variables Reopen this document within the branch version and create environment variables for the release version, which will be used in subsequent commands throughout this document. Keep your terminal open for further steps. ```bash PRV_VER="1.14.0" CUR_VER="1.14.1" NEXT_VER="1.14.2" BASE_BRANCH="1.14.x" TAG_NAME="v${CUR_VER}" TAG_MSG="Version ${CUR_VER}" ``` ## 4. Follow the Releasing Document Refer to the [Releasing](./releasing.md#5-update-changelog) document and follow the steps outlined from Step 5 until the end. This document will provide you with the necessary guidance to successfully release the patched branch. Ensure that your terminal remains open throughout the process for seamless execution of the required commands. ================================================ FILE: docs/release-candidate.md ================================================ # Release Candidate Release candidates are used to test the latest version before a final release. They are **not intended to be stored permanently** and will be removed from GitHub Releases after testing. To create a release candidate, follow the structure below: ## 1. Set Environment Variables Create environment variables for the release version, which will be used in subsequent commands throughout this document. Keep your terminal open for further steps. Update `X`, `Y`, `Z`, and `N` to reflect the release candidate (e.g., `1.7.0-rc1`, `1.7.0-rc2`, etc.). ```bash CUR_VER="X.Y.Z-rcN" TAG_NAME="v${CUR_VER}" TAG_MSG="Version ${CUR_VER}" ``` ## 2. Update the Version Set `rcX` in the `Meta` field and update the `Alias` in [version.go](../version/version.json). ## 3. Make a Release Candidate Commit Create a new commit for the release candidate: ```bash git commit -a -m "chore(release): releasing version ${CUR_VER}" ``` ## 4. Tag the Release Create a signed Git tag: ```bash git tag -s -a ${TAG_NAME} -m "${TAG_MSG}" ``` Verify the tag: ```bash git show ${TAG_NAME} ``` ## 5. Push the Tag Push the tag to the remote repository: ```bash git push origin ${TAG_NAME} ``` Pushing the tag will automatically trigger the creation of a release candidate and build the binaries. ================================================ FILE: docs/releasing.md ================================================ # Release Process To ensure a successful release and publication of the Pactus software, it is essential to follow these key steps. Please carefully follow the instructions provided below: ## 1. Preparing Your Environment Before proceeding with the release process, ensure that your `origin` remote is set to `git@github.com:pactus-project/pactus.git` and not your local fork. ```bash git remote -vv ``` It is recommended to re-clone the project in a location other than your current working directory. Also, make sure that you have set up GPG for your GitHub account. ## 2. Fetch the Latest Code Ensure that your local repository is up-to-date with the Pactus main repository: ```bash git checkout main git pull ``` ## 3. Set Environment Variables Create environment variables for the release version, which will be used in subsequent commands throughout this document. Keep your terminal open for further steps. ```bash PRV_VER="1.13.0" CUR_VER="1.14.0" NEXT_VER="1.15.0" BASE_BRANCH="main" TAG_NAME="v${CUR_VER}" TAG_MSG="Version ${CUR_VER}" ``` ## 4. Update the Version Clear Meta and set Alias in [version.json](../version/version.json). ## 5. Update Changelog Use [Commitizen](https://github.com/commitizen-tools/commitizen) to update the CHANGELOG. Execute the following command: ```bash cz changelog --incremental --unreleased-version ${TAG_NAME} perl -i -pe "s/## v${CUR_VER} /## [${CUR_VER}](https:\/\/github.com\/pactus-project\/pactus\/compare\/v${PRV_VER}...v${CUR_VER}) /g" CHANGELOG.md perl -i -pe "s/\(#([0-9]+)\)/([#\1](https:\/\/github.com\/pactus-project\/pactus\/pull\/\1))/g" CHANGELOG.md ``` Occasionally, you may need to make manual updates to the [CHANGELOG](../CHANGELOG.md). ## 6. Create a Release PR Generate a new PR against the base branch. It's better to use [GitHub CLI](https://github.com/cli/cli/) to create the PR, but manual creation is also an option. ```bash git checkout -b releasing_${CUR_VER} git commit -a -m "chore(release): releasing version ${CUR_VER}" git push origin HEAD gh pr create --title "chore(release): releasing version ${CUR_VER}" --body "Releasing version ${CUR_VER}" --base ${BASE_BRANCH} ``` Wait for the PR to be approved and merged into the main branch. ## 7. Tagging the Release Create a Git tag and sign it using your [GPG key](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification) with the following commands: ```bash git checkout ${BASE_BRANCH} git pull git tag -s -a ${TAG_NAME} -m "${TAG_MSG}" ``` Inspect the tag information: ```bash git show ${TAG_NAME} ``` ## 8. Push the Tag Now, push the tag to the repository: ```bash git push origin ${TAG_NAME} ``` Pushing the tag will automatically create a release tag and build the binaries. ## 9. Bump the Version Update the version inside [version.json](../version/version.json), add `beta` to the `meta` field, and: - If this is a **major release**, * update the versions inside [this document](./releasing.md#3-set-environment-variables) in step 3 and * update the versions inside the [patching](./patching.md#3-set-environment-variables) in step 3. - If this is a **patch release**, * update the versions inside the [patching](./patching.md#3-set-environment-variables) in step 3. Create a new PR against the base branch: ```bash git checkout -b bumping_${NEXT_VER} git commit -a -m "chore(version): bumping version to ${NEXT_VER}" git push origin HEAD gh pr create --title "chore(version): bumping version to ${NEXT_VER}" --body "Bumping version to ${NEXT_VER}" --base ${BASE_BRANCH} ``` Wait for the PR to be approved and merged into the main branch. ## 10. Update the Website Create a new announcement post on the [blog](https://pactus.org/blog/) and update the [Road Map](https://pactus.org/about/roadmap/) and [Download](https://pactus.org/download/) pages. Additionally, update the new release on the [GitHub Releases](https://github.com/pactus-project/pactus/releases) page. If gRPC APIs has changed in this version, be sure to update the [API documentation](https://docs.pactus.org/api/) and [Python SDK](https://github.com/pactus-project/python-sdk) accordingly. ## 11. Celebrate 🎉 Before celebrating, ensure that the release has been tested and that all documentation is up to date. Don't forget to update dependencies after major releases (see [Update Dependencies](./update-dependencies.md)). ================================================ FILE: docs/update-dependencies.md ================================================ # Update Dependencies This document outlines the steps to update dependencies in the Pactus project repository to their latest versions. ## Update Go First, update the Go version to the [latest release](https://go.dev/doc/install) in [go.mod](../go.mod). Ensure the Golang version is also updated in the [Dockerfile](../Dockerfile). ## Update Dependencies To update Go dependencies to their latest versions, use the following commands: ```sh go get -u ./... go mod tidy ``` Once all packages are updated, run `make build`, `make test`, and `make build_gui` to ensure no existing functionality is broken. If any packages introduce breaking changes or are deprecated, update the code to use the new methods or replace the package entirely. ## Update Dev Tools Next, update development tools such as `golangci-lint`, `buf`, and others. Refer to the [Makefile](../Makefile) and locate the `devtools` target. Replace each tool with its latest version. ## Update GitHub Workflows Navigate to the [workflows](../.github/workflows) directory and update outdated GitHub actions to their latest versions. You can find the latest versions by searching for the action name on GitHub. ## Buf Dependencies We use [buf](https://buf.build/explore) to generate code from proto files. Update the buf plugins in [buf.gen.yaml](../www/grpc/buf/buf.gen.yaml) to their latest versions. ### Packager Dependencies When updating Buf plugins, ensure that the **Runtime dependencies** align with the dependencies defined in the packages within the [packager](../.github/packager/) folder. ## Example Pull Request For reference, see this example pull request for updates and commit format: https://github.com/pactus-project/pactus/pull/1202 ================================================ FILE: execution/errors.go ================================================ package execution import ( "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/tx" ) // TransactionCommittedError is returned when an attempt is made // to replay a transaction that has already been committed. // This is to prevent replay attacks where an attacker tries to // submit the same transaction more than once. type TransactionCommittedError struct { ID tx.ID } func (e TransactionCommittedError) Error() string { return fmt.Sprintf("the transaction submitted before: %s", e.ID.String()) } // LockTimeExpiredError is returned when the lock time of a transaction // is in the past and has expired, // indicating the transaction can no longer be executed. type LockTimeExpiredError struct { LockTime types.Height } func (e LockTimeExpiredError) Error() string { return fmt.Sprintf("lock time expired: %v", e.LockTime) } // LockTimeInFutureError is returned when the lock time of a transaction // is in the future, // indicating the transaction is not yet eligible for processing. type LockTimeInFutureError struct { LockTime types.Height } func (e LockTimeInFutureError) Error() string { return fmt.Sprintf("lock time is in the future: %v", e.LockTime) } // SignerBannedError is returned when the signer of transaction is banned and its assets is freezed. type SignerBannedError struct { Address crypto.Address } func (e SignerBannedError) Error() string { return fmt.Sprintf("the signer is banned: %s", e.Address.String()) } ================================================ FILE: execution/execution.go ================================================ package execution import ( "github.com/pactus-project/pactus/execution/executor" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/tx" ) func Execute(trx *tx.Tx, sbx sandbox.Sandbox) error { exe, err := executor.MakeExecutor(trx, sbx) if err != nil { return err } exe.Execute() sbx.CommitTransaction(trx) return nil } func CheckAndExecute(trx *tx.Tx, sbx sandbox.Sandbox, strict bool) error { exe, err := executor.MakeExecutor(trx, sbx) if err != nil { return err } if sbx.IsBanned(trx.Payload().Signer()) { return SignerBannedError{ Address: trx.Payload().Signer(), } } if exists := sbx.RecentTransaction(trx.ID()); exists { return TransactionCommittedError{ ID: trx.ID(), } } if err := CheckLockTime(trx, sbx, strict); err != nil { return err } if err := exe.Check(strict); err != nil { return err } exe.Execute() sbx.CommitTransaction(trx) return nil } func CheckLockTime(trx *tx.Tx, sbx sandbox.Sandbox, strict bool) error { interval := sbx.Params().TransactionToLiveInterval if trx.IsSubsidyTx() { interval = 0 } else if trx.IsSortitionTx() { interval = sbx.Params().SortitionInterval } if sbx.CurrentHeight() > types.Height(interval) { if trx.LockTime() < sbx.CurrentHeight().SafeDecrease(interval) { return LockTimeExpiredError{ LockTime: trx.LockTime(), } } } if strict { // In strict mode, transactions with future lock times are rejected. // In non-strict mode, they are added to the transaction pool and // processed once eligible. if trx.LockTime() > sbx.CurrentHeight() { return LockTimeInFutureError{ LockTime: trx.LockTime(), } } } return nil } ================================================ FILE: execution/execution_test.go ================================================ package execution import ( "testing" "github.com/pactus-project/pactus/execution/executor" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTransferLockTime(t *testing.T) { ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) sbx.TestStore.AddTestBlock(8642) tests := []struct { name string lockTime types.Height strictErr error nonStrictErr error }{ { name: "Transaction has expired LockTime (-8641)", lockTime: sbx.CurrentHeight().SafeDecrease(sbx.TestParams.TransactionToLiveInterval) - 1, strictErr: LockTimeExpiredError{sbx.CurrentHeight().SafeDecrease(sbx.TestParams.TransactionToLiveInterval) - 1}, nonStrictErr: LockTimeExpiredError{sbx.CurrentHeight().SafeDecrease(sbx.TestParams.TransactionToLiveInterval) - 1}, }, { name: "Transaction has valid LockTime (-8640)", lockTime: sbx.CurrentHeight().SafeDecrease(sbx.TestParams.TransactionToLiveInterval), strictErr: nil, nonStrictErr: nil, }, { name: "Transaction has valid LockTime (-88)", lockTime: sbx.CurrentHeight() - 88, strictErr: nil, nonStrictErr: nil, }, { name: "Transaction has valid LockTime (0)", lockTime: sbx.CurrentHeight(), strictErr: nil, nonStrictErr: nil, }, { name: "Transaction has future LockTime (+1)", lockTime: sbx.CurrentHeight() + 1, strictErr: LockTimeInFutureError{sbx.CurrentHeight() + 1}, nonStrictErr: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(tt.lockTime)) strictErr := CheckLockTime(trx, sbx, true) require.ErrorIs(t, strictErr, tt.strictErr) nonStrictErr := CheckLockTime(trx, sbx, false) require.ErrorIs(t, nonStrictErr, tt.nonStrictErr) }) } } func TestSortitionLockTime(t *testing.T) { ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) sbx.TestAcceptSortition = true sbx.TestStore.AddTestBlock(8642) tests := []struct { name string lockTime types.Height strictErr error nonStrictErr error }{ { name: "Sortition transaction has expired LockTime (-8)", lockTime: sbx.CurrentHeight().SafeDecrease(sbx.TestParams.SortitionInterval) - 1, strictErr: LockTimeExpiredError{sbx.CurrentHeight().SafeDecrease(sbx.TestParams.SortitionInterval) - 1}, nonStrictErr: LockTimeExpiredError{sbx.CurrentHeight().SafeDecrease(sbx.TestParams.SortitionInterval) - 1}, }, { name: "Sortition transaction has valid LockTime (-7)", lockTime: sbx.CurrentHeight().SafeDecrease(sbx.TestParams.SortitionInterval), strictErr: nil, nonStrictErr: nil, }, { name: "Sortition transaction has valid LockTime (-1)", lockTime: sbx.CurrentHeight() - 1, strictErr: nil, nonStrictErr: nil, }, { name: "Sortition transaction has valid LockTime (0)", lockTime: sbx.CurrentHeight(), strictErr: nil, nonStrictErr: nil, }, { name: "Sortition transaction has future LockTime (+1)", lockTime: sbx.CurrentHeight() + 1, strictErr: LockTimeInFutureError{sbx.CurrentHeight() + 1}, nonStrictErr: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { trx := ts.GenerateTestSortitionTx( testsuite.TransactionWithLockTime(tt.lockTime)) strictErr := CheckLockTime(trx, sbx, true) require.ErrorIs(t, strictErr, tt.strictErr) nonStrictErr := CheckLockTime(trx, sbx, false) require.ErrorIs(t, nonStrictErr, tt.nonStrictErr) }) } } func TestSubsidyLockTime(t *testing.T) { ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) sbx.TestStore.AddTestBlock(8642) tests := []struct { name string lockTime types.Height strictErr error nonStrictErr error }{ { name: "Subsidy transaction has expired LockTime (-1)", lockTime: sbx.CurrentHeight() - 1, strictErr: LockTimeExpiredError{sbx.CurrentHeight() - 1}, nonStrictErr: LockTimeExpiredError{sbx.CurrentHeight() - 1}, }, { name: "Subsidy transaction has valid LockTime (0)", lockTime: sbx.CurrentHeight(), strictErr: nil, nonStrictErr: nil, }, { name: "Subsidy transaction has future LockTime (+1)", lockTime: sbx.CurrentHeight() + 1, strictErr: LockTimeInFutureError{sbx.CurrentHeight() + 1}, nonStrictErr: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { trx := ts.GenerateTestSubsidyTx( testsuite.TransactionWithLockTime(tt.lockTime)) strictErr := CheckLockTime(trx, sbx, true) require.ErrorIs(t, strictErr, tt.strictErr) nonStrictErr := CheckLockTime(trx, sbx, false) require.ErrorIs(t, nonStrictErr, tt.nonStrictErr) }) } } func TestExecute(t *testing.T) { ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) sbx.TestStore.AddTestBlock(8642) knownPub, knownSigner := ts.RandEd25519KeyPair() sbx.TestStore.AddTestAccount(testsuite.AccountWithAddress(knownPub.AccountAddress())) lockTime := sbx.CurrentHeight() t.Run("Unknown Signer", func(t *testing.T) { _, unknownSigner := ts.RandKeyPair() trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(unknownSigner)) err := Execute(trx, sbx) require.ErrorIs(t, err, executor.AccountNotFoundError{Address: trx.Payload().Signer()}) }) t.Run("Valid Transaction", func(t *testing.T) { trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(knownSigner)) err := Execute(trx, sbx) require.NoError(t, err) assert.True(t, sbx.RecentTransaction(trx.ID())) }) } func TestCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) sbx.TestStore.AddTestBlock(8642) knownPub, knownSigner := ts.RandEd25519KeyPair() _, testAcc := sbx.TestStore.AddTestAccount(testsuite.AccountWithAddress(knownPub.AccountAddress())) lockTime := sbx.CurrentHeight() t.Run("Unknown Sender", func(t *testing.T) { _, unknownSigner := ts.RandKeyPair() trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(unknownSigner)) err := CheckAndExecute(trx, sbx, true) require.ErrorIs(t, err, executor.AccountNotFoundError{Address: trx.Payload().Signer()}) }) t.Run("Invalid lock-time, Should return error", func(t *testing.T) { invalidLockTime := lockTime + 1 trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(invalidLockTime), testsuite.TransactionWithSigner(knownSigner)) err := CheckAndExecute(trx, sbx, true) require.ErrorIs(t, err, LockTimeInFutureError{LockTime: invalidLockTime}) }) t.Run("Invalid transaction, Should return error", func(t *testing.T) { trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(knownSigner), testsuite.TransactionWithAmount(testAcc.Balance()+1)) err := CheckAndExecute(trx, sbx, true) require.ErrorIs(t, err, executor.ErrInsufficientFunds) }) t.Run("Ok", func(t *testing.T) { trx := ts.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(knownSigner)) err := CheckAndExecute(trx, sbx, true) require.NoError(t, err) assert.True(t, sbx.RecentTransaction(trx.ID())) }) } func TestReplay(t *testing.T) { ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) sbx.TestStore.AddTestBlock(8642) knownPub, knownSigner := ts.RandEd25519KeyPair() sbx.TestStore.AddTestAccount( testsuite.AccountWithAddress(knownPub.AccountAddress())) trx := ts.GenerateTestTransferTx( testsuite.TransactionWithSigner(knownSigner)) err := Execute(trx, sbx) require.NoError(t, err) err = CheckAndExecute(trx, sbx, false) require.ErrorIs(t, err, TransactionCommittedError{ ID: trx.ID(), }) } ================================================ FILE: execution/executor/batch_transfer.go ================================================ package executor import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" ) type batchRecipient struct { Address crypto.Address Account *account.Account Amount amount.Amount } type BatchTransferExecutor struct { sbx sandbox.Sandbox pld *payload.BatchTransferPayload fee amount.Amount sender *account.Account recipients []batchRecipient } func newBatchTransferExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*BatchTransferExecutor, error) { pld := trx.Payload().(*payload.BatchTransferPayload) sender := sbx.Account(pld.From) if sender == nil { return nil, AccountNotFoundError{Address: pld.From} } recipients := make([]batchRecipient, len(pld.Recipients)) for i, r := range pld.Recipients { if r.To == pld.From { recipients[i].Account = sender } else { receiver := sbx.Account(r.To) if receiver == nil { receiver = sbx.MakeNewAccount(r.To) } recipients[i].Account = receiver } recipients[i].Address = r.To recipients[i].Amount = r.Amount } return &BatchTransferExecutor{ sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, recipients: recipients, }, nil } func (e *BatchTransferExecutor) Check(_ bool) error { if e.sender.Balance() < e.pld.Value()+e.fee { return ErrInsufficientFunds } return nil } func (e *BatchTransferExecutor) Execute() { e.sender.SubtractFromBalance(e.pld.Value() + e.fee) e.sbx.UpdateAccount(e.pld.From, e.sender) for _, r := range e.recipients { r.Account.AddToBalance(r.Amount) e.sbx.UpdateAccount(r.Address, r.Account) } } ================================================ FILE: execution/executor/batch_transfer_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/stretchr/testify/assert" ) func TestExecuteBatchTransferTx(t *testing.T) { td := setup(t) senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() senderBalance := senderAcc.Balance() receiverAddr1 := td.RandAccAddress() receiverAddr2 := td.RandAccAddress() amt := td.RandAmountRange(0, senderBalance) amt1 := td.RandAmount(amt / 2) amt2 := td.RandAmount(amt / 2) fee := td.RandFee() lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() recipients := []payload.BatchRecipient{ {To: receiverAddr1, Amount: amt1}, {To: receiverAddr2, Amount: amt2}, } trx := tx.NewBatchTransferTx(lockTime, randomAddr, recipients, fee) td.check(t, trx, true, AccountNotFoundError{Address: randomAddr}) td.check(t, trx, false, AccountNotFoundError{Address: randomAddr}) }) t.Run("Should fail, insufficient balance", func(t *testing.T) { recipients := []payload.BatchRecipient{ {To: receiverAddr1, Amount: senderBalance + 1}, {To: receiverAddr2, Amount: senderBalance + 1}, } trx := tx.NewBatchTransferTx(lockTime, senderAddr, recipients, 0) td.check(t, trx, true, ErrInsufficientFunds) td.check(t, trx, false, ErrInsufficientFunds) }) t.Run("Ok", func(t *testing.T) { recipients := []payload.BatchRecipient{ {To: receiverAddr1, Amount: amt1}, {To: receiverAddr2, Amount: amt2}, } trx := tx.NewBatchTransferTx(lockTime, senderAddr, recipients, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedSenderAcc := td.sbx.Account(senderAddr) updatedReceiverAcc1 := td.sbx.Account(receiverAddr1) updatedReceiverAcc2 := td.sbx.Account(receiverAddr2) assert.Equal(t, senderBalance-(amt1+amt2+fee), updatedSenderAcc.Balance()) assert.Equal(t, amt1, updatedReceiverAcc1.Balance()) assert.Equal(t, amt2, updatedReceiverAcc2.Balance()) td.checkTotalCoin(t, fee) } func TestBatchTransferToSelf(t *testing.T) { td := setup(t) senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() amt := td.RandAmountRange(0, senderAcc.Balance()) amt1 := td.RandAmount(amt / 2) amt2 := td.RandAmount(amt / 2) fee := td.RandFee() lockTime := td.sbx.CurrentHeight() recipients := []payload.BatchRecipient{ {To: td.RandAccAddress(), Amount: amt1}, {To: senderAddr, Amount: amt2}, } trx := tx.NewBatchTransferTx(lockTime, senderAddr, recipients, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) expectedBalance := senderAcc.Balance() - amt1 - fee // Fee should be deducted updatedAcc := td.sbx.Account(senderAddr) assert.Equal(t, expectedBalance, updatedAcc.Balance()) td.checkTotalCoin(t, fee) } ================================================ FILE: execution/executor/bond.go ================================================ package executor import ( "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" ) type BondExecutor struct { sbx sandbox.Sandbox pld *payload.BondPayload fee amount.Amount sender *account.Account receiver *validator.Validator } func newBondExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*BondExecutor, error) { pld := trx.Payload().(*payload.BondPayload) sender := sbx.Account(pld.From) if sender == nil { return nil, AccountNotFoundError{Address: pld.From} } receiver := sbx.Validator(pld.To) if receiver == nil { if pld.PublicKey == nil { return nil, ErrPublicKeyNotSet } receiver = sbx.MakeNewValidator(pld.PublicKey) } else if pld.PublicKey != nil { return nil, ErrPublicKeyAlreadySet } return &BondExecutor{ sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, receiver: receiver, }, nil } func (e *BondExecutor) Check(strict bool) error { if e.receiver.IsUnbonded() { return ErrValidatorUnbonded } if e.pld.IsDelegated() { if e.pld.Stake != e.sbx.Params().MaximumStake { return ErrInvalidDelegation } if e.pld.DelegateExpiry <= e.sbx.CurrentHeight() { return ErrDelegateExpiryInPast } } if e.sender.Balance() < e.pld.Value()+e.fee { return ErrInsufficientFunds } if e.pld.Stake < e.sbx.Params().MinimumStake { // This check prevents a potential attack where an attacker could send zero // or a small amount of stake to a full validator, effectively parking the // validator for the bonding period. if e.pld.Stake == 0 || e.pld.Stake+e.receiver.Stake() != e.sbx.Params().MaximumStake { return SmallStakeError{ Minimum: e.sbx.Params().MinimumStake, } } } if e.receiver.Stake()+e.pld.Stake > e.sbx.Params().MaximumStake { return MaximumStakeError{ Maximum: e.sbx.Params().MaximumStake, } } if strict { // In strict mode, bond transactions will be rejected if a validator is // already in the committee. // In non-strict mode, they are added to the transaction pool and // processed once eligible. if e.sbx.Committee().Contains(e.pld.To) { return ErrValidatorInCommittee } // In strict mode, bond transactions will be rejected if a validator is // going to join the committee in the next height. // In non-strict mode, they are added to the transaction pool and // processed once eligible. if e.sbx.IsJoinedCommittee(e.pld.To) { return ErrValidatorInCommittee } } return nil } func (e *BondExecutor) Execute() { e.sender.SubtractFromBalance(e.pld.Stake + e.fee) e.receiver.AddToStake(e.pld.Stake) e.receiver.UpdateLastBondingHeight(e.sbx.CurrentHeight()) if e.pld.IsDelegated() { e.receiver.SetDelegation(e.pld.DelegateOwner, e.pld.DelegateShare, e.pld.DelegateExpiry) } e.sbx.UpdatePowerDelta(int64(e.pld.Stake)) e.sbx.UpdateAccount(e.pld.From, e.sender) e.sbx.UpdateValidator(e.receiver) } ================================================ FILE: execution/executor/bond_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/stretchr/testify/assert" ) func TestExecuteBondTx(t *testing.T) { td := setup(t) senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() senderBalance := senderAcc.Balance() valPub, _ := td.RandBLSKeyPair() receiverAddr := valPub.ValidatorAddress() amt := td.RandAmountRange( td.sbx.TestParams.MinimumStake, td.sbx.TestParams.MaximumStake) fee := td.RandFee() lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() trx := tx.NewBondTx(lockTime, randomAddr, receiverAddr, valPub, amt, fee) td.check(t, trx, true, AccountNotFoundError{Address: randomAddr}) td.check(t, trx, false, AccountNotFoundError{Address: randomAddr}) }) t.Run("Should fail, public key is not set", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, amt, fee) td.check(t, trx, true, ErrPublicKeyNotSet) td.check(t, trx, false, ErrPublicKeyNotSet) }) t.Run("Should fail, public key should not set for existing validators", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(randPub) td.sbx.UpdateValidator(val) trx := tx.NewBondTx(lockTime, senderAddr, randPub.ValidatorAddress(), randPub, amt, fee) td.check(t, trx, true, ErrPublicKeyAlreadySet) td.check(t, trx, false, ErrPublicKeyAlreadySet) }) t.Run("Should fail, insufficient balance", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, senderBalance+1, 0) td.check(t, trx, true, ErrInsufficientFunds) td.check(t, trx, false, ErrInsufficientFunds) }) t.Run("Should fail, unbonded before", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(randPub) val.UpdateUnbondingHeight(td.RandHeight()) td.sbx.UpdateValidator(val) trx := tx.NewBondTx(lockTime, senderAddr, randPub.ValidatorAddress(), nil, amt, fee) td.check(t, trx, true, ErrValidatorUnbonded) td.check(t, trx, false, ErrValidatorUnbonded) }) t.Run("Should fail, amount less than MinimumStake", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, td.sbx.TestParams.MinimumStake-1, fee) td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) t.Run("Should fail, validator's stake exceeds the MaximumStake", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, td.sbx.TestParams.MaximumStake+1, fee) td.check(t, trx, true, MaximumStakeError{td.sbx.TestParams.MaximumStake}) td.check(t, trx, false, MaximumStakeError{td.sbx.TestParams.MaximumStake}) }) t.Run("Should fail, inside committee", func(t *testing.T) { pub0 := td.sbx.Committee().Proposer(0).PublicKey() trx := tx.NewBondTx(lockTime, senderAddr, pub0.ValidatorAddress(), nil, 1e9, fee) td.check(t, trx, true, ErrValidatorInCommittee) td.check(t, trx, false, nil) }) t.Run("Should fail, joining committee", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(randPub) td.sbx.UpdateValidator(val) td.sbx.JoinedToCommittee(val.Address()) trx := tx.NewBondTx(lockTime, senderAddr, randPub.ValidatorAddress(), nil, amt, fee) td.check(t, trx, true, ErrValidatorInCommittee) td.check(t, trx, false, nil) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, amt, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedSenderAcc := td.sbx.Account(senderAddr) updatedReceiverVal := td.sbx.Validator(receiverAddr) assert.Equal(t, senderBalance-(amt+fee), updatedSenderAcc.Balance()) assert.Equal(t, amt, updatedReceiverVal.Stake()) assert.Equal(t, lockTime, updatedReceiverVal.LastBondingHeight()) td.checkTotalCoin(t, fee) } func TestPowerDeltaBond(t *testing.T) { td := setup(t) senderAddr, _ := td.sbx.TestStore.RandomTestAcc() pub, _ := td.RandBLSKeyPair() receiverAddr := pub.ValidatorAddress() amt := td.RandAmountRange( td.sbx.TestParams.MinimumStake, td.sbx.TestParams.MaximumStake) fee := td.RandFee() lockTime := td.sbx.CurrentHeight() trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, pub, amt, fee) td.execute(t, trx) assert.Equal(t, int64(amt), td.sbx.PowerDelta()) } // TestSmallBond tests scenarios involving small and zero stake amounts in bond transactions. // This test suite is designed to address the issue reported on GitHub: // https://github.com/pactus-project/pactus/issues/1223 func TestSmallBond(t *testing.T) { td := setup(t) senderAddr, _ := td.sbx.TestStore.RandomTestAcc() receiverPub, _ := td.RandBLSKeyPair() receiverAddr := receiverPub.ValidatorAddress() receiverVal := td.sbx.MakeNewValidator(receiverPub) receiverVal.AddToStake(td.sbx.TestParams.MaximumStake - 2) td.sbx.UpdateValidator(receiverVal) lockTime := td.sbx.CurrentHeight() fee := td.RandFee() t.Run("Rejects bond transaction with zero amount", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 0, fee) td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) t.Run("Rejects bond transaction below full validator stake", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 1, fee) td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) t.Run("Accepts bond transaction reaching full validator stake", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 2, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) t.Run("Rejects bond transaction with zero amount on full validator", func(t *testing.T) { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, nil, 0, fee) td.check(t, trx, true, SmallStakeError{td.sbx.TestParams.MinimumStake}) td.check(t, trx, false, SmallStakeError{td.sbx.TestParams.MinimumStake}) }) receiverValAfterExecution, _ := td.sbx.TestStore.Validator(receiverVal.Address()) assert.Equal(t, td.sbx.Params().MaximumStake, receiverValAfterExecution.Stake()) } func TestExecuteDelegatedBondTx(t *testing.T) { td := setup(t) senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() senderBalance := senderAcc.Balance() valPub, _ := td.RandBLSKeyPair() receiverAddr := valPub.ValidatorAddress() lockTime := td.sbx.CurrentHeight() fee := td.RandFee() owner := td.RandAccAddress() delegateShare := td.RandAmountRange(0, param.MaxDelegateOwnerRewardShare) delegateExpiry := td.sbx.CurrentHeight() + 1 makeDelegatedBond := func(stake amount.Amount) *tx.Tx { trx := tx.NewBondTx(lockTime, senderAddr, receiverAddr, valPub, stake, fee) pld := trx.Payload().(*payload.BondPayload) pld.DelegateOwner = owner pld.DelegateShare = delegateShare pld.DelegateExpiry = delegateExpiry return trx } t.Run("Should fail, delegation stake must equal maximum", func(t *testing.T) { trx := makeDelegatedBond(td.sbx.TestParams.MaximumStake - 1) td.check(t, trx, true, ErrInvalidDelegation) td.check(t, trx, false, ErrInvalidDelegation) }) t.Run("Should fail, delegate expiry is in past/current height", func(t *testing.T) { trx := makeDelegatedBond(td.sbx.TestParams.MaximumStake) pld := trx.Payload().(*payload.BondPayload) pld.DelegateExpiry = td.sbx.CurrentHeight() td.check(t, trx, true, ErrDelegateExpiryInPast) td.check(t, trx, false, ErrDelegateExpiryInPast) }) t.Run("Ok", func(t *testing.T) { trx := makeDelegatedBond(td.sbx.TestParams.MaximumStake) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedSenderAcc := td.sbx.Account(senderAddr) updatedReceiverVal := td.sbx.Validator(receiverAddr) assert.Equal(t, senderBalance-(td.sbx.TestParams.MaximumStake+fee), updatedSenderAcc.Balance()) assert.Equal(t, td.sbx.TestParams.MaximumStake, updatedReceiverVal.Stake()) assert.Equal(t, owner, updatedReceiverVal.DelegateOwner()) assert.Equal(t, delegateShare, updatedReceiverVal.DelegateShare()) assert.Equal(t, delegateExpiry, updatedReceiverVal.DelegateExpiry()) assert.True(t, updatedReceiverVal.IsDelegated()) } ================================================ FILE: execution/executor/errors.go ================================================ package executor import ( "errors" "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" ) // ErrInsufficientFunds indicates that the balance is insufficient for the transaction. var ErrInsufficientFunds = errors.New("insufficient funds") // ErrPublicKeyNotSet indicates that the public key is not set for the initial Bond transaction. var ErrPublicKeyNotSet = errors.New("public key is not set") // ErrPublicKeyAlreadySet indicates that the public key has already been set for the given validator. var ErrPublicKeyAlreadySet = errors.New("public key is already set") // ErrValidatorBonded indicates that the validator is bonded. var ErrValidatorBonded = errors.New("validator is bonded") // ErrValidatorUnbonded indicates that the validator has unbonded. var ErrValidatorUnbonded = errors.New("validator has unbonded") // ErrBondingPeriod is returned when a validator is in the bonding period. var ErrBondingPeriod = errors.New("validator in bonding period") // ErrUnbondingPeriod is returned when a validator is in the unbonding period. var ErrUnbondingPeriod = errors.New("validator in unbonding period") // ErrInvalidSortitionProof indicates that the sortition proof is invalid. var ErrInvalidSortitionProof = errors.New("invalid sortition proof") // ErrExpiredSortition indicates that the sortition transaction is duplicated or expired. var ErrExpiredSortition = errors.New("expired sortition") // ErrValidatorInCommittee indicates that the validator is in the committee. var ErrValidatorInCommittee = errors.New("validator is in the committee") // ErrCommitteeJoinLimitExceeded indicates that at each height, // the maximum stake joining the committee can't be more than 1/3 of the committee's total stake. var ErrCommitteeJoinLimitExceeded = errors.New( "the maximum stake joining the committee can't be more than 1/3 of the committee's total stake") // ErrCommitteeLeaveLimitExceeded indicates that at each height, // the maximum stake leaving the committee can't be more than 1/3 of the committee's total stake. var ErrCommitteeLeaveLimitExceeded = errors.New( "the maximum stake leaving the committee can't be more than 1/3 of the committee's total stake") // ErrOldestValidatorNotProposed indicates that the oldest validator has not proposed any block yet. var ErrOldestValidatorNotProposed = errors.New("oldest validator has not proposed any block yet") // ErrInvalidBlockVersion is returned when the block version is invalid. var ErrInvalidBlockVersion = errors.New("invalid block version") // ErrInvalidDelegation is returned when the delegation parameters are invalid. var ErrInvalidDelegation = errors.New("invalid delegation") // ErrDelegateExpiryInPast is returned when the delegate expiry is in the past. var ErrDelegateExpiryInPast = errors.New("delegate expiry must be in the future") // ErrWithdrawMustGoToStakeOwner is returned when the withdrawal is not going to the stake owner. var ErrWithdrawMustGoToStakeOwner = errors.New("delegated validator withdraw must go to stake owner") // ErrInvalidDelegateOwner is returned when the delegate owner is invalid. var ErrInvalidDelegateOwner = errors.New("invalid delegate owner") // SmallStakeError is returned when the stake amount is less than the minimum stake. type SmallStakeError struct { Minimum amount.Amount } func (e SmallStakeError) Error() string { return fmt.Sprintf("stake amount can't be less than %v", e.Minimum.String()) } // MaximumStakeError is returned when the validator's stake exceeds the maximum stake limit. type MaximumStakeError struct { Maximum amount.Amount } func (e MaximumStakeError) Error() string { return fmt.Sprintf("validator's stake amount can't be more than %v", e.Maximum.String()) } // InvalidPayloadTypeError is returned when the transaction payload type is not valid. type InvalidPayloadTypeError struct { PayloadType payload.Type } func (e InvalidPayloadTypeError) Error() string { return fmt.Sprintf("unknown payload type: %s", e.PayloadType.String()) } // AccountNotFoundError is raised when the given address has no associated account. type AccountNotFoundError struct { Address crypto.Address } func (e AccountNotFoundError) Error() string { return fmt.Sprintf("no account found for address: %s", e.Address.String()) } // ValidatorNotFoundError is raised when the given address has no associated validator. type ValidatorNotFoundError struct { Address crypto.Address } func (e ValidatorNotFoundError) Error() string { return fmt.Sprintf("no validator found for address: %s", e.Address.String()) } ================================================ FILE: execution/executor/executor.go ================================================ package executor import ( "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" ) type Executor interface { Check(strict bool) error Execute() } func MakeExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (Executor, error) { var exe Executor var err error switch typ := trx.Payload().Type(); typ { case payload.TypeTransfer: exe, err = newTransferExecutor(trx, sbx) case payload.TypeBond: exe, err = newBondExecutor(trx, sbx) case payload.TypeUnbond: exe, err = newUnbondExecutor(trx, sbx) case payload.TypeWithdraw: exe, err = newWithdrawExecutor(trx, sbx) case payload.TypeSortition: exe, err = newSortitionExecutor(trx, sbx) case payload.TypeBatchTransfer: exe, err = newBatchTransferExecutor(trx, sbx) default: return nil, InvalidPayloadTypeError{ PayloadType: typ, } } return exe, err } ================================================ FILE: execution/executor/executor_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite sbx *sandbox.MockSandbox } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) sbx := sandbox.MockingSandbox(ts) randHeight := ts.RandHeight( testsuite.HeightWithMin(sbx.TestParams.UnbondInterval)) _ = sbx.TestStore.AddTestBlock(randHeight) return &testData{ TestSuite: ts, sbx: sbx, } } func (td *testData) checkTotalCoin(t *testing.T, fee amount.Amount) { t.Helper() total := amount.Amount(0) for _, acc := range td.sbx.TestStore.Accounts { total += acc.Balance() } for _, val := range td.sbx.TestStore.Validators { total += val.Stake() } assert.Equal(t, total+fee, amount.Amount(21_000_000*1e9)) } func (td *testData) check(t *testing.T, trx *tx.Tx, strict bool, expectedErr error) { t.Helper() exe, err := MakeExecutor(trx, td.sbx) if err != nil { require.ErrorIs(t, err, expectedErr) return } err = exe.Check(strict) require.ErrorIs(t, err, expectedErr) } func (td *testData) execute(t *testing.T, trx *tx.Tx) { t.Helper() exe, err := MakeExecutor(trx, td.sbx) require.NoError(t, err) exe.Execute() } ================================================ FILE: execution/executor/sortition.go ================================================ package executor import ( "cmp" "slices" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" ) type SortitionExecutor struct { sbx sandbox.Sandbox pld *payload.SortitionPayload validator *validator.Validator sortitionHeight types.Height } func newSortitionExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*SortitionExecutor, error) { pld := trx.Payload().(*payload.SortitionPayload) val := sbx.Validator(pld.Validator) if val == nil { return nil, ValidatorNotFoundError{ Address: pld.Validator, } } return &SortitionExecutor{ pld: pld, sbx: sbx, validator: val, sortitionHeight: trx.LockTime(), }, nil } func (e *SortitionExecutor) Check(strict bool) error { if e.sbx.CurrentHeight().SafeSub(e.validator.LastBondingHeight()) < e.sbx.Params().BondInterval { return ErrBondingPeriod } ok := e.sbx.VerifyProof(e.sortitionHeight, e.pld.Proof, e.validator) if !ok { return ErrInvalidSortitionProof } // Check for the duplicated or expired sortition transactions if e.sortitionHeight <= e.validator.LastSortitionHeight() { return ErrExpiredSortition } if strict { if err := e.canJoinCommittee(); err != nil { return err } } return nil } func (e *SortitionExecutor) canJoinCommittee() error { if e.sbx.Committee().Size() < e.sbx.Params().CommitteeSize { // There are available seats in the committee. if e.sbx.Committee().Contains(e.pld.Validator) { return ErrValidatorInCommittee } return nil } // The committee is full, check if the validator can join the committee. joiningNum := 0 joiningPower := int64(0) committee := e.sbx.Committee() e.sbx.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { if joined { if !committee.Contains(val.Address()) { joiningPower += val.Power() joiningNum++ } } }) if !committee.Contains(e.pld.Validator) { joiningPower += e.validator.Power() joiningNum++ } if joiningPower >= (committee.TotalPower() / 3) { return ErrCommitteeJoinLimitExceeded } vals := committee.Validators() slices.SortStableFunc(vals, func(a, b *validator.Validator) int { return cmp.Compare(a.LastSortitionHeight(), b.LastSortitionHeight()) }) leavingPower := int64(0) for i := 0; i < joiningNum; i++ { leavingPower += vals[i].Power() } if leavingPower >= (committee.TotalPower() / 3) { return ErrCommitteeLeaveLimitExceeded } oldestSortitionHeight := e.sbx.CurrentHeight() for _, v := range committee.Validators() { if v.LastSortitionHeight() < oldestSortitionHeight { oldestSortitionHeight = v.LastSortitionHeight() } } // If the oldest validator in the committee still hasn't propose a block yet, // it stays in the committee. proposerHeight := e.sbx.Committee().Proposer(0).LastSortitionHeight() if oldestSortitionHeight >= proposerHeight { return ErrOldestValidatorNotProposed } return nil } func (e *SortitionExecutor) Execute() { e.validator.UpdateLastSortitionHeight(e.sortitionHeight) e.sbx.JoinedToCommittee(e.pld.Validator) e.sbx.UpdateValidator(e.validator) } ================================================ FILE: execution/executor/sortition_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/stretchr/testify/assert" ) func updateCommittee(td *testData) { joiningCommittee := make([]*validator.Validator, 0) td.sbx.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { if joined { joiningCommittee = append(joiningCommittee, val) } }) td.sbx.TestCommittee.Update(0, joiningCommittee) td.sbx.TestJoinedValidators = make(map[crypto.Address]bool) } func TestExecuteSortitionTx(t *testing.T) { td := setup(t) bonderAddr, bonderAcc := td.sbx.TestStore.RandomTestAcc() bonderBalance := bonderAcc.Balance() stake := td.RandAmountRange( td.sbx.TestParams.MinimumStake, bonderBalance) bonderAcc.SubtractFromBalance(stake) td.sbx.UpdateAccount(bonderAddr, bonderAcc) valPub, _ := td.RandBLSKeyPair() valAddr := valPub.ValidatorAddress() val := td.sbx.MakeNewValidator(valPub) val.AddToStake(stake) td.sbx.UpdateValidator(val) curHeight := td.sbx.CurrentHeight() lockTime := td.sbx.CurrentHeight() proof := td.RandProof() val.UpdateLastBondingHeight(curHeight.SafeDecrease(td.sbx.Params().BondInterval - 1)) val.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val) assert.False(t, td.sbx.IsJoinedCommittee(val.Address())) t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() trx := tx.NewSortitionTx(lockTime, randomAddr, proof) td.check(t, trx, true, ValidatorNotFoundError{Address: randomAddr}) td.check(t, trx, false, ValidatorNotFoundError{Address: randomAddr}) }) t.Run("Should fail, Bonding period", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) td.check(t, trx, true, ErrBondingPeriod) td.check(t, trx, false, ErrBondingPeriod) }) // Let's add one more block td.sbx.TestStore.AddTestBlock(curHeight) t.Run("Should fail, invalid proof", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) td.sbx.TestAcceptSortition = false td.check(t, trx, true, ErrInvalidSortitionProof) td.check(t, trx, false, ErrInvalidSortitionProof) }) t.Run("Should fail, committee has free seats and validator is in the committee", func(t *testing.T) { val0 := td.sbx.Committee().Proposer(0) val0.UpdateLastSortitionHeight(lockTime - 1) val0.UpdateLastBondingHeight(curHeight.SafeDecrease(td.sbx.Params().BondInterval + 1)) td.sbx.UpdateValidator(val0) trx := tx.NewSortitionTx(lockTime, val0.Address(), proof) td.sbx.TestAcceptSortition = true td.check(t, trx, true, ErrValidatorInCommittee) td.check(t, trx, false, nil) }) t.Run("Should be ok", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) td.sbx.TestAcceptSortition = true td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) t.Run("Should fail, expired sortition", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime-1, val.Address(), proof) td.sbx.TestAcceptSortition = true td.check(t, trx, true, ErrExpiredSortition) td.check(t, trx, false, ErrExpiredSortition) }) t.Run("Should fail, duplicated sortition", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) td.check(t, trx, true, ErrExpiredSortition) td.check(t, trx, false, ErrExpiredSortition) }) updatedVal := td.sbx.Validator(valAddr) assert.Equal(t, lockTime, updatedVal.LastSortitionHeight()) assert.True(t, td.sbx.IsJoinedCommittee(val.Address())) td.checkTotalCoin(t, 0) } func TestChangePower1(t *testing.T) { td := setup(t) // This moves proposer to next validator updateCommittee(td) lockTime := td.sbx.CurrentHeight() proof := td.RandProof() // Let's create validators first pub1, _ := td.RandBLSKeyPair() amt1 := td.sbx.Committee().TotalPower() / 3 val1 := td.sbx.MakeNewValidator(pub1) val1.AddToStake(amount.Amount(amt1 - 1)) val1.UpdateLastBondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().BondInterval)) val1.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val1) pub2, _ := td.RandBLSKeyPair() val2 := td.sbx.MakeNewValidator(pub2) val2.AddToStake(2) val2.UpdateLastBondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().BondInterval)) val2.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val2) val3 := td.sbx.Committee().Proposer(0) val3.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val3) td.sbx.TestParams.CommitteeSize = 4 td.sbx.TestAcceptSortition = true trx1 := tx.NewSortitionTx(lockTime, val1.Address(), proof) td.check(t, trx1, true, nil) td.check(t, trx1, false, nil) td.execute(t, trx1) trx2 := tx.NewSortitionTx(lockTime, val2.Address(), proof) td.check(t, trx2, true, ErrCommitteeJoinLimitExceeded) td.check(t, trx2, false, nil) // Val3 is a Committee member trx3 := tx.NewSortitionTx(lockTime, val3.Address(), proof) td.check(t, trx3, true, nil) td.check(t, trx3, false, nil) } func TestChangePower2(t *testing.T) { td := setup(t) // This moves proposer to next validator updateCommittee(td) lockTime := td.sbx.CurrentHeight() proof := td.RandProof() // Let's create validators first pub1, _ := td.RandBLSKeyPair() val1 := td.sbx.MakeNewValidator(pub1) val1.AddToStake(1) val1.UpdateLastBondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().BondInterval)) val1.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val1) pub2, _ := td.RandBLSKeyPair() val2 := td.sbx.MakeNewValidator(pub2) val2.AddToStake(1) val2.UpdateLastBondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().BondInterval)) val2.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val2) pub3, _ := td.RandBLSKeyPair() val3 := td.sbx.MakeNewValidator(pub3) val3.AddToStake(1) val3.UpdateLastBondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().BondInterval)) val3.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val3) val4 := td.sbx.Committee().Proposer(0) val4.UpdateLastSortitionHeight(lockTime - 1) td.sbx.UpdateValidator(val4) td.sbx.TestParams.CommitteeSize = 7 td.sbx.TestAcceptSortition = true trx1 := tx.NewSortitionTx(lockTime, val1.Address(), proof) td.check(t, trx1, true, nil) td.check(t, trx1, false, nil) td.execute(t, trx1) trx2 := tx.NewSortitionTx(lockTime, val2.Address(), proof) td.check(t, trx2, true, nil) td.check(t, trx2, false, nil) td.execute(t, trx2) trx3 := tx.NewSortitionTx(lockTime, val3.Address(), proof) td.check(t, trx3, true, ErrCommitteeLeaveLimitExceeded) td.check(t, trx3, false, nil) // Committee member trx4 := tx.NewSortitionTx(lockTime, val4.Address(), proof) td.check(t, trx4, true, nil) td.check(t, trx4, false, nil) td.execute(t, trx4) } // TestOldestDidNotPropose tests if the oldest validator in the committee had // chance to propose a block or not. func TestOldestDidNotPropose(t *testing.T) { td := setup(t) // Let's create validators first vals := make([]*validator.Validator, 9) for index := 0; index < 9; index++ { pub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(pub) val.AddToStake(10 * 1e9) val.UpdateLastBondingHeight( td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().BondInterval)) td.sbx.UpdateValidator(val) vals[index] = val } td.sbx.TestParams.CommitteeSize = 7 td.sbx.TestAcceptSortition = true // This moves proposer to the next validator updateCommittee(td) // Let's update committee height := td.sbx.CurrentHeight() for i := uint32(0); i < 7; i++ { height++ _ = td.sbx.TestStore.AddTestBlock(height) lockTime := height trx := tx.NewSortitionTx(lockTime, vals[i].Address(), td.RandProof()) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) updateCommittee(td) } height++ _ = td.sbx.TestStore.AddTestBlock(height) lockTime := td.sbx.CurrentHeight() trx1 := tx.NewSortitionTx(lockTime, vals[7].Address(), td.RandProof()) td.check(t, trx1, true, nil) td.check(t, trx1, false, nil) td.execute(t, trx1) trx2 := tx.NewSortitionTx(lockTime, vals[8].Address(), td.RandProof()) td.check(t, trx2, true, nil) td.check(t, trx2, false, nil) td.execute(t, trx2) updateCommittee(td) height++ _ = td.sbx.TestStore.AddTestBlock(height) // Entering validator 16 trx3 := tx.NewSortitionTx(lockTime+1, vals[8].Address(), td.RandProof()) td.check(t, trx3, true, ErrOldestValidatorNotProposed) td.check(t, trx3, false, nil) td.execute(t, trx3) } ================================================ FILE: execution/executor/transfer.go ================================================ package executor import ( "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" ) type TransferExecutor struct { sbx sandbox.Sandbox pld *payload.TransferPayload fee amount.Amount sender *account.Account receiver *account.Account } func newTransferExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*TransferExecutor, error) { pld := trx.Payload().(*payload.TransferPayload) sender := sbx.Account(pld.From) if sender == nil { return nil, AccountNotFoundError{Address: pld.From} } var receiver *account.Account if pld.To == pld.From { receiver = sender } else { receiver = sbx.Account(pld.To) if receiver == nil { receiver = sbx.MakeNewAccount(pld.To) } } return &TransferExecutor{ sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, receiver: receiver, }, nil } func (e *TransferExecutor) Check(_ bool) error { if e.sender.Balance() < e.pld.Amount+e.fee { return ErrInsufficientFunds } return nil } func (e *TransferExecutor) Execute() { e.sender.SubtractFromBalance(e.pld.Amount + e.fee) e.receiver.AddToBalance(e.pld.Amount) e.sbx.UpdateAccount(e.pld.From, e.sender) e.sbx.UpdateAccount(e.pld.To, e.receiver) } ================================================ FILE: execution/executor/transfer_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/types/tx" "github.com/stretchr/testify/assert" ) func TestExecuteTransferTx(t *testing.T) { td := setup(t) senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() senderBalance := senderAcc.Balance() receiverAddr := td.RandAccAddress() amt := td.RandAmountRange(0, senderBalance) fee := td.RandFee() lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandAccAddress() trx := tx.NewTransferTx(lockTime, randomAddr, receiverAddr, amt, fee) td.check(t, trx, true, AccountNotFoundError{Address: randomAddr}) td.check(t, trx, false, AccountNotFoundError{Address: randomAddr}) }) t.Run("Should fail, insufficient balance", func(t *testing.T) { trx := tx.NewTransferTx(lockTime, senderAddr, receiverAddr, senderBalance+1, 0) td.check(t, trx, true, ErrInsufficientFunds) td.check(t, trx, false, ErrInsufficientFunds) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewTransferTx(lockTime, senderAddr, receiverAddr, amt, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedSenderAcc := td.sbx.Account(senderAddr) updatedReceiverAcc := td.sbx.Account(receiverAddr) assert.Equal(t, senderBalance-(amt+fee), updatedSenderAcc.Balance()) assert.Equal(t, amt, updatedReceiverAcc.Balance()) td.checkTotalCoin(t, fee) } func TestTransferToSelf(t *testing.T) { td := setup(t) senderAddr, senderAcc := td.sbx.TestStore.RandomTestAcc() amt := td.RandAmountRange(0, senderAcc.Balance()) fee := td.RandFee() lockTime := td.sbx.CurrentHeight() trx := tx.NewTransferTx(lockTime, senderAddr, senderAddr, amt, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) expectedBalance := senderAcc.Balance() - fee // Fee should be deducted updatedAcc := td.sbx.Account(senderAddr) assert.Equal(t, expectedBalance, updatedAcc.Balance()) td.checkTotalCoin(t, fee) } ================================================ FILE: execution/executor/unbond.go ================================================ package executor import ( "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" ) type UnbondExecutor struct { sbx sandbox.Sandbox pld *payload.UnbondPayload validator *validator.Validator } func newUnbondExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*UnbondExecutor, error) { pld := trx.Payload().(*payload.UnbondPayload) val := sbx.Validator(pld.Validator) if val == nil { return nil, ValidatorNotFoundError{Address: pld.Validator} } return &UnbondExecutor{ sbx: sbx, pld: pld, validator: val, }, nil } func (e *UnbondExecutor) Check(strict bool) error { if e.validator.IsUnbonded() { return ErrValidatorUnbonded } if e.validator.IsDelegated() { if e.pld.DelegateOwner != e.validator.DelegateOwner() { return ErrInvalidDelegateOwner } } if strict { // In strict mode, the unbond transaction will be rejected if the // validator is in the committee. // In non-strict mode, they are added to the transaction pool and // processed once eligible. if e.sbx.Committee().Contains(e.pld.Validator) { return ErrValidatorInCommittee } // In strict mode, unbond transactions will be rejected if a validator is // going to be in the committee for the next height. // In non-strict mode, they are added to the transaction pool and // processed once eligible. if e.sbx.IsJoinedCommittee(e.pld.Validator) { return ErrValidatorInCommittee } } return nil } func (e *UnbondExecutor) Execute() { unbondedPower := e.validator.Power() e.validator.UpdateUnbondingHeight(e.sbx.CurrentHeight()) // The validator's power is reduced to zero, // so we update the power delta with the negative value of the validator's power. e.sbx.UpdatePowerDelta(-1 * unbondedPower) e.sbx.UpdateValidator(e.validator) } ================================================ FILE: execution/executor/unbond_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/stretchr/testify/assert" ) func TestExecuteUnbondTx(t *testing.T) { td := setup(t) bonderAddr, bonderAcc := td.sbx.TestStore.RandomTestAcc() bonderBalance := bonderAcc.Balance() stake := td.RandAmountRange( td.sbx.TestParams.MinimumStake, bonderBalance) bonderAcc.SubtractFromBalance(stake) td.sbx.UpdateAccount(bonderAddr, bonderAcc) valPub, _ := td.RandBLSKeyPair() valAddr := valPub.ValidatorAddress() val := td.sbx.MakeNewValidator(valPub) val.AddToStake(stake) td.sbx.UpdateValidator(val) lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandValAddress() trx := tx.NewUnbondTx(lockTime, randomAddr) td.check(t, trx, true, ValidatorNotFoundError{Address: randomAddr}) td.check(t, trx, false, ValidatorNotFoundError{Address: randomAddr}) }) t.Run("Should fail, inside committee", func(t *testing.T) { val0 := td.sbx.Committee().Proposer(0) trx := tx.NewUnbondTx(lockTime, val0.Address()) td.check(t, trx, true, ErrValidatorInCommittee) td.check(t, trx, false, nil) }) t.Run("Should fail, joining committee", func(t *testing.T) { randPub, _ := td.RandBLSKeyPair() randVal := td.sbx.MakeNewValidator(randPub) td.sbx.UpdateValidator(randVal) td.sbx.JoinedToCommittee(randVal.Address()) trx := tx.NewUnbondTx(lockTime, randPub.ValidatorAddress()) td.check(t, trx, true, ErrValidatorInCommittee) td.check(t, trx, false, nil) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewUnbondTx(lockTime, valAddr) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) t.Run("Should fail, Cannot unbond if already unbonded", func(t *testing.T) { trx := tx.NewUnbondTx(lockTime, valAddr) td.check(t, trx, true, ErrValidatorUnbonded) td.check(t, trx, false, ErrValidatorUnbonded) }) updatedVal := td.sbx.Validator(valAddr) assert.Equal(t, stake, updatedVal.Stake()) assert.Zero(t, updatedVal.Power()) assert.Equal(t, lockTime, updatedVal.UnbondingHeight()) assert.Equal(t, int64(-stake), td.sbx.PowerDelta()) td.checkTotalCoin(t, 0) } func TestPowerDeltaUnbond(t *testing.T) { td := setup(t) pub, _ := td.RandBLSKeyPair() valAddr := pub.ValidatorAddress() val := td.sbx.MakeNewValidator(pub) amt := td.RandAmount() val.AddToStake(amt) td.sbx.UpdateValidator(val) lockTime := td.sbx.CurrentHeight() trx := tx.NewUnbondTx(lockTime, valAddr) td.execute(t, trx) assert.Equal(t, int64(-amt), td.sbx.PowerDelta()) } func TestExecuteDelegatedUnbondTx(t *testing.T) { td := setup(t) valPub, _ := td.RandBLSKeyPair() valAddr := valPub.ValidatorAddress() val := td.sbx.MakeNewValidator(valPub) val.AddToStake(td.sbx.TestParams.MaximumStake) owner := td.RandAccAddress() val.SetDelegation(owner, amount.Amount(0.2e9), td.sbx.CurrentHeight()+10) td.sbx.UpdateValidator(val) lockTime := td.sbx.CurrentHeight() t.Run("Should fail, invalid delegate owner", func(t *testing.T) { trx := tx.NewUnbondTx(lockTime, valAddr) pld := trx.Payload().(*payload.UnbondPayload) pld.DelegateOwner = td.RandAccAddress() td.check(t, trx, true, ErrInvalidDelegateOwner) td.check(t, trx, false, ErrInvalidDelegateOwner) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewUnbondTx(lockTime, valAddr) pld := trx.Payload().(*payload.UnbondPayload) pld.DelegateOwner = owner td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedVal := td.sbx.Validator(valAddr) assert.Equal(t, lockTime, updatedVal.UnbondingHeight()) } ================================================ FILE: execution/executor/withdraw.go ================================================ package executor import ( "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" ) type WithdrawExecutor struct { sbx sandbox.Sandbox pld *payload.WithdrawPayload fee amount.Amount sender *validator.Validator receiver *account.Account } func newWithdrawExecutor(trx *tx.Tx, sbx sandbox.Sandbox) (*WithdrawExecutor, error) { pld := trx.Payload().(*payload.WithdrawPayload) sender := sbx.Validator(pld.From) if sender == nil { return nil, ValidatorNotFoundError{Address: pld.From} } receiver := sbx.Account(pld.To) if receiver == nil { receiver = sbx.MakeNewAccount(pld.To) } return &WithdrawExecutor{ sbx: sbx, pld: pld, fee: trx.Fee(), sender: sender, receiver: receiver, }, nil } func (e *WithdrawExecutor) Check(_ bool) error { if e.sender.Stake() < e.pld.Value()+e.fee { return ErrInsufficientFunds } if !e.sender.IsUnbonded() { return ErrValidatorBonded } if e.sbx.CurrentHeight() < e.sender.UnbondingHeight().SafeIncrease(e.sbx.Params().UnbondInterval) { return ErrUnbondingPeriod } // For delegated validators (PIP-49), only the stake owner can receive withdrawn principal. if e.sender.IsDelegated() { if e.pld.To != e.sender.DelegateOwner() { return ErrWithdrawMustGoToStakeOwner } } return nil } func (e *WithdrawExecutor) Execute() { e.sender.SubtractFromStake(e.pld.Amount + e.fee) e.receiver.AddToBalance(e.pld.Amount) e.sbx.UpdateValidator(e.sender) e.sbx.UpdateAccount(e.pld.To, e.receiver) } ================================================ FILE: execution/executor/withdraw_test.go ================================================ package executor import ( "testing" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/stretchr/testify/assert" ) func TestExecuteWithdrawTx(t *testing.T) { td := setup(t) bonderAddr, bonderAcc := td.sbx.TestStore.RandomTestAcc() bonderBalance := bonderAcc.Balance() stake := td.RandAmountRange( td.sbx.TestParams.MinimumStake, bonderBalance) bonderAcc.SubtractFromBalance(stake) td.sbx.UpdateAccount(bonderAddr, bonderAcc) valPub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(valPub) val.AddToStake(stake) td.sbx.UpdateValidator(val) totalStake := val.Stake() fee := td.RandFee() amt := td.RandAmountRange(0, totalStake-fee) senderAddr := val.Address() receiverAddr := td.RandAccAddress() lockTime := td.sbx.CurrentHeight() t.Run("Should fail, unknown address", func(t *testing.T) { randomAddr := td.RandValAddress() trx := tx.NewWithdrawTx(lockTime, randomAddr, receiverAddr, amt, fee) td.check(t, trx, true, ValidatorNotFoundError{Address: randomAddr}) td.check(t, trx, false, ValidatorNotFoundError{Address: randomAddr}) }) t.Run("Should fail, hasn't unbonded yet", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, senderAddr, receiverAddr, amt, fee) td.check(t, trx, true, ErrValidatorBonded) td.check(t, trx, false, ErrValidatorBonded) }) val.UpdateUnbondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().UnbondInterval) + 1) td.sbx.UpdateValidator(val) t.Run("Should fail, insufficient balance", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, senderAddr, receiverAddr, totalStake, 1) td.check(t, trx, true, ErrInsufficientFunds) td.check(t, trx, false, ErrInsufficientFunds) }) t.Run("Should fail, hasn't passed unbonding period", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, senderAddr, receiverAddr, amt, fee) td.check(t, trx, true, ErrUnbondingPeriod) td.check(t, trx, false, ErrUnbondingPeriod) }) curHeight := td.sbx.CurrentHeight() td.sbx.TestStore.AddTestBlock(curHeight + 1) t.Run("Should pass, Everything is Ok!", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, senderAddr, receiverAddr, amt, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedSenderVal := td.sbx.Validator(senderAddr) updatedReceiverAcc := td.sbx.Account(receiverAddr) assert.Equal(t, totalStake-amt-fee, updatedSenderVal.Stake()) assert.Equal(t, amt, updatedReceiverAcc.Balance()) td.checkTotalCoin(t, fee) } func TestExecuteDelegatedWithdrawTx(t *testing.T) { td := setup(t) valPub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(valPub) totalStake := td.sbx.TestParams.MaximumStake val.AddToStake(totalStake) owner := td.RandAccAddress() val.SetDelegation(owner, amount.Amount(0.3e9), td.sbx.CurrentHeight()+10) val.UpdateUnbondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.Params().UnbondInterval) + 1) td.sbx.UpdateValidator(val) fee := td.RandFee() amt := td.RandAmountRange(0, totalStake-fee) lockTime := td.sbx.CurrentHeight() curHeight := td.sbx.CurrentHeight() td.sbx.TestStore.AddTestBlock(curHeight + 1) t.Run("Should fail, receiver must be stake owner", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, val.Address(), td.RandAccAddress(), amt, fee) td.check(t, trx, true, ErrWithdrawMustGoToStakeOwner) td.check(t, trx, false, ErrWithdrawMustGoToStakeOwner) }) t.Run("Ok", func(t *testing.T) { trx := tx.NewWithdrawTx(lockTime, val.Address(), owner, amt, fee) td.check(t, trx, true, nil) td.check(t, trx, false, nil) td.execute(t, trx) }) updatedVal := td.sbx.Validator(val.Address()) updatedOwner := td.sbx.Account(owner) assert.Equal(t, totalStake-amt-fee, updatedVal.Stake()) assert.Equal(t, amt, updatedOwner.Balance()) } ================================================ FILE: genesis/genesis.go ================================================ package genesis import ( "encoding/json" "os" "time" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" ) type ChainType uint8 const ( Mainnet ChainType = 0 Testnet ChainType = 1 Localnet ChainType = 2 ) func (n ChainType) IsMainnet() bool { return n == Mainnet } func (n ChainType) IsTestnet() bool { return n == Testnet } func (n ChainType) String() string { switch n { case Mainnet: return "Mainnet" case Testnet: return "Testnet" case Localnet: return "Localnet" default: return "Unknown" } } type genAccount struct { Address string `cbor:"1,keyasint" json:"address"` Balance amount.Amount `cbor:"2,keyasint" json:"balance"` } type genValidator struct { PublicKey string `cbor:"1,keyasint" json:"public_key"` } // Genesis is stored in the state database. type Genesis struct { data genesisData } type genesisData struct { GenesisTime time.Time `cbor:"1,keyasint" json:"genesis_time"` Params *GenesisParams `cbor:"2,keyasint" json:"params"` Accounts []genAccount `cbor:"3,keyasint" json:"accounts"` Validators []genValidator `cbor:"4,keyasint" json:"validators"` } func (gen *Genesis) Hash() hash.Hash { bs, _ := cbor.Marshal(gen.data) return hash.CalcHash(bs) } func (gen *Genesis) GenesisTime() time.Time { return gen.data.GenesisTime } func (gen *Genesis) Params() *GenesisParams { return gen.data.Params } func (gen *Genesis) Accounts() map[crypto.Address]*account.Account { accs := make(map[crypto.Address]*account.Account) for i, genAcc := range gen.data.Accounts { addr, err := crypto.AddressFromString(genAcc.Address) if err != nil { panic(err) } acc := account.NewAccount(int32(i)) acc.AddToBalance(genAcc.Balance) accs[addr] = acc } return accs } func (gen *Genesis) Validators() []*validator.Validator { vals := make([]*validator.Validator, 0, len(gen.data.Validators)) for i, genVal := range gen.data.Validators { pub, _ := bls.PublicKeyFromString(genVal.PublicKey) val := validator.NewValidator(pub, int32(i)) vals = append(vals, val) } return vals } func (gen *Genesis) MarshalJSON() ([]byte, error) { return json.MarshalIndent(&gen.data, " ", " ") } func (gen *Genesis) UnmarshalJSON(bs []byte) error { return json.Unmarshal(bs, &gen.data) } func makeGenesisAccount(addr crypto.Address, acc *account.Account) genAccount { return genAccount{ Address: addr.String(), Balance: acc.Balance(), } } func makeGenesisValidator(val *validator.Validator) genValidator { return genValidator{ PublicKey: val.PublicKey().String(), } } func MakeGenesis(genesisTime time.Time, accounts map[crypto.Address]*account.Account, validators []*validator.Validator, params *GenesisParams, ) *Genesis { genAccs := make([]genAccount, len(accounts)) for addr, acc := range accounts { genAcc := makeGenesisAccount(addr, acc) genAccs[acc.Number()] = genAcc } genVals := make([]genValidator, len(validators)) for _, val := range validators { genVal := makeGenesisValidator(val) genVals[val.Number()] = genVal } return &Genesis{ data: genesisData{ GenesisTime: genesisTime, Accounts: genAccs, Validators: genVals, Params: params, }, } } // LoadFromFile loads genesis object from a JSON file. func LoadFromFile(file string) (*Genesis, error) { dat, err := os.ReadFile(file) if err != nil { return nil, err } var gen Genesis if err := json.Unmarshal(dat, &gen); err != nil { return nil, err } return &gen, nil } // SaveToFile saves the genesis into a JSON file. func (gen *Genesis) SaveToFile(file string) error { data, err := gen.MarshalJSON() if err != nil { return err } // write dataContent to file return util.WriteFile(file, data) } func (gen *Genesis) TotalSupply() amount.Amount { totalSuppyly := amount.Amount(0) for _, acc := range gen.data.Accounts { totalSuppyly += acc.Balance } return totalSuppyly } func (gen *Genesis) ChainType() ChainType { switch gen.Hash() { case MainnetGenesis().Hash(): return Mainnet case TestnetGenesis().Hash(): return Testnet default: return Localnet } } ================================================ FILE: genesis/genesis_params.go ================================================ package genesis import ( "time" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" ) type GenesisParams struct { BlockVersion protocol.Version `cbor:"1,keyasint" json:"block_version"` BlockIntervalInSecond int `cbor:"2,keyasint" json:"block_interval_in_second"` CommitteeSize int `cbor:"3,keyasint" json:"committee_size"` BlockReward amount.Amount `cbor:"4,keyasint" json:"block_reward"` TransactionToLiveInterval uint32 `cbor:"5,keyasint" json:"transaction_to_live_interval"` BondInterval uint32 `cbor:"6,keyasint" json:"bond_interval"` UnbondInterval uint32 `cbor:"7,keyasint" json:"unbond_interval"` SortitionInterval uint32 `cbor:"8,keyasint" json:"sortition_interval"` FeeFraction float64 `cbor:"9,keyasint" json:"fee_fraction"` // Deprecated: Replaced by fix fee MinimumFee amount.Amount `cbor:"10,keyasint" json:"minimum_fee"` // Deprecated: Replaced by fix fee MaximumFee amount.Amount `cbor:"11,keyasint" json:"maximum_fee"` // Deprecated: Replaced by fix fee MinimumStake amount.Amount `cobr:"12,keyasint" json:"minimum_stake"` MaximumStake amount.Amount `cbor:"13,keyasint" json:"maximum_stake"` } func DefaultGenesisParams() *GenesisParams { return &GenesisParams{ BlockVersion: 1, BlockIntervalInSecond: 10, CommitteeSize: 51, BlockReward: 1000000000, TransactionToLiveInterval: 8640, // one day BondInterval: 360, // one hour UnbondInterval: 181440, // 21 days SortitionInterval: 17, MinimumStake: 1000000000, MaximumStake: 1000000000000, // Deprecated: Replaced by fix fee FeeFraction: 0.0, MinimumFee: 0, MaximumFee: 0, } } func (p *GenesisParams) BlockInterval() time.Duration { return time.Duration(p.BlockIntervalInSecond) * time.Second } ================================================ FILE: genesis/genesis_test.go ================================================ package genesis_test import ( "encoding/json" "testing" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) acc, addr := ts.GenerateTestAccount( testsuite.AccountWithNumber(0), testsuite.AccountWithBalance(100000)) val := ts.GenerateTestValidator( testsuite.ValidatorWithNumber(0), ) gen1 := genesis.MakeGenesis(util.RoundNow(10), map[crypto.Address]*account.Account{addr: acc}, []*validator.Validator{val}, genesis.DefaultGenesisParams()) gen2 := new(genesis.Genesis) assert.Equal(t, 10, gen1.Params().BlockIntervalInSecond) bz, err := json.MarshalIndent(gen1, " ", " ") require.NoError(t, err) err = json.Unmarshal(bz, gen2) require.NoError(t, err) require.Equal(t, gen1.Hash(), gen2.Hash()) // Test saving and loading f := util.TempFilePath() require.NoError(t, gen1.SaveToFile(f)) gen3, err := genesis.LoadFromFile(f) require.NoError(t, err) require.Equal(t, gen1.Hash(), gen3.Hash()) _, err = genesis.LoadFromFile(util.TempFilePath()) require.Error(t, err, "file not found") } func TestGenesisMainnet(t *testing.T) { gen := genesis.MainnetGenesis() assert.Len(t, gen.Validators(), 4) assert.Len(t, gen.Accounts(), 5) genTime, _ := time.Parse("02 Jan 2006, 15:04 MST", "24 Jan 2024, 20:24 UTC") expected, _ := hash.FromString("e4d59e3145c9d718caf178edb33bc2ca7fe43e5b30990c9d57d53a60c4741432") assert.Equal(t, expected, gen.Hash()) assert.Equal(t, genTime, gen.GenesisTime()) assert.Equal(t, uint32(8640/24), gen.Params().BondInterval) assert.Equal(t, uint32(8640*21), gen.Params().UnbondInterval) assert.Equal(t, genesis.Mainnet, gen.ChainType()) assert.Equal(t, amount.Amount(42e15), gen.TotalSupply()) assert.True(t, gen.ChainType().IsMainnet()) } func TestCheckGenesisAccountAndValidator(t *testing.T) { ts := testsuite.NewTestSuite(t) accs := map[crypto.Address]*account.Account{} vals := []*validator.Validator{} for i := int32(0); i < 10; i++ { pub, _ := ts.RandBLSKeyPair() acc := account.NewAccount(i) val := validator.NewValidator(pub, i) accs[pub.AccountAddress()] = acc vals = append(vals, val) } gen := genesis.MakeGenesis(time.Now(), accs, vals, genesis.DefaultGenesisParams()) for addr, acc := range gen.Accounts() { assert.Equal(t, accs[addr], acc) } for i, val := range gen.Validators() { assert.Equal(t, vals[i].Hash(), val.Hash()) } } func TestGenesisTestnet(t *testing.T) { crypto.AddressHRP = "tpc" gen := genesis.TestnetGenesis() assert.Len(t, gen.Validators(), 4) assert.Len(t, gen.Accounts(), 5) genTime, _ := time.Parse("2006-01-02", "2024-03-16") expected, _ := hash.FromString("13f96e6fbc9e0de0d53537ac5e894fc8e66be1600436db2df1511dc30696e822") assert.Equal(t, expected, gen.Hash()) assert.Equal(t, genTime, gen.GenesisTime()) assert.Equal(t, uint32(360), gen.Params().BondInterval) assert.Equal(t, genesis.Testnet, gen.ChainType()) assert.Equal(t, amount.Amount(42e15), gen.TotalSupply()) assert.True(t, gen.ChainType().IsTestnet()) // reset address HRP global variable to miannet to prevent next tests failing. crypto.AddressHRP = "pc" } ================================================ FILE: genesis/mainnet.go ================================================ package genesis import ( _ "embed" "encoding/json" ) //go:embed mainnet.json var mainnetJSON []byte func MainnetGenesis() *Genesis { gen := new(Genesis) _ = json.Unmarshal(mainnetJSON, &gen) return gen } ================================================ FILE: genesis/mainnet.json ================================================ { "genesis_time": "2024-01-24T20:24:00Z", "params": { "block_version": 1, "block_interval_in_second": 10, "committee_size": 51, "block_reward": 1000000000, "transaction_to_live_interval": 8640, "bond_interval": 360, "unbond_interval": 181440, "sortition_interval": 17, "fee_fraction": 0.0001, "minimum_fee": 1000, "maximum_fee": 1000000, "minimum_stake": 1000000000, "maximum_stake": 1000000000000 }, "accounts": [ { "address": "000000000000000000000000000000000000000000", "balance": 21000000000000000 }, { "address": "pc1z2r0fmu8sg2ffa0tgrr08gnefcxl2kq7wvquf8z", "balance": 8400000000000000 }, { "address": "pc1zprhnvcsy3pthekdcu28cw8muw4f432hkwgfasv", "balance": 6300000000000000 }, { "address": "pc1znn2qxsugfrt7j4608zvtnxf8dnz8skrxguyf45", "balance": 4200000000000000 }, { "address": "pc1zs64vdggjcshumjwzaskhfn0j9gfpkvche3kxd3", "balance": 2100000000000000 } ], "validators": [ { "public_key": "public1pslqgpw7c97fxaww6t7lcq88mqgnw43gegttwy7ame6jl83m72nyamek94nlyph75jx4maeq7yf3fwqqy4lw08ykjxduna6cx5tgy089umefcd60tnpe4netln29l5rs9uk9dm8lhefm7q09hytuxg2fzkuj8c7w5" }, { "public_key": "public1p5ww955ah5u35yx5g0v06nmlp4dxmd6achpd7w8t854qlw4vnxmmezpu86qwk07elk9msjfhdexkg6qj46jhgcc6fv22xclrpvxz2d6zjtldm9n3nzmnryszs4tfuufak2a7lea9jqu4asfmharsr86m7jvlekwt9" }, { "public_key": "public1p47uaggm5ya64ftcw28k34u7newp59jlj9g7trxzsgt7deqya6tcqxkmdq0lg2009t55s0z9jf2vu290qxp507s05rteagt2twhg967sec9nnvnrqdew4xkmleym3x9qwwe68hkdh6elhhncpyc472lqzsvvmatqs" }, { "public_key": "public1psxmnqxvu0d3xf66uyah02cj6wqyzlxz8275ha4m4e640txvndgqjydlzcxvc57dfmh0mx5guj2x2uxpw373r4wfgjzmxcxaf5zdd407k9uzjfekkkdjsvep56t5x7z6l7v8d3ppsv799ah2n2e9jmljnssrjj9ru" } ] } ================================================ FILE: genesis/testnet.go ================================================ package genesis import ( _ "embed" "encoding/json" ) //go:embed testnet.json var testnetJSON []byte func TestnetGenesis() *Genesis { gen := new(Genesis) _ = json.Unmarshal(testnetJSON, &gen) return gen } ================================================ FILE: genesis/testnet.json ================================================ { "genesis_time": "2024-03-16T00:00:00Z", "params": { "block_version": 1, "block_interval_in_second": 10, "committee_size": 51, "block_reward": 1000000000, "transaction_to_live_interval": 8640, "bond_interval": 360, "unbond_interval": 181440, "sortition_interval": 17, "fee_fraction": 0.0001, "minimum_fee": 1000, "maximum_fee": 1000000, "minimum_stake": 1000000000, "maximum_stake": 1000000000000 }, "accounts": [ { "address": "000000000000000000000000000000000000000000", "balance": 21000000000000000 }, { "address": "tpc1zeszhgvffmf2fx7arpp935n40ek09kx200evaga", "balance": 8400000000000000 }, { "address": "tpc1z76trjq323tp8cs2staa4vnhaegpxaqc8zm7uzk", "balance": 6300000000000000 }, { "address": "tpc1zty5pa3x0h879r5zdze6tat4exu97l4y2hyplkm", "balance": 4200000000000000 }, { "address": "tpc1zq6r4qjkgdn7qg7fdnusa9wsvepc94xeqd6rf6d", "balance": 2100000000000000 } ], "validators": [ { "public_key": "tpublic1ps5e3k3x9v3q0wdgw48sswx5za45w36fkeay8hkcwhgpl3q3w8zqs4uu7ewzhn537d5pnkmum3lf0yzqk9f2sld0qcl3700y372jxcjmt3kjzmfehru29z6ak7ehfmzh0965kgzdanptm7jnf89zvtkglzymnlq6q" }, { "public_key": "tpublic1p49mvzl9ray2rfhwg77ne7m457qlc5knpv897skqnkgfa3luluzq784hf7px30r68knhnhp5td5gayz8ss72dyfxgq8kk2qqm0y86tqsmzss8dvfn433z9j3g0saqhahzcw37f8wy48edrqh6qkf6h9yr4gg8093c" }, { "public_key": "tpublic1p3yyfsjdudntxlr6k5hdt249wxe6ajfnnkg6knklzt8lmj66s8z4j2duqk7qay8n8d47u0n6w97c8qrwwkljewqqw3t3ufy662llqflcq9nn6wsg35twdc3l5vn72j4ez50s982fxxh6per6hftn3e2v7fgm4gx35" }, { "public_key": "tpublic1pjy7z27zm6795xhj8rln65cve88dtqjkg7gca6scxzwwfxpncnmkhg35n2rw3fa9e04cqcc8c9fyqvpm7y39wj0x2e5qrl0he60ms6v79vga3le2uvgn566p7x9exjnyhh3klycqddstj7339afnm73k09v8k52uy" } ] } ================================================ FILE: go.mod ================================================ module github.com/pactus-project/pactus go 1.26.2 require ( github.com/NathanBaulch/protoc-gen-cobra v1.2.1 github.com/beevik/ntp v1.5.0 github.com/c-bata/go-prompt v0.2.6 github.com/consensys/gnark-crypto v0.20.1 github.com/ezex-io/gopkg/pipeline v0.0.0-20260127151556-579a32f19aa7 github.com/ezex-io/gopkg/scheduler v0.0.0-20260127151556-579a32f19aa7 github.com/ezex-io/gopkg/signal v0.0.0-20260127151556-579a32f19aa7 github.com/ezex-io/gopkg/testsuite v0.0.0-20260127151556-579a32f19aa7 github.com/fxamacker/cbor/v2 v2.9.1 github.com/glebarez/go-sqlite v1.22.1-0.20250214171204-e6de9fc0c320 github.com/go-zeromq/zmq4 v0.17.0 github.com/gofrs/flock v0.13.0 github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/google/uuid v1.6.0 github.com/gorilla/handlers v1.5.2 github.com/gorilla/mux v1.8.1 github.com/gotk3/gotk3 v0.6.2 github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 github.com/hashicorp/golang-lru/v2 v2.0.7 github.com/inancgumus/screen v0.0.0-20190314163918-06e984b86ed3 github.com/ipfs/boxo v0.38.0 github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213 github.com/kilic/bls12-381 v0.1.1-0.20220929213557-ca162e8a70f4 github.com/libp2p/go-libp2p v0.48.0 github.com/libp2p/go-libp2p-kad-dht v0.39.0 github.com/libp2p/go-libp2p-pubsub v0.15.0 github.com/manifoldco/promptui v0.9.0 github.com/multiformats/go-multiaddr v0.16.1 github.com/pacviewer/jrpc-gateway v0.6.0 github.com/pelletier/go-toml/v2 v2.3.0 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.23.2 github.com/rs/cors v1.11.1 github.com/rs/zerolog v1.35.0 github.com/schollz/progressbar/v3 v3.19.0 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d go.uber.org/mock v0.6.0 golang.org/x/crypto v0.50.0 golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f golang.org/x/term v0.42.0 google.golang.org/grpc v1.80.0 google.golang.org/protobuf v1.36.11 gopkg.in/natefinch/lumberjack.v2 v2.2.1 ) require ( filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 // indirect filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b // indirect github.com/benbjohnson/clock v1.3.5 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bits-and-blooms/bitset v1.24.4 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chzyer/readline v1.5.1 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/creachadair/jrpc2 v1.3.5 // indirect github.com/creachadair/mds v0.27.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect github.com/dunglas/httpsfv v1.1.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/filecoin-project/go-clock v0.1.0 // indirect github.com/flynn/noise v1.1.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-zeromq/goczmq/v4 v4.2.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/google/gopacket v1.1.19 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/huin/goupnp v1.3.0 // indirect github.com/iancoleman/strcase v0.3.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/ipfs/go-cid v0.6.1 // indirect github.com/ipfs/go-datastore v0.9.1 // indirect github.com/ipfs/go-log/v2 v2.9.1 // indirect github.com/ipld/go-ipld-prime v0.22.0 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/koron/go-ssdp v0.1.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect github.com/libp2p/go-cidranger v1.1.0 // indirect github.com/libp2p/go-flow-metrics v0.3.0 // indirect github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect github.com/libp2p/go-libp2p-kbucket v0.8.0 // indirect github.com/libp2p/go-libp2p-record v0.3.1 // indirect github.com/libp2p/go-libp2p-routing-helpers v0.7.5 // indirect github.com/libp2p/go-msgio v0.3.0 // indirect github.com/libp2p/go-netroute v0.4.0 // indirect github.com/libp2p/go-reuseport v0.4.0 // indirect github.com/libp2p/go-yamux/v5 v5.1.0 // indirect github.com/libp2p/zeroconf/v2 v2.2.0 // indirect github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.21 // indirect github.com/mattn/go-runewidth v0.0.23 // indirect github.com/mattn/go-tty v0.0.7 // indirect github.com/miekg/dns v1.1.72 // indirect github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b // indirect github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc // indirect github.com/minio/sha256-simd v1.0.1 // indirect github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mr-tron/base58 v1.3.0 // indirect github.com/multiformats/go-base32 v0.1.0 // indirect github.com/multiformats/go-base36 v0.2.0 // indirect github.com/multiformats/go-multiaddr-dns v0.5.0 // indirect github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect github.com/multiformats/go-multibase v0.3.0 // indirect github.com/multiformats/go-multicodec v0.10.0 // indirect github.com/multiformats/go-multihash v0.2.3 // indirect github.com/multiformats/go-multistream v0.6.1 // indirect github.com/multiformats/go-varint v0.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pion/datachannel v1.6.0 // indirect github.com/pion/dtls/v3 v3.1.2 // indirect github.com/pion/ice/v4 v4.2.3 // indirect github.com/pion/interceptor v0.1.44 // indirect github.com/pion/logging v0.2.4 // indirect github.com/pion/mdns/v2 v2.1.0 // indirect github.com/pion/randutil v0.1.0 // indirect github.com/pion/rtcp v1.2.16 // indirect github.com/pion/rtp v1.10.1 // indirect github.com/pion/sctp v1.9.4 // indirect github.com/pion/sdp/v3 v3.0.18 // indirect github.com/pion/srtp/v3 v3.0.10 // indirect github.com/pion/stun/v3 v3.1.2 // indirect github.com/pion/transport/v4 v4.0.1 // indirect github.com/pion/turn/v4 v4.1.4 // indirect github.com/pion/webrtc/v4 v4.2.11 // indirect github.com/pkg/term v1.2.0-beta.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/polydawn/refmt v0.89.1-0.20231129105047-37766d95467a // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect github.com/prometheus/procfs v0.20.1 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/quic-go/webtransport-go v0.10.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirect github.com/wlynxg/anet v0.0.5 // indirect github.com/x448/float16 v0.8.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel v1.43.0 // indirect go.opentelemetry.io/otel/metric v1.43.0 // indirect go.opentelemetry.io/otel/trace v1.43.0 // indirect go.uber.org/dig v1.19.0 // indirect go.uber.org/fx v1.24.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.1 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect golang.org/x/mod v0.35.0 // indirect golang.org/x/net v0.53.0 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/sys v0.43.0 // indirect golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa // indirect golang.org/x/text v0.36.0 // indirect golang.org/x/time v0.15.0 // indirect golang.org/x/tools v0.44.0 // indirect gonum.org/v1/gonum v0.17.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260406210006-6f92a3bedf2d // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d // indirect gopkg.in/yaml.v3 v3.0.1 // indirect lukechampine.com/blake3 v1.4.1 // indirect modernc.org/libc v1.72.0 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect modernc.org/sqlite v1.48.2 // indirect ) ================================================ FILE: go.sum ================================================ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 h1:JA0fFr+kxpqTdxR9LOBiTWpGNchqmkcsgmdeJZRclZ0= filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI= filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b h1:REI1FbdW71yO56Are4XAxD+OS/e+BQsB3gE4mZRQEXY= filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b/go.mod h1:9nnw1SlYHYuPSo/3wjQzNjSbeHlq2NsKo5iEtfJPWP0= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/NathanBaulch/protoc-gen-cobra v1.2.1 h1:BOqX9glwicbqDJDGndMnhHhx8psGTSjGdZzRDY1a7A8= github.com/NathanBaulch/protoc-gen-cobra v1.2.1/go.mod h1:ZLPLEPQgV3jP3a7IEp+xxYPk8tF4lhY9ViV0hn6K3iA= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/beevik/ntp v1.5.0 h1:y+uj/JjNwlY2JahivxYvtmv4ehfi3h74fAuABB9ZSM4= github.com/beevik/ntp v1.5.0/go.mod h1:mJEhBrwT76w9D+IfOEGvuzyuudiW9E52U2BaTrMOYow= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bits-and-blooms/bitset v1.24.4 h1:95H15Og1clikBrKr/DuzMXkQzECs1M6hhoGXLwLQOZE= github.com/bits-and-blooms/bitset v1.24.4/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI= github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY= github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 h1:oe6fCvaEpkhyW3qAicT0TnGtyht/UrgvOwMcEgLb7Aw= github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3/go.mod h1:qdP0gaj0QtgX2RUZhnlVrceJ+Qln8aSlDyJwelLLFeM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM= github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/consensys/gnark-crypto v0.20.1 h1:PXDUBvk8AzhvWowHLWBEAfUQcV1/aZgWIqD6eMpXmDg= github.com/consensys/gnark-crypto v0.20.1/go.mod h1:RBWrSgy+IDbGR69RRV313th3M/aZU1ubk2om+qHuTSc= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creachadair/jrpc2 v1.3.5 h1:onJko+1u6xoiRph3xwWmfNISR91teCRhbJwSyS9Svzo= github.com/creachadair/jrpc2 v1.3.5/go.mod h1:YXDmS53AavsiytbAwskrczJPcVHvKC9GoyWzwfSQXoE= github.com/creachadair/mds v0.27.0 h1:3nRi2FoC8l3mE4AxvNpubEdaiWaZVqfLcAPubbXxoek= github.com/creachadair/mds v0.27.0/go.mod h1:dMBTCSy3iS3dwh4Rb1zxeZz2d7K8+N24GCTsayWtQRI= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c h1:pFUpOrbxDR6AkioZ1ySsx5yxlDQZ8stG2b88gTPxgJU= github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c/go.mod h1:6UhI8N9EjYm1c2odKpFpAYeR8dsBeM7PtzQhRgxRr9U= github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8= github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= github.com/dunglas/httpsfv v1.1.0 h1:Jw76nAyKWKZKFrpMMcL76y35tOpYHqQPzHQiwDvpe54= github.com/dunglas/httpsfv v1.1.0/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/ezex-io/gopkg/pipeline v0.0.0-20260127151556-579a32f19aa7 h1:zUmRjqSmASCO4F/4oS5sUFbEh1yjhgmgRHUZLKUtbnQ= github.com/ezex-io/gopkg/pipeline v0.0.0-20260127151556-579a32f19aa7/go.mod h1:eDWtiQtQ6pAdxKSttVQbk98KXxdeFWzxaZcWKWODbX0= github.com/ezex-io/gopkg/scheduler v0.0.0-20260127151556-579a32f19aa7 h1:hujO8ZKXb+VwDgnSSa4ngoT6WNwkd9yLF9idzVLKA4Y= github.com/ezex-io/gopkg/scheduler v0.0.0-20260127151556-579a32f19aa7/go.mod h1:I5PLJTun10b6UvzR2s2oA2++QDsQQbUVVbKQDABLkSI= github.com/ezex-io/gopkg/signal v0.0.0-20260127151556-579a32f19aa7 h1:tFeQmqXM0SqiWSGz0kvbS3FfIdZusxZoa2Ggeucumww= github.com/ezex-io/gopkg/signal v0.0.0-20260127151556-579a32f19aa7/go.mod h1:nKAkGKaKCERbJZ1Pn9Jngi7prESr/YKfN6tCCaopZAU= github.com/ezex-io/gopkg/testsuite v0.0.0-20260127151556-579a32f19aa7 h1:51fXLznSPBGFjG2fc9emSXR9n5IM6X0ANIJy6SHNwtQ= github.com/ezex-io/gopkg/testsuite v0.0.0-20260127151556-579a32f19aa7/go.mod h1:UY5y7MLtFkTqRPJ8ExnHgXRfZtIryYVIS0JjrI13N5o= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/filecoin-project/go-clock v0.1.0 h1:SFbYIM75M8NnFm1yMHhN9Ahy3W5bEZV9gd6MPfXbKVU= github.com/filecoin-project/go-clock v0.1.0/go.mod h1:4uB/O4PvOjlx1VCMdZ9MyDZXRm//gkj1ELEbxfI1AZs= github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg= github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/glebarez/go-sqlite v1.22.1-0.20250214171204-e6de9fc0c320 h1:2swBMoqhMMr8Vv5m/XKEEyrTQ218LAFNUNL0pblvWYs= github.com/glebarez/go-sqlite v1.22.1-0.20250214171204-e6de9fc0c320/go.mod h1:cxXqFxpt08h2E1w0vYo4czkaAEwsdqHqtuY4SdVZMH4= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0= github.com/go-zeromq/goczmq/v4 v4.2.2 h1:HAJN+i+3NW55ijMJJhk7oWxHKXgAuSBkoFfvr8bYj4U= github.com/go-zeromq/goczmq/v4 v4.2.2/go.mod h1:Sm/lxrfxP/Oxqs0tnHD6WAhwkWrx+S+1MRrKzcxoaYE= github.com/go-zeromq/zmq4 v0.17.0 h1:r12/XdqPeRbuaF4C3QZJeWCt7a5vpJbslDH1rTXF+Kc= github.com/go-zeromq/zmq4 v0.17.0/go.mod h1:EQxjJD92qKnrsVMzAnx62giD6uJIPi1dMGZ781iCDtY= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw= github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8= github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gotk3/gotk3 v0.6.2 h1:sx/PjaKfKULJPTPq8p2kn2ZbcNFxpOJqi4VLzMbEOO8= github.com/gotk3/gotk3 v0.6.2/go.mod h1:/hqFpkNa9T3JgNAE2fLvCdov7c5bw//FHNZrZ3Uv9/Q= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs= github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inancgumus/screen v0.0.0-20190314163918-06e984b86ed3 h1:fO9A67/izFYFYky7l1pDP5Dr0BTCRkaQJUG6Jm5ehsk= github.com/inancgumus/screen v0.0.0-20190314163918-06e984b86ed3/go.mod h1:Ey4uAp+LvIl+s5jRbOHLcZpUDnkjLBROl15fZLwPlTM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/ipfs/boxo v0.38.0 h1:Kt/swuNXAtVXs7EP6KEjB5+2lo5/tTrvWzjakQ8IiOo= github.com/ipfs/boxo v0.38.0/go.mod h1:A6DRpImSXihx6MiEHOeBjXqleDqK5JX3yWDxM0WygPo= github.com/ipfs/go-block-format v0.2.3 h1:mpCuDaNXJ4wrBJLrtEaGFGXkferrw5eqVvzaHhtFKQk= github.com/ipfs/go-block-format v0.2.3/go.mod h1:WJaQmPAKhD3LspLixqlqNFxiZ3BZ3xgqxxoSR/76pnA= github.com/ipfs/go-cid v0.6.1 h1:T5TnNb08+ueovG76Z5gx1L4Y7QOaGTXHg1F6raWFxIc= github.com/ipfs/go-cid v0.6.1/go.mod h1:zrY0SwOhjrrIdfPQ/kf+k1sXyJ0QE7cMxfCployLBs0= github.com/ipfs/go-datastore v0.9.1 h1:67Po2epre/o0UxrmkzdS9ZTe2GFGODgTd2odx8Wh6Yo= github.com/ipfs/go-datastore v0.9.1/go.mod h1:zi07Nvrpq1bQwSkEnx3bfjz+SQZbdbWyCNvyxMh9pN0= github.com/ipfs/go-detect-race v0.0.1 h1:qX/xay2W3E4Q1U7d9lNs1sU9nvguX0a7319XbyQ6cOk= github.com/ipfs/go-detect-race v0.0.1/go.mod h1:8BNT7shDZPo99Q74BpGMK+4D8Mn4j46UU0LZ723meps= github.com/ipfs/go-log/v2 v2.9.1 h1:3JXwHWU31dsCpvQ+7asz6/QsFJHqFr4gLgQ0FWteujk= github.com/ipfs/go-log/v2 v2.9.1/go.mod h1:evFx7sBiohUN3AG12mXlZBw5hacBQld3ZPHrowlJYoo= github.com/ipfs/go-test v0.2.3 h1:Z/jXNAReQFtCYyn7bsv/ZqUwS6E7iIcSpJ2CuzCvnrc= github.com/ipfs/go-test v0.2.3/go.mod h1:QW8vSKkwYvWFwIZQLGQXdkt9Ud76eQXRQ9Ao2H+cA1o= github.com/ipld/go-ipld-prime v0.22.0 h1:YJhDhjEOvOYaqshd3b4atIWUoRg/rKrgmwCyUHwlbuY= github.com/ipld/go-ipld-prime v0.22.0/go.mod h1:ol7vKxOOVgEh0iAPuiDalM+0gScXVMA5ZZa4DVrTnEA= github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus= github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/jbenet/go-temp-err-catcher v0.1.0 h1:zpb3ZH6wIE8Shj2sKS+khgRvf7T7RABoLk/+KKHggpk= github.com/jbenet/go-temp-err-catcher v0.1.0/go.mod h1:0kJRvmDZXNMIiJirNPEYfhpPwbGVtZVWC34vc5WLsDk= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213 h1:qGQQKEcAR99REcMpsXCp3lJ03zYT1PkRd3kQGPn9GVg= github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw= github.com/kilic/bls12-381 v0.1.1-0.20220929213557-ca162e8a70f4 h1:xWK4TZ4bRL05WQUU/3x6TG1l+IYAqdXpAeSLt/zZJc4= github.com/kilic/bls12-381 v0.1.1-0.20220929213557-ca162e8a70f4/go.mod h1:tlkavyke+Ac7h8R3gZIjI5LKBcvMlSWnXNMgT3vZXo8= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/koron/go-ssdp v0.1.0 h1:ckl5x5H6qSNFmi+wCuROvvGUu2FQnMbQrU95IHCcv3Y= github.com/koron/go-ssdp v0.1.0/go.mod h1:GltaDBjtK1kemZOusWYLGotV0kBeEf59Bp0wtSB0uyU= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzWu4= github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c= github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/libp2p/go-cidranger v1.1.0 h1:ewPN8EZ0dd1LSnrtuwd4709PXVcITVeuwbag38yPW7c= github.com/libp2p/go-cidranger v1.1.0/go.mod h1:KWZTfSr+r9qEo9OkI9/SIEeAtw+NNoU0dXIXt15Okic= github.com/libp2p/go-flow-metrics v0.3.0 h1:q31zcHUvHnwDO0SHaukewPYgwOBSxtt830uJtUx6784= github.com/libp2p/go-flow-metrics v0.3.0/go.mod h1:nuhlreIwEguM1IvHAew3ij7A8BMlyHQJ279ao24eZZo= github.com/libp2p/go-libp2p v0.48.0 h1:h2BrLAgrj7X8bEN05K7qmrjpNHYA+6tnsGRdprjTnvo= github.com/libp2p/go-libp2p v0.48.0/go.mod h1:Q1fBZNdmC2Hf82husCTfkKJVfHm2we5zk+NWmOGEmWk= github.com/libp2p/go-libp2p-asn-util v0.4.1 h1:xqL7++IKD9TBFMgnLPZR6/6iYhawHKHl950SO9L6n94= github.com/libp2p/go-libp2p-asn-util v0.4.1/go.mod h1:d/NI6XZ9qxw67b4e+NgpQexCIiFYJjErASrYW4PFDN8= github.com/libp2p/go-libp2p-kad-dht v0.39.0 h1:mww38eBYiUvdsu+Xl/GLlBC0Aa8M+5HAwvafkFOygAM= github.com/libp2p/go-libp2p-kad-dht v0.39.0/go.mod h1:Po2JugFEkDq9Vig/JXtc153ntOi0q58o4j7IuITCOVs= github.com/libp2p/go-libp2p-kbucket v0.8.0 h1:QAK7RzKJpYe+EuSEATAaaHYMYLkPDGC18m9jxPLnU8s= github.com/libp2p/go-libp2p-kbucket v0.8.0/go.mod h1:JMlxqcEyKwO6ox716eyC0hmiduSWZZl6JY93mGaaqc4= github.com/libp2p/go-libp2p-pubsub v0.15.0 h1:cG7Cng2BT82WttmPFMi50gDNV+58K626m/wR00vGL1o= github.com/libp2p/go-libp2p-pubsub v0.15.0/go.mod h1:lr4oE8bFgQaifRcoc2uWhWWiK6tPdOEKpUuR408GFN4= github.com/libp2p/go-libp2p-record v0.3.1 h1:cly48Xi5GjNw5Wq+7gmjfBiG9HCzQVkiZOUZ8kUl+Fg= github.com/libp2p/go-libp2p-record v0.3.1/go.mod h1:T8itUkLcWQLCYMqtX7Th6r7SexyUJpIyPgks757td/E= github.com/libp2p/go-libp2p-routing-helpers v0.7.5 h1:HdwZj9NKovMx0vqq6YNPTh6aaNzey5zHD7HeLJtq6fI= github.com/libp2p/go-libp2p-routing-helpers v0.7.5/go.mod h1:3YaxrwP0OBPDD7my3D0KxfR89FlcX/IEbxDEDfAmj98= github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA= github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg= github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0= github.com/libp2p/go-msgio v0.3.0/go.mod h1:nyRM819GmVaF9LX3l03RMh10QdOroF++NBbxAb0mmDM= github.com/libp2p/go-netroute v0.4.0 h1:sZZx9hyANYUx9PZyqcgE/E1GUG3iEtTZHUEvdtXT7/Q= github.com/libp2p/go-netroute v0.4.0/go.mod h1:Nkd5ShYgSMS5MUKy/MU2T57xFoOKvvLR92Lic48LEyA= github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQscQm2s= github.com/libp2p/go-reuseport v0.4.0/go.mod h1:ZtI03j/wO5hZVDFo2jKywN6bYKWLOy8Se6DrI2E1cLU= github.com/libp2p/go-yamux/v5 v5.1.0 h1:8Qlxj4E9JGJAQVW6+uj2o7mqkqsIVlSUGmTWhlXzoHE= github.com/libp2p/go-yamux/v5 v5.1.0/go.mod h1:tgIQ07ObtRR/I0IWsFOyQIL9/dR5UXgc2s8xKmNZv1o= github.com/libp2p/zeroconf/v2 v2.2.0 h1:Cup06Jv6u81HLhIj1KasuNM/RHHrJ8T7wOTS4+Tv53Q= github.com/libp2p/zeroconf/v2 v2.2.0/go.mod h1:fuJqLnUwZTshS3U/bMRJ3+ow/v9oid1n0DmyYyNO1Xs= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= github.com/marcopolo/simnet v0.0.4 h1:50Kx4hS9kFGSRIbrt9xUS3NJX33EyPqHVmpXvaKLqrY= github.com/marcopolo/simnet v0.0.4/go.mod h1:tfQF1u2DmaB6WHODMtQaLtClEf3a296CKQLq5gAsIS0= github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd h1:br0buuQ854V8u83wA0rVZ8ttrq5CpaPZdvrK0LP2lOk= github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd/go.mod h1:QuCEs1Nt24+FYQEqAAncTDPJIuGs+LxK1MCiFL25pMU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs= github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw= github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0= github.com/mattn/go-tty v0.0.7 h1:KJ486B6qI8+wBO7kQxYgmmEFDaFEE96JMBQ7h400N8Q= github.com/mattn/go-tty v0.0.7/go.mod h1:f2i5ZOvXBU/tCABmLmOfzLz9azMo5wdAaElRNnJKr+k= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4= github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c h1:bzE/A84HN25pxAuk9Eej1Kz9OUelF97nAc82bDquQI8= github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c/go.mod h1:0SQS9kMwD2VsyFEB++InYyBJroV/FRmBgcydeSUcJms= github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b h1:z78hV3sbSMAUoyUMM0I83AUIT6Hu17AWfgjzIbtrYFc= github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b/go.mod h1:lxPUiZwKoFL8DUUmalo2yJJUCxbPKtm8OKfqr2/FTNU= github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc h1:PTfri+PuQmWDqERdnNMiD9ZejrlswWrCpBEZgWOiTrc= github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc/go.mod h1:cGKTAVKx4SxOuR/czcZ/E2RSJ3sfHs8FpHhQ5CWMf9s= github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ= github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ= github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mr-tron/base58 v1.1.2/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= github.com/mr-tron/base58 v1.3.0 h1:K6Y13R2h+dku0wOqKtecgRnBUBPrZzLZy5aIj8lCcJI= github.com/mr-tron/base58 v1.3.0/go.mod h1:2BuubE67DCSWwVfx37JWNG8emOC0sHEU4/HpcYgCLX8= github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aGkbLYxPE= github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYgtWibDcT0rExnbI= github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0= github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4= github.com/multiformats/go-multiaddr v0.1.1/go.mod h1:aMKBKNEYmzmDmxfX88/vz+J5IU55txyt0p4aiWVohjo= github.com/multiformats/go-multiaddr v0.16.1 h1:fgJ0Pitow+wWXzN9do+1b8Pyjmo8m5WhGfzpL82MpCw= github.com/multiformats/go-multiaddr v0.16.1/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0= github.com/multiformats/go-multiaddr-dns v0.5.0 h1:p/FTyHKX0nl59f+S+dEUe8HRK+i5Ow/QHMw8Nh3gPCo= github.com/multiformats/go-multiaddr-dns v0.5.0/go.mod h1:yJ349b8TPIAANUyuOzn1oz9o22tV9f+06L+cCeMxC14= github.com/multiformats/go-multiaddr-fmt v0.1.0 h1:WLEFClPycPkp4fnIzoFoV9FVd49/eQsuaL3/CWe167E= github.com/multiformats/go-multiaddr-fmt v0.1.0/go.mod h1:hGtDIW4PU4BqJ50gW2quDuPVjyWNZxToGUh/HwTZYJo= github.com/multiformats/go-multibase v0.3.0 h1:8helZD2+4Db7NNWFiktk2NePbF0boolBe6bDQvM4r68= github.com/multiformats/go-multibase v0.3.0/go.mod h1:MoBLQPCkRTOL3eveIPO81860j2AQY8JwcnNlRkGRUfI= github.com/multiformats/go-multicodec v0.10.0 h1:UpP223cig/Cx8J76jWt91njpK3GTAO1w02sdcjZDSuc= github.com/multiformats/go-multicodec v0.10.0/go.mod h1:wg88pM+s2kZJEQfRCKBNU+g32F5aWBEjyFHXvZLTcLI= github.com/multiformats/go-multihash v0.0.8/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew= github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U= github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM= github.com/multiformats/go-multistream v0.6.1 h1:4aoX5v6T+yWmc2raBHsTvzmFhOI8WVOer28DeBBEYdQ= github.com/multiformats/go-multistream v0.6.1/go.mod h1:ksQf6kqHAb6zIsyw7Zm+gAuVo57Qbq84E27YlYqavqw= github.com/multiformats/go-varint v0.1.0 h1:i2wqFp4sdl3IcIxfAonHQV9qU5OsZ4Ts9IOoETFs5dI= github.com/multiformats/go-varint v0.1.0/go.mod h1:5KVAVXegtfmNQQm/lCY+ATvDzvJJhSkUlGQV9wgObdI= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= github.com/neelance/sourcemap v0.0.0-20200213170602-2833bce08e4c/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/pacviewer/jrpc-gateway v0.6.0 h1:h4btj93+Fyaq74rIz9oODTVE1GiuC/aswKzt4u4exrg= github.com/pacviewer/jrpc-gateway v0.6.0/go.mod h1:e5x4eyPeACtG4nP9oj3uRYDVOiODh55YdP5iB045WQ0= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y= github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM= github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pion/datachannel v1.6.0 h1:XecBlj+cvsxhAMZWFfFcPyUaDZtd7IJvrXqlXD/53i0= github.com/pion/datachannel v1.6.0/go.mod h1:ur+wzYF8mWdC+Mkis5Thosk+u/VOL287apDNEbFpsIk= github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc= github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo= github.com/pion/ice/v4 v4.2.3 h1:1QUD3JA+0MUoXk5Bl4pbcuSyUlxRDiTQDPr29PnIPCA= github.com/pion/ice/v4 v4.2.3/go.mod h1:ELQIH5Xmcs/nsJnKyzLJWij8v9Z/xHOzdPTfpFZMh2o= github.com/pion/interceptor v0.1.44 h1:sNlZwM8dWXU9JQAkJh8xrarC0Etn8Oolcniukmuy0/I= github.com/pion/interceptor v0.1.44/go.mod h1:4atVlBkcgXuUP+ykQF0qOCGU2j7pQzX2ofvPRFsY5RY= github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8= github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so= github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY= github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A= github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo= github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo= github.com/pion/rtp v1.10.1 h1:xP1prZcCTUuhO2c83XtxyOHJteISg6o8iPsE2acaMtA= github.com/pion/rtp v1.10.1/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM= github.com/pion/sctp v1.9.4 h1:cMxEu0F5tbP4qH07bKf1Zjf4rUih9LIo0qQt424e258= github.com/pion/sctp v1.9.4/go.mod h1:N20Dq6LY+JvJDAh9VVh1JELngb2rQ8dPgds5yBWiPgw= github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI= github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8= github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ= github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M= github.com/pion/stun/v3 v3.1.2 h1:86IhD8wFn6IDW4b1/0QzoQS+f5PeA8OHHRn8UZW5ErY= github.com/pion/stun/v3 v3.1.2/go.mod h1:H7gDic7nNwlUL05pbs6T1dtaBehh/KjupxfWw3ZI7cA= github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM= github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ= github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o= github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM= github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ= github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ= github.com/pion/webrtc/v4 v4.2.11 h1:QUX1QZKlNIn4O7U5JxLPGP0sV5RTncZkzu9SPR3jVNU= github.com/pion/webrtc/v4 v4.2.11/go.mod h1:s/rAiyy77GyRFrZMx+Ls6aua26dIBPudH8/ZHYbIRWY= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw= github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/polydawn/refmt v0.89.1-0.20231129105047-37766d95467a h1:cgqrm0F3zwf9IPzca7xN4w+Zy6MC9ZkPvAC8QEWa/iQ= github.com/polydawn/refmt v0.89.1-0.20231129105047-37766d95467a/go.mod h1:ocZfO/tLSHqfScRDNTJbAJR1by4D1lewauX9OwTaPuY= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/quic-go/webtransport-go v0.10.0 h1:LqXXPOXuETY5Xe8ITdGisBzTYmUOy5eSj+9n4hLTjHI= github.com/quic-go/webtransport-go v0.10.0/go.mod h1:LeGIXr5BQKE3UsynwVBeQrU1TPrbh73MGoC6jd+V7ow= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/zerolog v1.35.0 h1:VD0ykx7HMiMJytqINBsKcbLS+BJ4WYjz+05us+LRTdI= github.com/rs/zerolog v1.35.0/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/schollz/progressbar/v3 v3.19.0 h1:Ea18xuIRQXLAUidVDox3AbwfUhD0/1IvohyTutOIFoc= github.com/schollz/progressbar/v3 v3.19.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shurcooL/go v0.0.0-20200502201357-93f07166e636/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY= github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0 h1:GDDkbFiaK8jsSDJfjId/PEGEShv6ugrt4kYsC5UIDaQ= github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw= github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 h1:EKhdznlJHPMoKr0XTrX+IlJs1LH3lyx2nfr1dOlZ79k= github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1/go.mod h1:8UvriyWtv5Q5EOgjHaSseUEdkQfvwFv1I/In/O2M9gc= github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4= go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE= go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg= go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200602180216-279210d13fed/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210423184538-5f58ad60dda6/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210426080607-c94f62235c83/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa h1:efT73AJZfAAUV7SOip6pWGkwJDzIGiKBZGVzHYa+ve4= golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY= golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= google.golang.org/genproto/googleapis/api v0.0.0-20260406210006-6f92a3bedf2d h1:/aDRtSZJjyLQzm75d+a1wOJaqyKBMvIAfeQmoa3ORiI= google.golang.org/genproto/googleapis/api v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:etfGUgejTiadZAUaEP14NP97xi1RGeawqkjDARA/UOs= google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d h1:wT2n40TBqFY6wiwazVK9/iTWbsQrgk5ZfCSVFLO9LQA= google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM= google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg= lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo= modernc.org/cc/v4 v4.27.3 h1:uNCgn37E5U09mTv1XgskEVUJ8ADKpmFMPxzGJ0TSo+U= modernc.org/cc/v4 v4.27.3/go.mod h1:3YjcbCqhoTTHPycJDRl2WZKKFj0nwcOIPBfEZK0Hdk8= modernc.org/ccgo/v4 v4.32.4 h1:L5OB8rpEX4ZsXEQwGozRfJyJSFHbbNVOoQ59DU9/KuU= modernc.org/ccgo/v4 v4.32.4/go.mod h1:lY7f+fiTDHfcv6YlRgSkxYfhs+UvOEEzj49jAn2TOx0= modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo= modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= modernc.org/libc v1.72.0 h1:IEu559v9a0XWjw0DPoVKtXpO2qt5NVLAnFaBbjq+n8c= modernc.org/libc v1.72.0/go.mod h1:tTU8DL8A+XLVkEY3x5E/tO7s2Q/q42EtnNWda/L5QhQ= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= modernc.org/sqlite v1.48.2 h1:5CnW4uP8joZtA0LedVqLbZV5GD7F/0x91AXeSyjoh5c= modernc.org/sqlite v1.48.2/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig= modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= ================================================ FILE: network/config.go ================================================ package network import ( "fmt" "time" lp2pcore "github.com/libp2p/go-libp2p/core" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util" ) // Config defines parameters for the network module. type Config struct { NetworkKey string `toml:"network_key"` PublicAddrString string `toml:"public_addr"` ListenAddrStrings []string `toml:"listen_addrs"` BootstrapAddrStrings []string `toml:"bootstrap_addrs"` MaxConns int `toml:"max_connections"` EnableUDP bool `toml:"enable_udp"` EnableNATService bool `toml:"enable_nat_service"` EnableUPnP bool `toml:"enable_upnp"` EnableRelay bool `toml:"enable_relay"` EnableRelayService bool `toml:"enable_relay_service"` EnableMdns bool `toml:"enable_mdns"` EnableMetrics bool `toml:"enable_metrics"` ForcePrivateNetwork bool `toml:"force_private_network"` // Private configs NetworkName string `toml:"-"` DefaultPort int `toml:"-"` DefaultBootstrapAddrStrings []string `toml:"-"` IsBootstrapper bool `toml:"-"` PeerStorePath string `toml:"-"` StreamTimeout time.Duration `toml:"-"` CheckConnectivityInterval time.Duration `toml:"-"` MaxGossipMessageSize int `toml:"-"` MaxStreamMessageSize int `toml:"-"` } func DefaultConfig() *Config { return &Config{ NetworkKey: "network_key", PublicAddrString: "", ListenAddrStrings: []string{}, BootstrapAddrStrings: []string{}, MaxConns: 64, EnableUDP: false, EnableNATService: false, EnableUPnP: false, EnableRelay: true, EnableRelayService: false, EnableMdns: false, EnableMetrics: false, ForcePrivateNetwork: false, DefaultPort: 0, IsBootstrapper: false, PeerStorePath: "peers.json", StreamTimeout: 20 * time.Second, CheckConnectivityInterval: 60 * time.Second, MaxGossipMessageSize: 1 * 1024 * 1024, // 1 MB MaxStreamMessageSize: 8 * 1024 * 1024, // 8 MB } } func validateMultiAddr(addrs ...string) error { _, err := MakeMultiAddrs(addrs) if err != nil { return ConfigError{ Reason: fmt.Sprintf("address is not valid: %s", err.Error()), } } return err } func validateAddrInfo(addrs ...string) error { _, err := MakeAddrInfos(addrs) if err != nil { return ConfigError{ Reason: fmt.Sprintf("address is not valid: %s", err.Error()), } } return nil } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { if conf.PublicAddrString != "" { if err := validateMultiAddr(conf.PublicAddrString); err != nil { return err } } if err := validateMultiAddr(conf.ListenAddrStrings...); err != nil { return err } if err := validateAddrInfo(conf.DefaultBootstrapAddrStrings...); err != nil { return err } if conf.EnableRelay && conf.EnableRelayService { return ConfigError{ Reason: "both the relay and relay service cannot be active at the same time", } } if conf.MaxConns < 16 { return ConfigError{ Reason: "maximum connection should be greater than 16", } } return validateAddrInfo(conf.BootstrapAddrStrings...) } func (conf *Config) PublicAddr() multiaddr.Multiaddr { if conf.PublicAddrString != "" { addr, _ := multiaddr.NewMultiaddr(conf.PublicAddrString) return addr } return nil } func (conf *Config) ListenAddrs() []multiaddr.Multiaddr { listenAddrs := conf.ListenAddrStrings if len(listenAddrs) == 0 { listenAddrs = []string{ fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", conf.DefaultPort), fmt.Sprintf("/ip4/0.0.0.0/udp/%d/quic-v1", conf.DefaultPort), fmt.Sprintf("/ip6/::/tcp/%d", conf.DefaultPort), fmt.Sprintf("/ip6/::/udp/%d/quic-v1", conf.DefaultPort), } } addrs, _ := MakeMultiAddrs(listenAddrs) return addrs } func (conf *Config) BootstrapAddrInfos() []lp2ppeer.AddrInfo { addrs := util.Merge(conf.DefaultBootstrapAddrStrings, conf.BootstrapAddrStrings) addrInfos, _ := MakeAddrInfos(addrs) return addrInfos } func (conf *Config) CheckIsBootstrapper(pid lp2pcore.PeerID) { addrInfos := conf.BootstrapAddrInfos() for _, ai := range addrInfos { if ai.ID == pid { conf.IsBootstrapper = true break } } } func (conf *Config) MinConns() int { return (conf.MaxConns / 4) - 2 } ================================================ FILE: network/config_test.go ================================================ package network import ( "testing" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConfigBasicCheck(t *testing.T) { tests := []struct { name string expectedErr error updateFn func(c *Config) }{ { name: "Empty ListenAddrStrings", expectedErr: ConfigError{ Reason: "address is not valid: failed to parse multiaddr \"\": empty multiaddr", }, updateFn: func(c *Config) { c.ListenAddrStrings = []string{""} }, }, { name: "Both Relay and Relay Service be true", expectedErr: ConfigError{ Reason: "both the relay and relay service cannot be active at the same time", }, updateFn: func(c *Config) { c.EnableRelay = true c.EnableRelayService = true }, }, { name: "Invalid ListenAddrStrings", expectedErr: ConfigError{ Reason: "address is not valid: failed to parse multiaddr \"127.0.0.1\": must begin with /", }, updateFn: func(c *Config) { c.ListenAddrStrings = []string{"127.0.0.1"} }, }, { name: "Invalid ListenAddrStrings (No port)", expectedErr: ConfigError{ Reason: "address is not valid: failed to parse multiaddr \"/ip4\": unexpected end of multiaddr", }, updateFn: func(c *Config) { c.ListenAddrStrings = []string{"/ip4"} }, }, { name: "Invalid Public Address", expectedErr: ConfigError{ Reason: "address is not valid: failed to parse multiaddr \"/ip4\": unexpected end of multiaddr", }, updateFn: func(c *Config) { c.PublicAddrString = "/ip4" }, }, { name: "Invalid DefaultBootstrapAddrStrings", expectedErr: ConfigError{ Reason: "address is not valid: invalid p2p multiaddr", }, updateFn: func(c *Config) { c.DefaultBootstrapAddrStrings = []string{"/ip4/127.0.0.1/"} }, }, { name: "Invalid BootstrapAddrStrings", expectedErr: ConfigError{ Reason: "address is not valid: invalid p2p multiaddr", }, updateFn: func(c *Config) { c.BootstrapAddrStrings = []string{"/ip4/127.0.0.1/"} }, }, { name: "Low MaxConns", expectedErr: ConfigError{ Reason: "maximum connection should be greater than 16", }, updateFn: func(c *Config) { c.MaxConns = 8 }, }, { name: "Valid Public Address", updateFn: func(c *Config) { c.PublicAddrString = "/ip4/127.0.0.1/" }, }, { name: "Valid ListenAddrStrings", updateFn: func(c *Config) { c.ListenAddrStrings = []string{"/ip4/127.0.0.1"} }, }, { name: "Valid BootstrapAddrStrings", updateFn: func(c *Config) { c.BootstrapAddrStrings = []string{ "/ip4/127.0.0.1/p2p/12D3KooWQBpPV6NtZy1dvN2oF7dJdLoooRZfEmwtHiDUf42ArDjT", } }, }, { name: "DefaultConfig", updateFn: func(*Config) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() tt.updateFn(conf) if tt.expectedErr != nil { err := conf.BasicCheck() require.ErrorIs(t, err, tt.expectedErr, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } func TestIsBootstrapper(t *testing.T) { conf := DefaultConfig() conf.BootstrapAddrStrings = []string{"/ip4/127.0.0.1/p2p/12D3KooWQBpPV6NtZy1dvN2oF7dJdLoooRZfEmwtHiDUf42ArDjT"} conf.DefaultBootstrapAddrStrings = []string{"/ip4/127.0.0.2/p2p/12D3KooWBqutgDboACf1i1c9uN9BQg9xdREoeXYb2rvFHQU1QcAp"} pid1, _ := lp2ppeer.Decode("12D3KooWQQKidG8Nn6fLgxjryHFhRCfG9fUWU88yGSZNd59Kbqka") pid2, _ := lp2ppeer.Decode("12D3KooWQBpPV6NtZy1dvN2oF7dJdLoooRZfEmwtHiDUf42ArDjT") pid3, _ := lp2ppeer.Decode("12D3KooWBqutgDboACf1i1c9uN9BQg9xdREoeXYb2rvFHQU1QcAp") conf.CheckIsBootstrapper(pid1) assert.False(t, conf.IsBootstrapper) conf.CheckIsBootstrapper(pid2) assert.True(t, conf.IsBootstrapper) conf.CheckIsBootstrapper(pid3) assert.True(t, conf.IsBootstrapper) } func TestMinConns(t *testing.T) { tests := []struct { config Config expectedMin int }{ {Config{MaxConns: 16}, 2}, {Config{MaxConns: 30}, 5}, {Config{MaxConns: 128}, 30}, } for _, tt := range tests { resultMin := tt.config.MinConns() if resultMin != tt.expectedMin { t.Errorf("For MaxConns %d, "+ "MinConns() returned %d (expected %d)", tt.config.MaxConns, resultMin, tt.expectedMin) } } } func TestPublicAddr(t *testing.T) { conf1 := DefaultConfig() assert.Nil(t, conf1.PublicAddr()) conf2 := DefaultConfig() conf2.PublicAddrString = "/ip4/127.0.0.1/p2p/12D3KooWQBpPV6NtZy1dvN2oF7dJdLoooRZfEmwtHiDUf42ArDjT" assert.NotNil(t, conf2.PublicAddr()) } ================================================ FILE: network/dht.go ================================================ package network import ( "context" lp2pdht "github.com/libp2p/go-libp2p-kad-dht" lp2pcore "github.com/libp2p/go-libp2p/core" lp2phost "github.com/libp2p/go-libp2p/core/host" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util/logger" ) type dhtService struct { ctx context.Context host lp2phost.Host kademlia *lp2pdht.IpfsDHT logger *logger.SubLogger } func newDHTService(ctx context.Context, host lp2phost.Host, conf *Config, protocolID lp2pcore.ProtocolID, log *logger.SubLogger, ) *dhtService { // A dirty code in LibP2P!!! // prevent apply default bootstrap node of libp2p lp2pdht.DefaultBootstrapPeers = []multiaddr.Multiaddr{} mode := lp2pdht.ModeAuto if conf.IsBootstrapper { mode = lp2pdht.ModeServer } opts := []lp2pdht.Option{ lp2pdht.Mode(mode), lp2pdht.ProtocolPrefix(protocolID), lp2pdht.BootstrapPeers(conf.BootstrapAddrInfos()...), } kademlia, err := lp2pdht.New(ctx, host, opts...) if err != nil { panic(err) } return &dhtService{ ctx: ctx, host: host, kademlia: kademlia, logger: log, } } func (s *dhtService) Start() error { return s.kademlia.Bootstrap(s.ctx) } func (s *dhtService) Stop() { if err := s.kademlia.Close(); err != nil { s.logger.Error("unable to close Kademlia", "error", err) } } ================================================ FILE: network/errors.go ================================================ package network import "fmt" // ConfigError is returned when the config is not valid with a descriptive Reason message. type ConfigError struct { Reason string } func (e ConfigError) Error() string { return e.Reason } // NotSubscribedError is returned when the peer is not subscribed to a // specific topic. type NotSubscribedError struct { TopicID TopicID } func (e NotSubscribedError) Error() string { return fmt.Sprintf("not subscribed to the '%s' topic", e.TopicID.String()) } // InvalidTopicError is returned when the Pub-Sub topic is invalid. type InvalidTopicError struct { TopicID TopicID } func (e InvalidTopicError) Error() string { return fmt.Sprintf("invalid topic: '%s'", e.TopicID.String()) } // LibP2PError is returned when an underlying libp2p operation encounters an error. type LibP2PError struct { Err error } func (e LibP2PError) Error() string { return fmt.Sprintf("libp2p error: %s", e.Err.Error()) } ================================================ FILE: network/gater.go ================================================ package network import ( "sync" lp2pconnmgr "github.com/libp2p/go-libp2p/core/connmgr" lp2pcontrol "github.com/libp2p/go-libp2p/core/control" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util/logger" ) var _ lp2pconnmgr.ConnectionGater = &ConnectionGater{} type ConnectionGater struct { lk sync.RWMutex filters *multiaddr.Filters peerMgr *peerMgr acceptLimit int dialLimit int logger *logger.SubLogger } func NewConnectionGater(conf *Config, log *logger.SubLogger) (*ConnectionGater, error) { filters := multiaddr.NewFilters() if !conf.ForcePrivateNetwork { privateSubnets := PrivateSubnets() filters = SubnetsToFilters(privateSubnets, multiaddr.ActionDeny) } acceptLimit := conf.MaxConns dialLimit := conf.MaxConns / 4 log.Info("connection gater created", "listen", acceptLimit, "dial", dialLimit) return &ConnectionGater{ filters: filters, acceptLimit: acceptLimit, dialLimit: dialLimit, logger: log, }, nil } func (g *ConnectionGater) SetPeerManager(peerMgr *peerMgr) { g.lk.Lock() defer g.lk.Unlock() g.peerMgr = peerMgr } func (g *ConnectionGater) onDialLimit() bool { if g.peerMgr == nil { return false } return g.peerMgr.NumOutbound() > g.dialLimit } func (g *ConnectionGater) onAcceptLimit() bool { if g.peerMgr == nil { return false } return g.peerMgr.NumInbound() > g.acceptLimit } func (g *ConnectionGater) InterceptPeerDial(pid lp2ppeer.ID) bool { g.lk.RLock() defer g.lk.RUnlock() if g.onDialLimit() { g.logger.Debug("InterceptPeerDial rejected: many connections", "pid", pid, "outbound", g.peerMgr.NumOutbound()) return false } return true } func (g *ConnectionGater) InterceptAddrDial(pid lp2ppeer.ID, ma multiaddr.Multiaddr) bool { g.lk.RLock() defer g.lk.RUnlock() if g.onDialLimit() { g.logger.Debug("InterceptAddrDial rejected: many connections", "pid", pid, "ma", ma.String(), "outbound", g.peerMgr.NumOutbound()) return false } deny := g.filters.AddrBlocked(ma) if deny { g.logger.Debug("InterceptAddrDial rejected", "pid", pid, "ma", ma.String()) return false } return true } func (g *ConnectionGater) InterceptAccept(cma lp2pnetwork.ConnMultiaddrs) bool { g.lk.RLock() defer g.lk.RUnlock() if g.onAcceptLimit() { g.logger.Debug("InterceptAccept rejected: many connections", "inbound", g.peerMgr.NumInbound()) return false } deny := g.filters.AddrBlocked(cma.RemoteMultiaddr()) if deny { g.logger.Debug("InterceptAccept rejected") return false } return true } func (*ConnectionGater) InterceptSecured(_ lp2pnetwork.Direction, _ lp2ppeer.ID, _ lp2pnetwork.ConnMultiaddrs) bool { return true } func (*ConnectionGater) InterceptUpgraded(_ lp2pnetwork.Conn) (bool, lp2pcontrol.DisconnectReason) { return true, 0 } ================================================ FILE: network/gater_test.go ================================================ package network import ( "testing" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) // mockConnMultiaddrs is a mock implementation of the ConnMultiaddrs interface for testing. type mockConnMultiaddrs struct { remote multiaddr.Multiaddr } func (*mockConnMultiaddrs) LocalMultiaddr() multiaddr.Multiaddr { return nil } func (cma *mockConnMultiaddrs) RemoteMultiaddr() multiaddr.Multiaddr { return cma.remote } func TestAllowedConnections(t *testing.T) { ts := testsuite.NewTestSuite(t) conf := testConfig() net := makeTestNetwork(t, conf, nil) maPrivate := multiaddr.StringCast("/ip4/127.0.0.1/tcp/1234") maPublic := multiaddr.StringCast("/ip4/8.8.8.8/tcp/1234") cmaPrivate := &mockConnMultiaddrs{remote: maPrivate} cmaPublic := &mockConnMultiaddrs{remote: maPublic} pid := ts.RandPeerID() assert.True(t, net.connGater.InterceptPeerDial(pid)) assert.True(t, net.connGater.InterceptAddrDial(pid, maPrivate)) assert.True(t, net.connGater.InterceptAddrDial(pid, maPublic)) assert.True(t, net.connGater.InterceptAccept(cmaPrivate)) assert.True(t, net.connGater.InterceptAccept(cmaPublic)) } func TestDenyPrivate(t *testing.T) { ts := testsuite.NewTestSuite(t) conf := testConfig() conf.ForcePrivateNetwork = false net := makeTestNetwork(t, conf, nil) maPrivate := multiaddr.StringCast("/ip4/127.0.0.1/tcp/1234") maPublic := multiaddr.StringCast("/ip4/8.8.8.8/tcp/1234") cmaPrivate := &mockConnMultiaddrs{remote: maPrivate} cmaPublic := &mockConnMultiaddrs{remote: maPublic} pid := ts.RandPeerID() assert.True(t, net.connGater.InterceptPeerDial(pid)) assert.False(t, net.connGater.InterceptAddrDial(pid, maPrivate)) assert.True(t, net.connGater.InterceptAddrDial(pid, maPublic)) assert.False(t, net.connGater.InterceptAccept(cmaPrivate)) assert.True(t, net.connGater.InterceptAccept(cmaPublic)) } func TestMaxConnection(t *testing.T) { ts := testsuite.NewTestSuite(t) conf := testConfig() conf.MaxConns = 4 net := makeTestNetwork(t, conf, nil) maPrivate := multiaddr.StringCast("/ip4/127.0.0.1/tcp/1234") maPublic := multiaddr.StringCast("/ip4/8.8.8.8/tcp/1234") aMultiAddr := multiaddr.StringCast("/ip4/1.1.1.1/tcp/1234") cmaPrivate := &mockConnMultiaddrs{remote: maPrivate} cmaPublic := &mockConnMultiaddrs{remote: maPublic} pid := ts.RandPeerID() net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirOutbound) net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirInbound) net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirInbound) net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirInbound) net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirInbound) assert.True(t, net.connGater.InterceptPeerDial(pid)) assert.True(t, net.connGater.InterceptAddrDial(pid, maPrivate)) assert.True(t, net.connGater.InterceptAddrDial(pid, maPublic)) assert.True(t, net.connGater.InterceptAccept(cmaPrivate)) assert.True(t, net.connGater.InterceptAccept(cmaPublic)) net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirOutbound) assert.False(t, net.connGater.InterceptPeerDial(pid)) assert.False(t, net.connGater.InterceptAddrDial(pid, maPrivate)) assert.False(t, net.connGater.InterceptAddrDial(pid, maPublic)) assert.True(t, net.connGater.InterceptAccept(cmaPrivate)) assert.True(t, net.connGater.InterceptAccept(cmaPublic)) net.peerMgr.SetPeerConnected(ts.RandPeerID(), aMultiAddr, lp2pnetwork.DirInbound) assert.False(t, net.connGater.InterceptPeerDial(pid)) assert.False(t, net.connGater.InterceptAddrDial(pid, maPrivate)) assert.False(t, net.connGater.InterceptAddrDial(pid, maPublic)) assert.False(t, net.connGater.InterceptAccept(cmaPrivate)) assert.False(t, net.connGater.InterceptAccept(cmaPublic)) } ================================================ FILE: network/gossip.go ================================================ package network import ( "context" "fmt" "sync" "time" "github.com/ezex-io/gopkg/pipeline" lp2pps "github.com/libp2p/go-libp2p-pubsub" lp2pcore "github.com/libp2p/go-libp2p/core" lp2phost "github.com/libp2p/go-libp2p/core/host" "github.com/pactus-project/pactus/util/logger" ) type gossipService struct { ctx context.Context wg sync.WaitGroup host lp2phost.Host pubsub *lp2pps.PubSub topics []*lp2pps.Topic subs []*lp2pps.Subscription topicBlock *lp2pps.Topic topicTransaction *lp2pps.Topic topicConsensus *lp2pps.Topic networkName string networkPipe pipeline.Pipeline[Event] logger *logger.SubLogger } func newGossipService(ctx context.Context, host lp2phost.Host, conf *Config, networkPipe pipeline.Pipeline[Event], log *logger.SubLogger, ) *gossipService { opts := []lp2pps.Option{ lp2pps.WithFloodPublish(true), lp2pps.WithMessageSignaturePolicy(lp2pps.StrictNoSign), lp2pps.WithNoAuthor(), lp2pps.WithMessageIdFn(MessageIDFunc), lp2pps.WithSeenMessagesTTL(60 * time.Second), lp2pps.WithMaxMessageSize(conf.MaxGossipMessageSize), } if conf.IsBootstrapper { // enable Peer exchange on bootstrappers opts = append(opts, lp2pps.WithPeerExchange(true)) } gsParams := lp2pps.DefaultGossipSubParams() if conf.IsBootstrapper { gsParams.Dhi = 12 gsParams.D = 8 gsParams.Dlo = 6 gsParams.HeartbeatInterval = 700 * time.Millisecond } opts = append(opts, lp2pps.WithGossipSubParams(gsParams)) pubsub, err := lp2pps.NewGossipSub(ctx, host, opts...) if err != nil { log.Panic("unable to start Gossip service", "error", err) return nil } return &gossipService{ ctx: ctx, networkName: conf.NetworkName, host: host, pubsub: pubsub, wg: sync.WaitGroup{}, networkPipe: networkPipe, logger: log, } } // Broadcast broadcasts a message with the specified topic ID to the network. func (g *gossipService) Broadcast(msg []byte, topicID TopicID) error { g.logger.Debug("publishing new message", "topic", topicID) switch topicID { case TopicIDUnspecified: return InvalidTopicError{TopicID: topicID} case TopicIDBlock: if g.topicBlock == nil { return NotSubscribedError{TopicID: topicID} } return g.publish(msg, g.topicBlock) case TopicIDTransaction: if g.topicTransaction == nil { return NotSubscribedError{TopicID: topicID} } return g.publish(msg, g.topicTransaction) case TopicIDConsensus: if g.topicConsensus == nil { return NotSubscribedError{TopicID: topicID} } return g.publish(msg, g.topicConsensus) default: return InvalidTopicError{TopicID: topicID} } } // publish publishes a message with the specified topic to the network. func (g *gossipService) publish(msg []byte, topic *lp2pps.Topic) error { err := topic.Publish(g.ctx, msg) if err != nil { return LibP2PError{Err: err} } return nil } // JoinTopic joins to the topic with the given name and subscribes to receive topic messages. func (g *gossipService) JoinTopic(topicID TopicID, evaluator PropagationEvaluator) error { switch topicID { case TopicIDUnspecified: return InvalidTopicError{TopicID: topicID} case TopicIDBlock: topic, err := g.joinTopic(topicID, evaluator) if err != nil { return err } g.topicBlock = topic return nil case TopicIDTransaction: topic, err := g.joinTopic(topicID, evaluator) if err != nil { return err } g.topicTransaction = topic return nil case TopicIDConsensus: topic, err := g.joinTopic(topicID, evaluator) if err != nil { return err } g.topicConsensus = topic return nil default: return InvalidTopicError{TopicID: topicID} } } func (g *gossipService) TopicName(topicID TopicID) string { return fmt.Sprintf("/%s/topic/%s/v1", g.networkName, topicID.String()) } // joinTopic joins a given topic and registers a validator for it. // If successful, it returns the topic and subscribes to it. func (g *gossipService) joinTopic(topicID TopicID, evaluator PropagationEvaluator) (*lp2pps.Topic, error) { topicName := g.TopicName(topicID) topic, err := g.pubsub.Join(topicName) if err != nil { return nil, LibP2PError{Err: err} } sub, err := topic.Subscribe() if err != nil { return nil, LibP2PError{Err: err} } err = g.pubsub.RegisterTopicValidator( topicName, g.createValidator(topicID, evaluator)) if err != nil { return nil, LibP2PError{Err: err} } g.topics = append(g.topics, topic) g.subs = append(g.subs, sub) g.wg.Go(func() { for { lp2pMsg, err := sub.Next(g.ctx) if err != nil { g.logger.Debug("readLoop error", "error", err) return } msg := &GossipMessage{ From: lp2pMsg.ReceivedFrom, Data: lp2pMsg.Data, TopicID: topicID, } g.onReceiveMessage(msg) } }) return topic, nil } func (g *gossipService) createValidator(topicID TopicID, evaluator PropagationEvaluator, ) func(context.Context, lp2pcore.PeerID, *lp2pps.Message) lp2pps.ValidationResult { return func(_ context.Context, peerId lp2pcore.PeerID, lp2pMsg *lp2pps.Message) lp2pps.ValidationResult { msg := &GossipMessage{ From: peerId, Data: lp2pMsg.Data, TopicID: topicID, } // Automatically accept and broadcast messages originating from this node if msg.From == g.host.ID() { return lp2pps.ValidationAccept } switch evaluator(msg) { case Drop: g.logger.Debug("message dropped", "from", peerId, "topic", topicID) return lp2pps.ValidationIgnore case DropButConsume: g.logger.Debug("message dropped but consumed", "from", peerId, "topic", topicID) // Consume the message first g.onReceiveMessage(msg) return lp2pps.ValidationIgnore case Propagate: return lp2pps.ValidationAccept default: panic("unreachable") } } } // Start starts the gossip service. func (*gossipService) Start() { } // Stop stops the gossip service. // It closes all the joined topics and cancels all the subscriptions. func (g *gossipService) Stop() { for _, t := range g.topics { _ = t.Close() } for _, s := range g.subs { s.Cancel() } g.wg.Wait() } func (g *gossipService) onReceiveMessage(msg *GossipMessage) { // only forward messages delivered by others if msg.From == g.host.ID() { return } g.logger.Debug("receiving new gossip message", "from", msg.From) g.networkPipe.Send(msg) } ================================================ FILE: network/gossip_test.go ================================================ package network import ( "testing" lp2pps "github.com/libp2p/go-libp2p-pubsub" pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" lp2pcore "github.com/libp2p/go-libp2p/core" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestJoinBlockTopic(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) msg := []byte("test-block-topic") require.ErrorIs(t, net.gossip.Broadcast(msg, TopicIDBlock), NotSubscribedError{ TopicID: TopicIDBlock, }) require.NoError(t, net.JoinTopic(TopicIDBlock, alwaysPropagate)) require.NoError(t, net.gossip.Broadcast(msg, TopicIDBlock)) require.Error(t, net.JoinTopic(TopicIDBlock, alwaysPropagate), "already joined") } func TestJoinConsensusTopic(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) msg := []byte("test-consensus-topic") require.ErrorIs(t, net.gossip.Broadcast(msg, TopicIDConsensus), NotSubscribedError{ TopicID: TopicIDConsensus, }) require.NoError(t, net.JoinTopic(TopicIDConsensus, alwaysPropagate)) require.NoError(t, net.gossip.Broadcast(msg, TopicIDConsensus)) require.Error(t, net.JoinTopic(TopicIDConsensus, alwaysPropagate), "already joined") } func TestJoinTransactionTopic(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) msg := []byte("test-transaction-topic") require.ErrorIs(t, net.gossip.Broadcast(msg, TopicIDTransaction), NotSubscribedError{ TopicID: TopicIDTransaction, }) require.NoError(t, net.JoinTopic(TopicIDTransaction, alwaysPropagate)) require.NoError(t, net.gossip.Broadcast(msg, TopicIDTransaction)) require.Error(t, net.JoinTopic(TopicIDTransaction, alwaysPropagate), "already joined") } func TestJoinInvalidTopic(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) require.ErrorIs(t, net.JoinTopic(TopicIDUnspecified, alwaysPropagate), InvalidTopicError{ TopicID: TopicIDUnspecified, }) require.ErrorIs(t, net.JoinTopic(TopicID(-1), alwaysPropagate), InvalidTopicError{ TopicID: TopicID(-1), }) } func TestInvalidTopic(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) msg := []byte("test-invalid-topic") require.ErrorIs(t, net.gossip.Broadcast(msg, TopicIDUnspecified), InvalidTopicError{ TopicID: TopicIDUnspecified, }) require.ErrorIs(t, net.gossip.Broadcast(msg, -1), InvalidTopicError{ TopicID: TopicID(-1), }) } func TestTopicValidator(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) selfID := net.host.ID() propagate := Drop validator := net.gossip.createValidator(TopicIDConsensus, func(_ *GossipMessage) PropagationPolicy { return propagate }) tests := []struct { name string peerID lp2pcore.PeerID policy PropagationPolicy expectedResult lp2pps.ValidationResult }{ { name: "Message from self", policy: Drop, peerID: selfID, expectedResult: lp2pps.ValidationAccept, }, { name: "Message from self", policy: DropButConsume, peerID: selfID, expectedResult: lp2pps.ValidationAccept, }, { name: "Message from self", policy: propagate, peerID: selfID, expectedResult: lp2pps.ValidationAccept, }, { name: "Message from other peer, should not propagate", policy: Drop, peerID: "other-peerID", expectedResult: lp2pps.ValidationIgnore, }, { name: "Message from other peer, should not propagate", policy: DropButConsume, peerID: "other-peerID", expectedResult: lp2pps.ValidationIgnore, }, { name: "Message from other peer, should propagate", policy: Propagate, peerID: "other-peerID", expectedResult: lp2pps.ValidationAccept, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { msg := &lp2pps.Message{ Message: &pubsubpb.Message{ Data: []byte("some-data"), }, } propagate = tt.policy result := validator(t.Context(), tt.peerID, msg) assert.Equal(t, tt.expectedResult, result) }) } } ================================================ FILE: network/interface.go ================================================ package network import ( "io" lp2pcore "github.com/libp2p/go-libp2p/core" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" ) type TopicID int const ( TopicIDUnspecified TopicID = 0 TopicIDBlock TopicID = 1 TopicIDTransaction TopicID = 2 TopicIDConsensus TopicID = 3 ) func (t TopicID) String() string { switch t { case TopicIDUnspecified: return "unspecified" case TopicIDBlock: return "block" case TopicIDTransaction: return "transaction" case TopicIDConsensus: return "consensus" } return "invalid" } type EventType int const ( EventTypeConnect EventType = 1 EventTypeDisconnect EventType = 2 EventTypeProtocols EventType = 3 EventTypeGossip EventType = 4 EventTypeStream EventType = 5 ) func (t EventType) String() string { switch t { case EventTypeConnect: return "connect" case EventTypeDisconnect: return "disconnect" case EventTypeProtocols: return "protocols" case EventTypeGossip: return "gossip-msg" case EventTypeStream: return "stream-msg" } return "invalid" } type Event interface { Type() EventType } // GossipMessage represents message from PubSub module. // `From` is the ID of the peer that we received a message from. type GossipMessage struct { From lp2pcore.PeerID Data []byte TopicID TopicID } func (*GossipMessage) Type() EventType { return EventTypeGossip } // StreamMessage represents message from Stream module. // `From` is the ID of the peer that we received a message from. type StreamMessage struct { From lp2pcore.PeerID Reader io.ReadCloser } func (*StreamMessage) Type() EventType { return EventTypeStream } // ConnectEvent represents a peer connection event. type ConnectEvent struct { PeerID lp2pcore.PeerID RemoteAddress string Direction lp2pnetwork.Direction } func (*ConnectEvent) Type() EventType { return EventTypeConnect } // DisconnectEvent represents a peer disconnection event. type DisconnectEvent struct { PeerID lp2pcore.PeerID } func (*DisconnectEvent) Type() EventType { return EventTypeDisconnect } // ProtocolsEvents represents updating protocols event. type ProtocolsEvents struct { PeerID lp2pcore.PeerID Protocols []string } func (*ProtocolsEvents) Type() EventType { return EventTypeProtocols } // PropagationPolicy defines the possible actions for how a gossip message should propagate. type PropagationPolicy int const ( // Propagate means the message should be forwarded to other peers in the network. Propagate = PropagationPolicy(0) // DropButConsume means the message should not be forwarded but should be processed locally. DropButConsume = PropagationPolicy(1) // Drop means the message should be discarded without any further processing. Drop = PropagationPolicy(2) ) // PropagationEvaluator is a function that evaluates how a gossip message should propagate. type PropagationEvaluator func(*GossipMessage) PropagationPolicy type Network interface { Start() error Stop() Protect(lp2pcore.PeerID, string) Broadcast([]byte, TopicID) SendTo([]byte, lp2pcore.PeerID) JoinTopic(TopicID, PropagationEvaluator) error CloseConnection(lp2pcore.PeerID) SelfID() lp2pcore.PeerID NumConnectedPeers() int NumInbound() int NumOutbound() int ReachabilityStatus() string HostAddrs() []string Name() string Protocols() []string } ================================================ FILE: network/mdns.go ================================================ package network import ( "context" "time" lp2phost "github.com/libp2p/go-libp2p/core/host" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" lp2pmdns "github.com/libp2p/go-libp2p/p2p/discovery/mdns" "github.com/pactus-project/pactus/util/logger" ) type mdnsService struct { ctx context.Context host lp2phost.Host service lp2pmdns.Service logger *logger.SubLogger } // newMdnsService creates an mDNS discovery service and attaches it to the libp2p Host. // This lets us automatically discover peers on the same LAN and connect to them. func newMdnsService(ctx context.Context, host lp2phost.Host, log *logger.SubLogger) *mdnsService { mdns := &mdnsService{ ctx: ctx, host: host, logger: log, } // setup mDNS discovery to find local peers mdns.service = lp2pmdns.NewMdnsService(host, "pactus-mdns", mdns) return mdns } // HandlePeerFound connects to peers discovered via mDNS. Once they're connected, // the PubSub system will automatically start interacting with them if they also // support PubSub. func (s *mdnsService) HandlePeerFound(addrInfo lp2ppeer.AddrInfo) { ctx, cancel := context.WithTimeout(s.ctx, time.Second*10) defer cancel() if addrInfo.ID != s.host.ID() { s.logger.Debug("connecting to new peer", "addr", addrInfo.Addrs, "id", addrInfo.ID) if err := s.host.Connect(ctx, addrInfo); err != nil { s.logger.Error("error on connecting to peer", "id", addrInfo.ID, "error", err) } } } func (s *mdnsService) Start() error { err := s.service.Start() if err != nil { return LibP2PError{Err: err} } return nil } func (s *mdnsService) Stop() { err := s.service.Close() if err != nil { s.logger.Error("unable to close the network", "error", err) } } ================================================ FILE: network/mdns_test.go ================================================ package network import ( "runtime" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMDNS(t *testing.T) { if runtime.GOOS == "darwin" { // Disable this test on darwin (macOS) // Read more here: https://github.com/pactus-project/pactus/issues/1860 return } conf1 := testConfig() conf1.ListenAddrStrings = []string{ "/ip6/::1/tcp/0", "/ip6/::1/udp/0/quic-v1", "/ip4/127.0.0.1/tcp/0", "/ip4/127.0.0.1/udp/0/quic-v1", } conf1.EnableMdns = true net1 := makeTestNetwork(t, conf1, nil) conf2 := testConfig() conf2.ListenAddrStrings = []string{ "/ip6/::1/tcp/0", "/ip6/::1/udp/0/quic-v1", "/ip4/127.0.0.1/tcp/0", "/ip4/127.0.0.1/udp/0/quic-v1", } conf2.EnableMdns = true net2 := makeTestNetwork(t, conf2, nil) require.NoError(t, net1.Start()) time.Sleep(250 * time.Millisecond) require.NoError(t, net2.Start()) time.Sleep(250 * time.Millisecond) msg := []byte("test-mdns") net1.SendTo(msg, net2.SelfID()) se := shouldReceiveEvent(t, net2, EventTypeStream).(*StreamMessage) assert.Equal(t, net1.SelfID(), se.From) assert.Equal(t, msg, readData(t, se.Reader, len(msg))) net1.Stop() net2.Stop() } ================================================ FILE: network/mock.go ================================================ package network import ( "bytes" "context" "io" "sync" "github.com/ezex-io/gopkg/pipeline" lp2pcore "github.com/libp2p/go-libp2p/core" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/util/testsuite" ) var _ Network = &MockNetwork{} type PublishData struct { Data []byte Target *lp2pcore.PeerID } // MockNetwork is a mock implementation of the Network interface for testing. type MockNetwork struct { *testsuite.TestSuite lk sync.RWMutex ID lp2ppeer.ID PublishCh chan PublishData EventPipe pipeline.Pipeline[Event] OtherNets map[lp2ppeer.ID]*MockNetwork } func MockingNetwork(ts *testsuite.TestSuite, pid lp2ppeer.ID) *MockNetwork { return &MockNetwork{ TestSuite: ts, PublishCh: make(chan PublishData, 100), EventPipe: pipeline.New[Event](context.Background()), OtherNets: make(map[lp2ppeer.ID]*MockNetwork), ID: pid, } } func (*MockNetwork) Start() error { return nil } func (*MockNetwork) Stop() {} func (*MockNetwork) Protect(_ lp2pcore.PeerID, _ string) {} func (*MockNetwork) JoinTopic(_ TopicID, _ PropagationEvaluator) error { return nil } func (m *MockNetwork) SelfID() lp2ppeer.ID { return m.ID } func (m *MockNetwork) SendTo(data []byte, pid lp2pcore.PeerID) { m.lk.RLock() defer m.lk.RUnlock() net, exists := m.OtherNets[pid] if exists { // direct message event := &StreamMessage{ From: m.ID, Reader: io.NopCloser(bytes.NewReader(data)), } net.EventPipe.Send(event) } m.PublishCh <- PublishData{ Data: data, Target: &pid, } } func (m *MockNetwork) Broadcast(data []byte, _ TopicID) { m.lk.RLock() defer m.lk.RUnlock() for _, net := range m.OtherNets { if net.SelfID() == m.ID { continue } // Broadcast message event := &GossipMessage{ From: m.ID, Data: data, } net.EventPipe.Send(event) } m.PublishCh <- PublishData{ Data: data, Target: nil, // Send to all } } func (m *MockNetwork) CloseConnection(pid lp2ppeer.ID) { m.lk.RLock() defer m.lk.RUnlock() delete(m.OtherNets, pid) } func (m *MockNetwork) IsClosed(pid lp2ppeer.ID) bool { m.lk.RLock() defer m.lk.RUnlock() _, exists := m.OtherNets[pid] return !exists } func (m *MockNetwork) NumConnectedPeers() int { return len(m.OtherNets) } func (m *MockNetwork) AddAnotherNetwork(otherNet *MockNetwork, direction lp2pnetwork.Direction) { m.lk.Lock() defer m.lk.Unlock() m.OtherNets[otherNet.SelfID()] = otherNet m.EventPipe.Send(&ConnectEvent{ PeerID: otherNet.SelfID(), RemoteAddress: m.RandMultiAddress(), Direction: direction, }) m.EventPipe.Send(&ProtocolsEvents{ PeerID: otherNet.SelfID(), Protocols: []string{"protocol-1", "protocol-2"}, }) } func (*MockNetwork) ReachabilityStatus() string { return "Unknown" } func (*MockNetwork) HostAddrs() []string { return []string{"localhost"} } func (*MockNetwork) Name() string { return "pactus" } func (*MockNetwork) Protocols() []string { return []string{"gossip"} } func (m *MockNetwork) NumInbound() int { return len(m.OtherNets) } func (m *MockNetwork) NumOutbound() int { return len(m.OtherNets) } ================================================ FILE: network/network.go ================================================ package network import ( "context" "encoding/hex" "errors" "fmt" "strings" "time" "github.com/ezex-io/gopkg/pipeline" lp2p "github.com/libp2p/go-libp2p" lp2pcore "github.com/libp2p/go-libp2p/core" lp2pcrypto "github.com/libp2p/go-libp2p/core/crypto" lp2phost "github.com/libp2p/go-libp2p/core/host" lp2pmetrics "github.com/libp2p/go-libp2p/core/metrics" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" lp2pautorelay "github.com/libp2p/go-libp2p/p2p/host/autorelay" lp2prcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager" lp2pconnmgr "github.com/libp2p/go-libp2p/p2p/net/connmgr" lp2pproto "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/proto" lp2quic "github.com/libp2p/go-libp2p/p2p/transport/quic" lp2ptcp "github.com/libp2p/go-libp2p/p2p/transport/tcp" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/version" "github.com/prometheus/client_golang/prometheus" "golang.org/x/exp/slices" ) var _ Network = &network{} type network struct { ctx context.Context config *Config host lp2phost.Host mdns *mdnsService dht *dhtService peerMgr *peerMgr connGater *ConnectionGater stream *streamService gossip *gossipService notifee *NotifeeService networkPipe pipeline.Pipeline[Event] logger *logger.SubLogger } func loadOrCreateKey(path string) (lp2pcrypto.PrivKey, error) { if util.PathExists(path) { data, err := util.ReadFile(path) if err != nil { return nil, err } h := strings.TrimSpace(string(data)) bs, err := hex.DecodeString(h) if err != nil { return nil, err } key, err := lp2pcrypto.UnmarshalPrivateKey(bs) if err != nil { return nil, err } return key, nil } key, _, err := lp2pcrypto.GenerateEd25519Key(nil) if err != nil { return nil, errors.New("failed to generate private key") } bs, err := lp2pcrypto.MarshalPrivateKey(key) if err != nil { return nil, err } h := hex.EncodeToString(bs) err = util.WriteFile(path, []byte(h)) if err != nil { return nil, err } return key, nil } func NewNetwork(ctx context.Context, conf *Config, networkPipe pipeline.Pipeline[Event]) (Network, error) { log := logger.NewSubLogger("_network", nil) return makeNetwork(ctx, conf, log, networkPipe, []lp2p.Option{}) } func makeNetwork(ctx context.Context, conf *Config, log *logger.SubLogger, networkPipe pipeline.Pipeline[Event], opts []lp2p.Option, ) (*network, error) { self := new(network) networkKey, err := loadOrCreateKey(conf.NetworkKey) if err != nil { return nil, LibP2PError{Err: err} } rcMgrOpt := []lp2prcmgr.Option{} if conf.EnableMetrics { log.Info("metric enabled") str, err := lp2prcmgr.NewStatsTraceReporter() if err != nil { return nil, LibP2PError{Err: err} } // metrics for rcMgr lp2prcmgr.MustRegisterWith(prometheus.DefaultRegisterer) rcMgrOpt = append(rcMgrOpt, lp2prcmgr.WithTraceReporter(str)) // metrics for lp2p bandwidthCounter := lp2pmetrics.NewBandwidthCounter() opts = append(opts, lp2p.BandwidthReporter(bandwidthCounter)) } else { rcMgrOpt = append(rcMgrOpt, lp2prcmgr.WithMetricsDisabled()) opts = append(opts, lp2p.DisableMetrics()) } resMgr, err := lp2prcmgr.NewResourceManager( lp2prcmgr.NewFixedLimiter(lp2prcmgr.InfiniteLimits), rcMgrOpt..., ) if err != nil { return nil, LibP2PError{Err: err} } // https://docs.libp2p.io/concepts/security/dos-mitigation/#limit-the-number-of-connections-your-application-needs // The ConnManager is in charge of pruning connections to stay below the defined high watermark, // in contrast, the Resource Manager represents a hard limit where connections will fail to // be created in the first place once we’ve reached our limits. // lowWM := conf.MaxConns // Low Watermark, ex: 64 (if max_conn = 64) highWM := conf.MaxConns + (conf.MaxConns / 4) // High Watermark, ex: 80 (if max_conn = 64) connMgr, err := lp2pconnmgr.NewConnManager( lowWM, highWM, lp2pconnmgr.WithGracePeriod(time.Minute), ) if err != nil { return nil, LibP2PError{Err: err} } log.Info("connection manager created", "lowWM", lowWM, "highWM", highWM) opts = append(opts, lp2p.Identity(networkKey), lp2p.ListenAddrs(conf.ListenAddrs()...), lp2p.UserAgent(version.NodeAgent.String()), lp2p.ResourceManager(resMgr), lp2p.ConnectionManager(connMgr), lp2p.Ping(true), lp2p.Transport(lp2ptcp.NewTCPTransport), ) if conf.EnableUDP { log.Info("UDP is enabled") opts = append(opts, lp2p.Transport(lp2quic.NewTransport)) } if conf.EnableNATService { log.Info("Nat service enabled") opts = append(opts, lp2p.EnableNATService(), ) } else { log.Info("AutoNATv2 enabled") opts = append(opts, lp2p.EnableAutoNATv2(), ) } if conf.EnableUPnP { log.Info("UPnP enabled") opts = append(opts, lp2p.NATPortMap(), ) } // networkReady is a channel used to wait until the network is ready. // This is primarily to avoid reading while writing. networkReady := make(chan struct{}) defer close(networkReady) networkGetter := func() *network { <-networkReady // Closed when newNetwork is finished time.Sleep(1 * time.Second) // Adding a safety delay return self } if conf.EnableRelay { log.Info("relay enabled") autoRelayOpt := []lp2pautorelay.Option{ lp2pautorelay.WithMinCandidates(1), lp2pautorelay.WithMaxCandidates(4), lp2pautorelay.WithMinInterval(1 * time.Minute), } opts = append(opts, lp2p.EnableRelay(), lp2p.EnableAutoRelayWithPeerSource(findRelayPeers(networkGetter), autoRelayOpt...), lp2p.EnableHolePunching(), ) } else { log.Info("relay disabled") opts = append(opts, lp2p.DisableRelay(), ) } if conf.EnableRelayService { log.Info("relay service enabled") opts = append(opts, lp2p.EnableRelayService()) } privateSubnets := PrivateSubnets() privateFilters := SubnetsToFilters(privateSubnets, multiaddr.ActionDeny) publicAddrs := conf.PublicAddr() addrFactory := lp2p.AddrsFactory(func(mas []multiaddr.Multiaddr) []multiaddr.Multiaddr { addrs := []multiaddr.Multiaddr{} for _, addr := range mas { if conf.ForcePrivateNetwork || !privateFilters.AddrBlocked(addr) { addrs = append(addrs, addr) } } if publicAddrs != nil { addrs = append(addrs, publicAddrs) } return addrs }) opts = append(opts, addrFactory) connGater, err := NewConnectionGater(conf, log) if err != nil { return nil, LibP2PError{Err: err} } opts = append(opts, lp2p.ConnectionGater(connGater)) host, err := lp2p.New(opts...) if err != nil { return nil, LibP2PError{Err: err} } self.ctx = ctx self.config = conf self.logger = log self.host = host self.connGater = connGater self.networkPipe = networkPipe log.SetObj(self) conf.CheckIsBootstrapper(host.ID()) kadProtocolID := lp2pcore.ProtocolID(fmt.Sprintf("/%s/gossip/v1", conf.NetworkName)) // TODO: better name? streamProtocolID := lp2pcore.ProtocolID(fmt.Sprintf("/%s/stream/v1", conf.NetworkName)) if conf.EnableMdns { self.mdns = newMdnsService(ctx, self.host, self.logger) } self.peerMgr = newPeerMgr(ctx, host, conf, self.logger) self.dht = newDHTService(ctx, host, conf, kadProtocolID, self.logger) self.stream = newStreamService(ctx, host, conf, streamProtocolID, self.networkPipe, self.logger) self.gossip = newGossipService(ctx, host, conf, self.networkPipe, self.logger) self.notifee = newNotifeeService(ctx, host, self.networkPipe, self.peerMgr, streamProtocolID, self.logger) self.logger.Info("network setup", "id", self.host.ID(), "name", conf.NetworkName, "address", conf.ListenAddrs(), "bootstrapper", conf.IsBootstrapper, "maxConns", conf.MaxConns) return self, nil } func findRelayPeers(networkGetter func() *network) func(ctx context.Context, num int) <-chan lp2ppeer.AddrInfo { return func(ctx context.Context, num int) <-chan lp2ppeer.AddrInfo { // make a channel to return, and put items from numPeers on // that channel up to numPeers. Then close it. r := make(chan lp2ppeer.AddrInfo, num) defer close(r) // Because the network is initialized after relay, we need to // obtain them indirectly this way. net := networkGetter() if net == nil { // context canceled etc. return r } net.logger.Debug("try to find relay peers", "num", num) peerStore := net.host.Peerstore() for _, pid := range peerStore.Peers() { protos, err := peerStore.GetProtocols(pid) if err != nil { continue } if !slices.Contains(protos, lp2pproto.ProtoIDv2Hop) { continue } addr := peerStore.Addrs(pid) net.logger.Debug("found relay peer", "addr", addr) dhtPeer := lp2ppeer.AddrInfo{ID: pid, Addrs: addr} // Attempt to put peers on r if we have space, // otherwise return (we reached numPeers) select { case r <- dhtPeer: case <-ctx.Done(): return r default: return r } } return r } } func (n *network) Start() error { if err := n.dht.Start(); err != nil { return LibP2PError{Err: err} } if n.mdns != nil { if err := n.mdns.Start(); err != nil { return LibP2PError{Err: err} } } n.gossip.Start() n.stream.Start() n.peerMgr.Start() n.notifee.Start() n.host.Network().Notify(n.notifee) n.connGater.SetPeerManager(n.peerMgr) n.logger.Info("network started", "addr", n.host.Addrs(), "id", n.host.ID()) return nil } func (n *network) Stop() { if n.mdns != nil { n.mdns.Stop() } n.gossip.Stop() n.stream.Stop() n.peerMgr.Stop() n.notifee.Stop() n.dht.Stop() if err := n.host.Close(); err != nil { n.logger.Error("unable to close the network", "error", err) } } func (n *network) SelfID() lp2ppeer.ID { return n.host.ID() } func (n *network) Protect(pid lp2pcore.PeerID, tag string) { n.host.ConnManager().Protect(pid, tag) } // SendTo sends a message to a specific peer identified by pid asynchronously. // It uses a goroutine to ensure that if sending is blocked, receiving messages won't be blocked. func (n *network) SendTo(msg []byte, pid lp2pcore.PeerID) { go func() { _, err := n.stream.SendTo(msg, pid) if err != nil { n.logger.Warn("error on sending msg", "pid", pid, "error", err) } }() } // Broadcast sends a message to all peers subscribed to a specific topic asynchronously. // It uses a goroutine to ensure that if broadcasting is blocked, receiving messages won't be blocked. func (n *network) Broadcast(msg []byte, topicID TopicID) { go func() { err := n.gossip.Broadcast(msg, topicID) if err != nil { n.logger.Warn("error on broadcasting msg", "error", err) } }() } func (n *network) JoinTopic(topicID TopicID, evaluator PropagationEvaluator) error { return n.gossip.JoinTopic(topicID, evaluator) } func (n *network) CloseConnection(pid lp2ppeer.ID) { n.logger.Debug("closing connection", "pid", pid) if err := n.host.Network().ClosePeer(pid); err != nil { n.logger.Warn("unable to close connection", "peer", pid) } n.logger.Debug("connection closed", "pid", pid) } // LogString returns a concise string representation intended for use in logs. func (n *network) LogString() string { return fmt.Sprintf("{%d}", n.NumConnectedPeers()) } func (n *network) NumConnectedPeers() int { return len(n.host.Network().Peers()) } func (n *network) ReachabilityStatus() string { return n.notifee.Reachability().String() } func (n *network) HostAddrs() []string { addrs := make([]string, 0, len(n.host.Addrs())) for _, addr := range n.host.Addrs() { addrs = append(addrs, addr.String()) } return addrs } func (n *network) Name() string { return n.config.NetworkName } func (n *network) Protocols() []string { protocolIDs := n.host.Mux().Protocols() protocols := make([]string, 0, len(protocolIDs)) for _, p := range protocolIDs { protocols = append(protocols, string(p)) } return protocols } func (n *network) NumInbound() int { return n.peerMgr.NumInbound() } func (n *network) NumOutbound() int { return n.peerMgr.NumOutbound() } ================================================ FILE: network/network_test.go ================================================ package network import ( "errors" "fmt" "io" "testing" "time" "github.com/ezex-io/gopkg/pipeline" lp2p "github.com/libp2p/go-libp2p" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" lp2pproto "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/proto" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func alwaysPropagate(_ *GossipMessage) PropagationPolicy { return Propagate } func makeTestNetwork(t *testing.T, conf *Config, opts []lp2p.Option) *network { t.Helper() pipe := pipeline.New[Event](t.Context()) log := logger.NewSubLogger("_network", nil) net, err := makeNetwork(t.Context(), conf, log, pipe, opts) require.NoError(t, err) log.SetObj(testsuite.NewOverrideLogStringer( fmt.Sprintf("%s - %s: ", net.SelfID().ShortString(), t.Name()), net)) require.NoError(t, net.Start()) return net } func testConfig() *Config { return &Config{ ListenAddrStrings: []string{}, NetworkKey: util.TempFilePath(), BootstrapAddrStrings: []string{}, MaxConns: 16, EnableUDP: true, EnableNATService: false, EnableUPnP: false, EnableRelay: false, EnableRelayService: false, EnableMdns: false, ForcePrivateNetwork: true, NetworkName: "test", DefaultPort: testsuite.FindFreePort(), PeerStorePath: util.TempFilePath(), StreamTimeout: 10 * time.Second, CheckConnectivityInterval: 1 * time.Second, MaxGossipMessageSize: 1 * 1024 * 1024, // 1 MB MaxStreamMessageSize: 8 * 1024 * 1024, // 8 MB } } func shouldReceiveEvent(t *testing.T, net *network, eventType EventType) Event { t.Helper() timer := time.NewTimer(10 * time.Second) for { select { case <-timer.C: require.NoError(t, fmt.Errorf("shouldReceiveEvent Timeout, test: %v id:%s", t.Name(), net.SelfID().String())) return nil case e := <-net.networkPipe.UnsafeGetChannel(): if e.Type() == eventType { return e } } } } func shouldNotReceiveEvent(t *testing.T, net *network) { t.Helper() timer := time.NewTimer(100 * time.Millisecond) for { select { case <-timer.C: return case <-net.networkPipe.UnsafeGetChannel(): require.NoError(t, fmt.Errorf("shouldNotReceiveEvent, test: %v id:%s", t.Name(), net.SelfID().String())) return } } } func readData(t *testing.T, r io.ReadCloser, length int) []byte { t.Helper() buf := make([]byte, length) _, err := r.Read(buf) if !errors.Is(err, io.EOF) { require.NoError(t, err) require.NoError(t, r.Close()) } return buf } func TestStoppingNetwork(t *testing.T) { net := makeTestNetwork(t, testConfig(), nil) require.NoError(t, net.Start()) require.NoError(t, net.JoinTopic(TopicIDBlock, alwaysPropagate)) // Should stop peacefully net.Stop() } // In this test, we are setting up a simulated network environment that consists of these nodes: // - B is a Bootstrap node // - P is a Public and relay node // - M, N, and X are Private Nodes behind a Network Address Translation (NAT) // - M and N have relay enabled, while X does not. // // The test evaluates the following scenarios: // - Get supporting protocols // - Connection establishment to the bootstrap node // - Receiving gossip message // - Receiving direct message // - Receiving relayed message (Not covered yet!) func TestNetwork(t *testing.T) { ts := testsuite.NewTestSuite(t) // Bootstrap node confB := testConfig() fmt.Println("Starting Bootstrap node") networkB := makeTestNetwork(t, confB, []lp2p.Option{ lp2p.ForceReachabilityPublic(), }) bootstrapAddresses := []string{ fmt.Sprintf("/ip4/127.0.0.1/tcp/%v/p2p/%v", confB.DefaultPort, networkB.SelfID().String()), fmt.Sprintf("/ip4/127.0.0.1/udp/%v/quic-v1/p2p/%v", confB.DefaultPort, networkB.SelfID().String()), fmt.Sprintf("/ip6/::1/tcp/%v/p2p/%v", confB.DefaultPort, networkB.SelfID().String()), fmt.Sprintf("/ip6/::1/udp/%v/quic-v1/p2p/%v", confB.DefaultPort, networkB.SelfID().String()), } // Public and relay node confP := testConfig() confP.BootstrapAddrStrings = bootstrapAddresses confP.EnableRelay = false confP.EnableRelayService = true fmt.Println("Starting Public node") networkP := makeTestNetwork(t, confP, []lp2p.Option{ lp2p.ForceReachabilityPublic(), }) publicAddrInfo, _ := lp2ppeer.AddrInfoFromString( fmt.Sprintf("/ip4/127.0.0.1/tcp/%v/p2p/%s", confP.DefaultPort, networkP.SelfID())) // Private node M confM := testConfig() confM.EnableRelay = true confM.BootstrapAddrStrings = bootstrapAddresses fmt.Println("Starting Private node M") networkM := makeTestNetwork(t, confM, []lp2p.Option{ lp2p.ForceReachabilityPrivate(), }) // Private node N confN := testConfig() confN.EnableRelay = true confN.BootstrapAddrStrings = bootstrapAddresses fmt.Println("Starting Private node N") networkN := makeTestNetwork(t, confN, []lp2p.Option{ lp2p.ForceReachabilityPrivate(), }) // Private node X, doesn't join consensus topic and disabled relay confX := testConfig() confX.EnableRelay = false confX.BootstrapAddrStrings = bootstrapAddresses fmt.Println("Starting Private node X") networkX := makeTestNetwork(t, confX, []lp2p.Option{ lp2p.ForceReachabilityPrivate(), }) require.NoError(t, networkB.JoinTopic(TopicIDBlock, alwaysPropagate)) require.NoError(t, networkP.JoinTopic(TopicIDBlock, alwaysPropagate)) require.NoError(t, networkM.JoinTopic(TopicIDBlock, alwaysPropagate)) require.NoError(t, networkN.JoinTopic(TopicIDBlock, alwaysPropagate)) require.NoError(t, networkX.JoinTopic(TopicIDBlock, alwaysPropagate)) require.NoError(t, networkB.JoinTopic(TopicIDConsensus, alwaysPropagate)) require.NoError(t, networkP.JoinTopic(TopicIDConsensus, alwaysPropagate)) require.NoError(t, networkM.JoinTopic(TopicIDConsensus, alwaysPropagate)) require.NoError(t, networkN.JoinTopic(TopicIDConsensus, alwaysPropagate)) // Network X doesn't join the consensus topic time.Sleep(4 * time.Second) t.Run("Supported Protocols", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) require.EventuallyWithT(t, func(c *assert.CollectT) { protos := networkM.Protocols() assert.Contains(c, protos, lp2pproto.ProtoIDv2Stop) assert.NotContains(c, protos, lp2pproto.ProtoIDv2Hop) }, 2*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { protos := networkN.Protocols() assert.Contains(c, protos, lp2pproto.ProtoIDv2Stop) assert.NotContains(c, protos, lp2pproto.ProtoIDv2Hop) }, 2*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { protos := networkP.Protocols() assert.NotContains(c, protos, lp2pproto.ProtoIDv2Stop) assert.Contains(c, protos, lp2pproto.ProtoIDv2Hop) }, 2*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { protos := networkX.Protocols() assert.NotContains(c, protos, lp2pproto.ProtoIDv2Stop) assert.NotContains(c, protos, lp2pproto.ProtoIDv2Hop) }, 2*time.Second, 100*time.Millisecond) }) t.Run("Reachability", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) require.EventuallyWithT(t, func(c *assert.CollectT) { reachability := networkB.ReachabilityStatus() require.Equal(c, "Public", reachability) }, time.Second*2, 500*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { reachability := networkM.ReachabilityStatus() require.Equal(c, "Private", reachability) }, time.Second*2, 500*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { reachability := networkN.ReachabilityStatus() require.Equal(c, "Private", reachability) }, time.Second*2, 500*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { reachability := networkP.ReachabilityStatus() require.Equal(c, "Public", reachability) }, time.Second*2, 500*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { reachability := networkP.ReachabilityStatus() require.Equal(c, "Public", reachability) }, time.Second*2, 100*time.Millisecond) }) t.Run("all nodes have at least one connection to the bootstrap node B", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) require.EventuallyWithT(t, func(c *assert.CollectT) { require.GreaterOrEqual(c, networkP.NumConnectedPeers(), 1) // Connected to B, M, N, X }, 5*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { require.GreaterOrEqual(c, networkB.NumConnectedPeers(), 1) // Connected to P, M, N, X }, 5*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { require.GreaterOrEqual(c, networkM.NumConnectedPeers(), 1) // Connected to B, P, N? }, 5*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { require.GreaterOrEqual(c, networkN.NumConnectedPeers(), 1) // Connected to B, P, M? }, 5*time.Second, 100*time.Millisecond) require.EventuallyWithT(t, func(c *assert.CollectT) { require.GreaterOrEqual(c, networkX.NumConnectedPeers(), 1) // Connected to B, P }, 5*time.Second, 100*time.Millisecond) }) t.Run("Gossip: all nodes receive gossip messages", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) msg := ts.RandBytes(64) networkP.Broadcast(msg, TopicIDBlock) eB := shouldReceiveEvent(t, networkB, EventTypeGossip).(*GossipMessage) eM := shouldReceiveEvent(t, networkM, EventTypeGossip).(*GossipMessage) eN := shouldReceiveEvent(t, networkN, EventTypeGossip).(*GossipMessage) eX := shouldReceiveEvent(t, networkX, EventTypeGossip).(*GossipMessage) assert.Equal(t, msg, eB.Data) assert.Equal(t, msg, eM.Data) assert.Equal(t, msg, eN.Data) assert.Equal(t, msg, eX.Data) }) t.Run("only nodes subscribed to the consensus topic receive consensus gossip messages", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) msg := ts.RandBytes(64) networkP.Broadcast(msg, TopicIDConsensus) eB := shouldReceiveEvent(t, networkB, EventTypeGossip).(*GossipMessage) eM := shouldReceiveEvent(t, networkM, EventTypeGossip).(*GossipMessage) eN := shouldReceiveEvent(t, networkN, EventTypeGossip).(*GossipMessage) shouldNotReceiveEvent(t, networkX) // Not joined the consensus topic assert.Equal(t, msg, eB.Data) assert.Equal(t, msg, eM.Data) assert.Equal(t, msg, eN.Data) }) t.Run("node P (public) is directly accessible by nodes M and N (private behind NAT)", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) require.NoError(t, networkM.host.Connect(networkM.ctx, *publicAddrInfo)) msgM := ts.RandBytes(64) networkM.SendTo(msgM, networkP.SelfID()) eP := shouldReceiveEvent(t, networkP, EventTypeStream).(*StreamMessage) assert.Equal(t, networkM.SelfID(), eP.From) assert.Equal(t, msgM, readData(t, eP.Reader, len(msgM))) }) t.Run("node P (public) is directly accessible by node X (private behind NAT, without relay)", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) require.NoError(t, networkX.host.Connect(networkX.ctx, *publicAddrInfo)) msgX := ts.RandBytes(64) networkX.SendTo(msgX, networkP.SelfID()) eP := shouldReceiveEvent(t, networkP, EventTypeStream).(*StreamMessage) assert.Equal(t, networkX.SelfID(), eP.From) assert.Equal(t, msgX, readData(t, eP.Reader, len(msgX))) }) t.Run("node P (public) is directly accessible by node B (bootstrap)", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) msgB := ts.RandBytes(64) networkB.SendTo(msgB, networkP.SelfID()) eB := shouldReceiveEvent(t, networkP, EventTypeStream).(*StreamMessage) assert.Equal(t, networkB.SelfID(), eB.From) assert.Equal(t, msgB, readData(t, eB.Reader, len(msgB))) }) t.Run("Ignore broadcasting identical messages", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) msg := ts.RandBytes(64) networkM.Broadcast(msg, TopicIDBlock) networkN.Broadcast(msg, TopicIDBlock) eX := shouldReceiveEvent(t, networkX, EventTypeGossip).(*GossipMessage) assert.Equal(t, msg, eX.Data) assert.NotEqual(t, eX.From, networkM.SelfID(), "network X has no direct connection with M") assert.NotEqual(t, eX.From, networkN.SelfID(), "network X has no direct connection with N") shouldNotReceiveEvent(t, networkX) }) t.Run("node X (private, not connected via relay) is not accessible by node M", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) msgM := ts.RandBytes(64) networkM.SendTo(msgM, networkX.SelfID()) }) // TODO: How to test this? // t.Run("nodes M and N (private, connected via relay) can communicate using the relay node R", func(t *testing.T) { // msgM := ts.RandBytes(64) // networkM.SendTo(msgM, networkN.SelfID()) // eM := shouldReceiveEvent(t, networkN, EventTypeStream).(*StreamMessage) // assert.Equal(t, msgM, readData(t, eM.Reader, len(msgM))) // }) t.Run("closing connection", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) msgB := ts.RandBytes(64) networkP.Stop() networkB.CloseConnection(networkP.SelfID()) e := shouldReceiveEvent(t, networkB, EventTypeDisconnect).(*DisconnectEvent) assert.Equal(t, networkP.SelfID(), e.PeerID) networkB.SendTo(msgB, networkP.SelfID()) }) t.Run("Reachability Status", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) require.Equal(t, "Public", networkP.ReachabilityStatus()) require.Equal(t, "Public", networkB.ReachabilityStatus()) require.Equal(t, "Private", networkM.ReachabilityStatus()) require.Equal(t, "Private", networkN.ReachabilityStatus()) require.Equal(t, "Private", networkX.ReachabilityStatus()) }) } func TestHostAddrs(t *testing.T) { conf := testConfig() net := makeTestNetwork(t, conf, nil) addrs := net.HostAddrs() assert.Contains(t, addrs, fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", conf.DefaultPort)) assert.Contains(t, addrs, fmt.Sprintf("/ip4/127.0.0.1/udp/%d/quic-v1", conf.DefaultPort)) } func TestNetworkName(t *testing.T) { conf := testConfig() net := makeTestNetwork(t, conf, nil) assert.Equal(t, conf.NetworkName, net.Name()) } func TestConnections(t *testing.T) { t.Parallel() // run the tests in parallel tests := []struct { bootstrapAddr string peerAddr string }{ {"/ip4/127.0.0.1/tcp/%d", "/ip4/127.0.0.1/tcp/0"}, {"/ip6/::1/tcp/%d", "/ip6/::1/tcp/0"}, {"/ip4/127.0.0.1/udp/%d/quic-v1", "/ip4/127.0.0.1/udp/0/quic-v1"}, {"/ip6/::1/udp/%d/quic-v1", "/ip6/::1/udp/0/quic-v1"}, } for no, tt := range tests { // Bootstrap node confB := testConfig() bootstrapAddr := fmt.Sprintf(tt.bootstrapAddr, confB.DefaultPort) confB.ListenAddrStrings = []string{bootstrapAddr} fmt.Println("Starting Bootstrap node") networkB := makeTestNetwork(t, confB, []lp2p.Option{ lp2p.ForceReachabilityPublic(), }) // Public node confP := testConfig() confP.BootstrapAddrStrings = []string{ fmt.Sprintf("%s/p2p/%v", bootstrapAddr, networkB.SelfID().String()), } confP.ListenAddrStrings = []string{tt.peerAddr} fmt.Println("Starting Public node") networkP := makeTestNetwork(t, confP, []lp2p.Option{ lp2p.ForceReachabilityPublic(), }) t.Run(fmt.Sprintf("Running test %d: %s <-> %s ... ", no, bootstrapAddr, tt.peerAddr), func(t *testing.T) { t.Parallel() // run the tests in parallel checkConnection(t, networkP, networkB) }) } } func checkConnection(t *testing.T, networkP, networkB *network) { t.Helper() assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.GreaterOrEqual(c, networkP.NumConnectedPeers(), 1) assert.GreaterOrEqual(c, networkB.NumConnectedPeers(), 1) }, 5*time.Second, 100*time.Millisecond) msg := []byte("test-msg") networkP.SendTo(msg, networkB.SelfID()) e := shouldReceiveEvent(t, networkB, EventTypeStream).(*StreamMessage) assert.Equal(t, networkP.SelfID(), e.From) assert.Equal(t, msg, readData(t, e.Reader, len(msg))) networkB.Stop() networkP.Stop() } func TestLoadOrCreateKey(t *testing.T) { t.Run("Should load same network key after being created", func(t *testing.T) { keyPath := util.TempFilePath() // Create new valid key validKey, err := loadOrCreateKey(keyPath) require.NoError(t, err) // Retrieve previously created valid key, the file path exists previousValidKey, err := loadOrCreateKey(keyPath) require.NoError(t, err) assert.Equal(t, validKey.GetPublic(), previousValidKey.GetPublic()) }) t.Run("Should return error when file contains invalid data", func(t *testing.T) { tempFilePath := util.TempFilePath() err := util.WriteFile(tempFilePath, []byte("invalid_data")) require.NoError(t, err) key, err := loadOrCreateKey(tempFilePath) require.Error(t, err) assert.Nil(t, key) }) t.Run("Should return error when file contains invalid private key", func(t *testing.T) { tempFilePath := util.TempFilePath() err := util.WriteFile(tempFilePath, []byte("00")) require.NoError(t, err) key, err := loadOrCreateKey(tempFilePath) require.Error(t, err) assert.Nil(t, key) }) t.Run("Should return error when input path is directory", func(t *testing.T) { tempDir := t.TempDir() key, err := loadOrCreateKey(tempDir) require.Error(t, err) assert.Nil(t, key) }) t.Run("Should return error when input path is invalid", func(t *testing.T) { invalidPath := string([]byte{0x00}) key, err := loadOrCreateKey(invalidPath) require.Error(t, err) assert.Nil(t, key) }) t.Run("Should trim spaces", func(t *testing.T) { tempFilePath := util.TempFilePath() err := util.WriteFile(tempFilePath, []byte(" 080112406da99c6b29ac8093fad3a92327aaf87acf22dbb60927786db25880f025c0"+ "4cb6f80873898709981d9b75795a191eab2d29bc7983ebcb4826e2b44566c85ea194 \r\n")) require.NoError(t, err) key, err := loadOrCreateKey(tempFilePath) require.NoError(t, err) assert.NotNil(t, key) }) } ================================================ FILE: network/notifee.go ================================================ package network import ( "context" "github.com/ezex-io/gopkg/pipeline" lp2pcore "github.com/libp2p/go-libp2p/core" lp2pevent "github.com/libp2p/go-libp2p/core/event" lp2phost "github.com/libp2p/go-libp2p/core/host" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" lp2peventbus "github.com/libp2p/go-libp2p/p2p/host/eventbus" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util/logger" "golang.org/x/exp/slices" ) type NotifeeService struct { ctx context.Context host lp2phost.Host lp2pEventSub lp2pevent.Subscription networkPipe pipeline.Pipeline[Event] logger *logger.SubLogger streamProtocolID lp2pcore.ProtocolID peerMgr *peerMgr reachability lp2pnetwork.Reachability } func newNotifeeService(ctx context.Context, host lp2phost.Host, networkPipe pipeline.Pipeline[Event], peerMgr *peerMgr, protocolID lp2pcore.ProtocolID, log *logger.SubLogger, ) *NotifeeService { events := []any{ new(lp2pevent.EvtLocalReachabilityChanged), new(lp2pevent.EvtPeerIdentificationCompleted), new(lp2pevent.EvtPeerIdentificationFailed), new(lp2pevent.EvtPeerProtocolsUpdated), } subOptions := []lp2pevent.SubscriptionOpt{ lp2peventbus.BufSize(1024), } eventSub, err := host.EventBus().Subscribe(events, subOptions...) if err != nil { logger.Error("failed to register for libp2p events") } notifee := &NotifeeService{ ctx: ctx, host: host, lp2pEventSub: eventSub, networkPipe: networkPipe, streamProtocolID: protocolID, peerMgr: peerMgr, logger: log, reachability: lp2pnetwork.ReachabilityUnknown, } return notifee } func (s *NotifeeService) Start() { go func() { for { select { case evt := <-s.lp2pEventSub.Out(): switch evt := evt.(type) { case lp2pevent.EvtLocalReachabilityChanged: s.logger.Info("reachability changed", "reachability", evt.Reachability) s.reachability = evt.Reachability case lp2pevent.EvtPeerIdentificationCompleted: s.logger.Debug("identification completed", "pid", evt.Peer) s.sendProtocolsEvent(evt.Peer) case lp2pevent.EvtPeerIdentificationFailed: s.logger.Warn("identification failed", "pid", evt.Peer) case lp2pevent.EvtPeerProtocolsUpdated: s.logger.Debug("protocols updated", "pid", evt.Peer, "protocols", evt.Added) s.sendProtocolsEvent(evt.Peer) default: // unhandled libp2p event } case <-s.ctx.Done(): return } } }() } func (s *NotifeeService) Stop() { _ = s.lp2pEventSub.Close() } func (s *NotifeeService) Reachability() lp2pnetwork.Reachability { return s.reachability } func (s *NotifeeService) Connected(_ lp2pnetwork.Network, conn lp2pnetwork.Conn) { pid := conn.RemotePeer() s.logger.Info("connected to peer", "pid", pid, "direction", conn.Stat().Direction, "addr", conn.RemoteMultiaddr()) s.peerMgr.SetPeerConnected(pid, conn.RemoteMultiaddr(), conn.Stat().Direction) s.sendConnectEvent(pid, conn.RemoteMultiaddr(), conn.Stat().Direction) } func (s *NotifeeService) Disconnected(_ lp2pnetwork.Network, conn lp2pnetwork.Conn) { pid := conn.RemotePeer() s.logger.Info("disconnected from peer", "pid", pid) s.peerMgr.SetPeerDisconnected(pid) s.sendDisconnectEvent(pid) } func (s *NotifeeService) Listen(_ lp2pnetwork.Network, ma multiaddr.Multiaddr) { // Handle listen event if needed. s.logger.Debug("notifee Listen event emitted", "addr", ma.String()) } // ListenClose is called when the peer stops listening on an address. func (s *NotifeeService) ListenClose(_ lp2pnetwork.Network, ma multiaddr.Multiaddr) { // Handle listen close event if needed. s.logger.Debug("notifee ListenClose event emitted", "addr", ma.String()) } func (s *NotifeeService) sendProtocolsEvent(pid lp2pcore.PeerID) { protocols, _ := s.host.Peerstore().GetProtocols(pid) protocolsStr := make([]string, 0, len(protocols)) for _, p := range protocols { protocolsStr = append(protocolsStr, string(p)) } slices.Sort(protocolsStr) event := &ProtocolsEvents{ PeerID: pid, Protocols: protocolsStr, } s.networkPipe.Send(event) } func (s *NotifeeService) sendConnectEvent(pid lp2pcore.PeerID, remoteAddress multiaddr.Multiaddr, direction lp2pnetwork.Direction, ) { event := &ConnectEvent{ PeerID: pid, RemoteAddress: remoteAddress.String(), Direction: direction, } s.networkPipe.Send(event) } func (s *NotifeeService) sendDisconnectEvent(pid lp2pcore.PeerID) { event := &DisconnectEvent{ PeerID: pid, } s.networkPipe.Send(event) } ================================================ FILE: network/peermgr.go ================================================ package network import ( "context" "encoding/json" "fmt" "sync" "time" "github.com/ezex-io/gopkg/scheduler" lp2phost "github.com/libp2p/go-libp2p/core/host" lp2pnet "github.com/libp2p/go-libp2p/core/network" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" ) type peerInfo struct { MultiAddress multiaddr.Multiaddr Connected bool Direction lp2pnet.Direction } // Peer Manager attempts to establish connections with other nodes when the // number of connections falls below the minimum threshold. type peerMgr struct { lk sync.RWMutex ctx context.Context logger *logger.SubLogger minConns int numInbound int numOutbound int host lp2phost.Host peers map[lp2ppeer.ID]*peerInfo peerStorePath string checkInterval time.Duration } // newPeerMgr creates a new Peer Manager instance. func newPeerMgr(ctx context.Context, host lp2phost.Host, conf *Config, log *logger.SubLogger, ) *peerMgr { peerStore, err := loadPeerStore(conf.PeerStorePath) if err != nil { log.Debug("failed to load peer store", "err", err) } log.Info("peer store loaded successfully") peerStore = append(peerStore, conf.BootstrapAddrInfos()...) peers := make(map[lp2ppeer.ID]*peerInfo) for _, ai := range peerStore { peers[ai.ID] = &peerInfo{ MultiAddress: ai.Addrs[0], Connected: false, Direction: lp2pnet.DirUnknown, } } mgr := &peerMgr{ ctx: ctx, minConns: conf.MinConns(), peers: peers, peerStorePath: conf.PeerStorePath, host: host, logger: log, checkInterval: conf.CheckConnectivityInterval, } log.Info("peer manager created", "minConns", mgr.minConns) return mgr } // Start starts the Peer Manager. func (mgr *peerMgr) Start() { mgr.CheckConnectivity() scheduler.Every(mgr.checkInterval).Do(mgr.ctx, func(context.Context) { mgr.CheckConnectivity() }) } func (mgr *peerMgr) Stop() { if err := mgr.savePeerStore(); err != nil { mgr.logger.Error("can't save peer store", "err", err) } } func (mgr *peerMgr) SetPeerConnected(pid lp2ppeer.ID, ma multiaddr.Multiaddr, direction lp2pnet.Direction, ) { mgr.lk.Lock() defer mgr.lk.Unlock() mgr.setPeerConnected(pid, ma, direction) } func (mgr *peerMgr) setPeerConnected(pid lp2ppeer.ID, ma multiaddr.Multiaddr, direction lp2pnet.Direction, ) { pi, exists := mgr.peers[pid] if exists && pi.Connected { return } switch direction { case lp2pnet.DirInbound: mgr.numInbound++ case lp2pnet.DirOutbound: mgr.numOutbound++ case lp2pnet.DirUnknown: // } mgr.peers[pid] = &peerInfo{ Connected: true, MultiAddress: ma, Direction: direction, } } func (mgr *peerMgr) SetPeerDisconnected(pid lp2ppeer.ID) { mgr.lk.Lock() defer mgr.lk.Unlock() mgr.setPeerDisconnected(pid) } func (mgr *peerMgr) setPeerDisconnected(pid lp2ppeer.ID) { peerInfo, exists := mgr.peers[pid] if !exists { return } if !peerInfo.Connected { return } switch peerInfo.Direction { case lp2pnet.DirInbound: mgr.numInbound-- case lp2pnet.DirOutbound: mgr.numOutbound-- case lp2pnet.DirUnknown: // } peerInfo.Connected = false peerInfo.Direction = lp2pnet.DirUnknown } // CheckConnectivity performs the actual work of maintaining connections. // It ensures that the number of connections stays within the minimum and maximum thresholds. func (mgr *peerMgr) CheckConnectivity() { mgr.lk.Lock() defer mgr.lk.Unlock() net := mgr.host.Network() // Check if some peers are disconnected numConnected := 0 for pid := range mgr.peers { connectedness := net.Connectedness(pid) if connectedness == lp2pnet.Connected { numConnected++ } } mgr.logger.Debug("check connectivity", "numConnected", numConnected, "inbound", mgr.numInbound, "outbound", mgr.numOutbound) if numConnected < mgr.minConns { mgr.logger.Info("peer count is less than minimum threshold", "numConnected", numConnected, "min", mgr.minConns) for pid, info := range mgr.peers { // preventing self dialing. if pid == mgr.host.ID() { continue } mgr.logger.Debug("try connecting to a bootstrap peer", "peer", pid.String()) // Don't try to connect to an already connected peer. if info.Connected { continue } ai := lp2ppeer.AddrInfo{ ID: pid, Addrs: []multiaddr.Multiaddr{info.MultiAddress}, } ConnectAsync(mgr.ctx, mgr.host, ai, mgr.logger) } } } func (mgr *peerMgr) NumInbound() int { mgr.lk.RLock() defer mgr.lk.RUnlock() return mgr.numInbound } func (mgr *peerMgr) NumOutbound() int { mgr.lk.RLock() defer mgr.lk.RUnlock() return mgr.numOutbound } func (mgr *peerMgr) savePeerStore() error { mgr.lk.RLock() defer mgr.lk.RUnlock() ps := make([]string, 0, len(mgr.peers)) for id, info := range mgr.peers { ps = append(ps, fmt.Sprintf("%s/p2p/%s", info.MultiAddress.String(), id.String())) } data, err := json.Marshal(ps) if err != nil { return err } return util.WriteFile(mgr.peerStorePath, data) } func loadPeerStore(path string) ([]lp2ppeer.AddrInfo, error) { peerStore := make([]lp2ppeer.AddrInfo, 0) data, err := util.ReadFile(path) if err != nil { return peerStore, err } addrs := make([]string, 0) err = json.Unmarshal(data, &addrs) if err != nil { return peerStore, err } peerStore, err = MakeAddrInfos(addrs) if err != nil { return []lp2ppeer.AddrInfo{}, err } return peerStore, nil } ================================================ FILE: network/peermgr_test.go ================================================ package network import ( "testing" lp2pnet "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestNumInboundOutbound(t *testing.T) { ts := testsuite.NewTestSuite(t) conf := testConfig() net := makeTestNetwork(t, conf, nil) addr, _ := IPToMultiAddr("1.2.3.4", 1234) pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() pid3 := ts.RandPeerID() net.peerMgr.SetPeerConnected(pid1, addr, lp2pnet.DirInbound) net.peerMgr.SetPeerConnected(pid1, addr, lp2pnet.DirInbound) // Duplicated event net.peerMgr.SetPeerConnected(pid2, addr, lp2pnet.DirOutbound) net.peerMgr.SetPeerConnected(pid3, addr, lp2pnet.DirOutbound) net.peerMgr.SetPeerDisconnected(pid1) net.peerMgr.SetPeerDisconnected(pid1) // Duplicated event net.peerMgr.SetPeerDisconnected(pid2) net.peerMgr.SetPeerDisconnected(ts.RandPeerID()) net.peerMgr.SetPeerConnected(pid1, addr, lp2pnet.DirInbound) // Connect again assert.Equal(t, 1, net.NumInbound()) assert.Equal(t, 1, net.NumOutbound()) } ================================================ FILE: network/stream.go ================================================ package network import ( "context" "time" "github.com/ezex-io/gopkg/pipeline" lp2pcore "github.com/libp2p/go-libp2p/core" lp2phost "github.com/libp2p/go-libp2p/core/host" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" lp2peer "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" ) type streamService struct { ctx context.Context host lp2phost.Host protocolID lp2pcore.ProtocolID timeout time.Duration networkPipe pipeline.Pipeline[Event] maxMessageSize int64 logger *logger.SubLogger } func newStreamService(ctx context.Context, host lp2phost.Host, conf *Config, protocolID lp2pcore.ProtocolID, networkPipe pipeline.Pipeline[Event], log *logger.SubLogger, ) *streamService { service := &streamService{ ctx: ctx, host: host, protocolID: protocolID, timeout: conf.StreamTimeout, networkPipe: networkPipe, maxMessageSize: int64(conf.MaxStreamMessageSize), logger: log, } service.host.SetStreamHandler(protocolID, service.handleStream) return service } func (*streamService) Start() {} func (*streamService) Stop() {} func (s *streamService) handleStream(stream lp2pnetwork.Stream) { // Set a deadline for both reading and writing to ensure // this stream will eventually be closed. // In very rare cases, the read or write channel may get stuck. _ = stream.SetDeadline(time.Now().Add(s.timeout)) from := stream.Conn().RemotePeer() s.logger.Debug("receiving stream", "from", from) limitReader := util.LimitReaderClose(stream, s.maxMessageSize) event := &StreamMessage{ From: from, Reader: limitReader, } s.networkPipe.Send(event) } // SendTo sends a message to a specific peer, assuming there is already a direct connection. // // For simplicity, we do not use bi-directional streams. // Each time a peer wants to send a message, it creates a new stream. // // For more details on stream multiplexing, refer to: https://docs.libp2p.io/concepts/multiplex/overview/ func (s *streamService) SendTo(msg []byte, pid lp2peer.ID) (lp2pnetwork.Stream, error) { s.logger.Trace("sending stream", "to", pid) _, err := s.host.Peerstore().SupportsProtocols(pid, s.protocolID) if err != nil { return nil, LibP2PError{Err: err} } // To prevent a broken stream from being open forever. ctxWithTimeout, cancel := context.WithTimeout(s.ctx, s.timeout) defer cancel() // Attempt to open a new stream to the peer, assuming there's already a direct connection. stream, err := s.host.NewStream( lp2pnetwork.WithNoDial(ctxWithTimeout, "should already have connection"), pid, s.protocolID) if err != nil { return nil, LibP2PError{Err: err} } _ = stream.SetDeadline(time.Now().Add(s.timeout)) _, err = stream.Write(msg) if err != nil { _ = stream.Reset() return nil, LibP2PError{Err: err} } err = stream.CloseWrite() if err != nil { return nil, LibP2PError{Err: err} } // We need to close the stream once it is read by the receiver. // If, for any reason, the receiver doesn't close the stream, we need to close it after a timeout. go func() { timer := time.NewTimer(s.timeout) closed := make(chan bool) go func() { // We need only one byte to read the EOF. buf := make([]byte, 1) _, _ = stream.Read(buf) closed <- true }() select { case <-timer.C: s.logger.Warn("stream timeout", "to", pid) _ = stream.Close() case <-closed: s.logger.Debug("stream closed", "to", pid) _ = stream.Close() } }() return stream, nil } ================================================ FILE: network/stream_test.go ================================================ package network import ( "fmt" "testing" "time" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCloseStream(t *testing.T) { ts := testsuite.NewTestSuite(t) makeNetworks := func(streamTimeout time.Duration) (networkA, networkB *network) { confA := testConfig() confA.StreamTimeout = streamTimeout confA.CheckConnectivityInterval = 60 * time.Second networkA = makeTestNetwork(t, confA, nil) confB := testConfig() confB.StreamTimeout = streamTimeout confB.CheckConnectivityInterval = 60 * time.Second _ = util.WriteFile(confB.PeerStorePath, []byte(fmt.Sprintf("[\"/ip4/127.0.0.1/tcp/%v/p2p/%v\"]", confA.DefaultPort, networkA.SelfID().String()))) networkB = makeTestNetwork(t, confB, nil) assert.EventuallyWithT(t, func(collect *assert.CollectT) { e := <-networkA.networkPipe.UnsafeGetChannel() assert.Equal(collect, EventTypeConnect, e.Type()) }, 5*time.Second, 100*time.Millisecond) assert.EventuallyWithT(t, func(collect *assert.CollectT) { e := <-networkB.networkPipe.UnsafeGetChannel() assert.Equal(collect, EventTypeConnect, e.Type()) }, 5*time.Second, 100*time.Millisecond) return networkA, networkB } // streamClosed check if a stream is fully closed for both ends streamClosed := func(networkA, networkB *network, streamID string) bool { connsAtoB := networkA.host.Network().ConnsToPeer(networkB.SelfID()) streamsAtoB := connsAtoB[0].GetStreams() hasStream := false for _, s := range streamsAtoB { if s.ID() == streamID { hasStream = true } } connsBtoA := networkB.host.Network().ConnsToPeer(networkA.SelfID()) streamsBtoA := connsBtoA[0].GetStreams() for _, s := range streamsBtoA { if s.ID() == streamID { hasStream = true } } return !hasStream } t.Run("Normal Case", func(t *testing.T) { networkA, networkB := makeNetworks(10 * time.Second) sentMsg := ts.RandBytes(32) stream, err := networkA.stream.SendTo(sentMsg, networkB.SelfID()) require.NoError(t, err) // NetworkB close the stream after reading the data assert.EventuallyWithT(t, func(collect *assert.CollectT) { e := <-networkB.networkPipe.UnsafeGetChannel() streamMsg, ok := e.(*StreamMessage) assert.True(collect, ok) if ok { receivedMsg := make([]byte, len(sentMsg)) _, _ = streamMsg.Reader.Read(receivedMsg) assert.Equal(collect, sentMsg, receivedMsg) _ = streamMsg.Reader.Close() } }, 5*time.Second, 100*time.Millisecond) // NetworkA should receive EOF and close/remove the stream assert.EventuallyWithT(t, func(collect *assert.CollectT) { assert.True(collect, streamClosed(networkA, networkB, stream.ID())) }, 5*time.Second, 100*time.Millisecond) }) t.Run("Receiver (NetworkB) doesn't close the stream", func(t *testing.T) { networkA, networkB := makeNetworks(1 * time.Second) sentMsg := ts.RandBytes(32) stream, err := networkA.stream.SendTo(sentMsg, networkB.SelfID()) require.NoError(t, err) // NetworkB close the stream after reading the data. assert.EventuallyWithT(t, func(collect *assert.CollectT) { e := <-networkB.networkPipe.UnsafeGetChannel() s, ok := e.(*StreamMessage) assert.True(collect, ok) if ok { receivedMsg := make([]byte, len(sentMsg)) _, _ = s.Reader.Read(receivedMsg) assert.Equal(collect, sentMsg, receivedMsg) // NetworkB doesn't close the stream. // s.Reader.Close() } }, 5*time.Second, 100*time.Millisecond) // NetworkA should close/remove the stream after timeout. assert.EventuallyWithT(t, func(collect *assert.CollectT) { assert.True(collect, streamClosed(networkA, networkB, stream.ID())) }, 5*time.Second, 100*time.Millisecond) }) t.Run("Receiver (NetworkB) close the stream without reading", func(t *testing.T) { networkA, networkB := makeNetworks(1 * time.Second) sentMsg := ts.RandBytes(32) stream, err := networkA.stream.SendTo(sentMsg, networkB.SelfID()) require.NoError(t, err) // NetworkB close the stream after reading the data assert.EventuallyWithT(t, func(collect *assert.CollectT) { e := <-networkB.networkPipe.UnsafeGetChannel() s, ok := e.(*StreamMessage) assert.True(collect, ok) if ok { _ = s.Reader.Close() } }, 5*time.Second, 100*time.Millisecond) // NetworkA should close/remove the stream as well. assert.EventuallyWithT(t, func(collect *assert.CollectT) { assert.True(collect, streamClosed(networkA, networkB, stream.ID())) }, 5*time.Second, 100*time.Millisecond) }) } ================================================ FILE: network/utils.go ================================================ package network import ( "context" "fmt" "net" "slices" "time" lp2pspb "github.com/libp2p/go-libp2p-pubsub/pb" lp2phost "github.com/libp2p/go-libp2p/core/host" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" lp2pswarm "github.com/libp2p/go-libp2p/p2p/net/swarm" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/util/logger" ) // MakeMultiAddrs converts a slice of string peer addresses to MultiAddress. func MakeMultiAddrs(addrs []string) ([]multiaddr.Multiaddr, error) { mas := make([]multiaddr.Multiaddr, 0, len(addrs)) for _, addr := range addrs { ma, err := multiaddr.NewMultiaddr(addr) if err != nil { return nil, err } mas = append(mas, ma) } return mas, nil } // MakeAddrInfos converts a slice of string peer addresses to AddrInfo. func MakeAddrInfos(addrs []string) ([]lp2ppeer.AddrInfo, error) { pis := make([]lp2ppeer.AddrInfo, 0, len(addrs)) for _, addr := range addrs { pinfo, err := lp2ppeer.AddrInfoFromString(addr) if err != nil { return nil, err } pis = append(pis, *pinfo) } return pis, nil } func IPToMultiAddr(ip string, port int) (multiaddr.Multiaddr, error) { ipParsed := net.ParseIP(ip) if ipParsed == nil { return nil, fmt.Errorf("invalid IP address: %s", ip) } var addr string if ipParsed.To4() != nil { addr = fmt.Sprintf("/ip4/%s/tcp/%d", ip, port) } else { addr = fmt.Sprintf("/ip6/%s/tcp/%d", ip, port) } ma, err := multiaddr.NewMultiaddr(addr) if err != nil { return nil, err } return ma, nil } // HasPID checks if a peer ID exists in a list of peer IDs. func HasPID(pids []lp2ppeer.ID, pid lp2ppeer.ID) bool { return slices.Contains(pids, pid) } func ConnectAsync(ctx context.Context, h lp2phost.Host, addrInfo lp2ppeer.AddrInfo, log *logger.SubLogger) { go func() { err := ConnectSync(ctx, h, addrInfo) if log != nil { if err != nil { log.Info("connection failed", "addr", addrInfo.Addrs, "err", err) } else { log.Debug("connection successful", "addr", addrInfo.Addrs) } } }() } func ConnectSync(ctx context.Context, h lp2phost.Host, addrInfo lp2ppeer.AddrInfo) error { if swarm, ok := h.Network().(*lp2pswarm.Swarm); ok { swarm.Backoff().Clear(addrInfo.ID) } return h.Connect(lp2pnetwork.WithDialPeerTimeout(ctx, 10*time.Second), addrInfo) } func PrivateSubnets() []*net.IPNet { privateCIDRs := []string{ // -- Ipv4 -- // localhost "127.0.0.0/8", // private networks "10.0.0.0/8", "100.64.0.0/10", "172.16.0.0/12", "192.168.0.0/16", // link local "169.254.0.0/16", // -- Ipv6 -- // localhost "::1/128", // ULA reserved "fc00::/7", // link local "fe80::/10", } subnets := make([]*net.IPNet, 0, len(privateCIDRs)) for _, cidr := range privateCIDRs { _, sn, err := net.ParseCIDR(cidr) if err != nil { panic(err) } subnets = append(subnets, sn) } return subnets } func SubnetsToFilters(subnets []*net.IPNet, action multiaddr.Action) *multiaddr.Filters { filters := multiaddr.NewFilters() for _, sn := range subnets { filters.AddFilter(*sn, action) } return filters } func MessageIDFunc(m *lp2pspb.Message) string { h := hash.CalcHash(m.Data) return string(h[:20]) } ================================================ FILE: network/utils_test.go ================================================ package network import ( "testing" lp2pspb "github.com/libp2p/go-libp2p-pubsub/pb" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/multiformats/go-multiaddr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMakeMultiAddrs(t *testing.T) { tests := []struct { name string inputAddrs []string expected []multiaddr.Multiaddr }{ { inputAddrs: []string{ "/ip4/127.0.0.1/tcp/1234", "/ip6/::1/tcp/5678/", "/dns4/example.com", }, expected: []multiaddr.Multiaddr{ multiaddr.Cast([]byte{0x04, 0x7f, 0x00, 0x00, 0x01, 0x06, 0x04, 0xd2}), multiaddr.Cast([]byte{ 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x06, 0x16, 0x2e, }), multiaddr.Cast([]byte{0x36, 0x0b, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d}), }, }, { inputAddrs: []string{ "invalid_address", }, expected: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualPis, actualError := MakeMultiAddrs(tt.inputAddrs) if tt.expected != nil { assert.Equal(t, tt.expected, actualPis) require.NoError(t, actualError) } else { require.Error(t, actualError) assert.Nil(t, actualPis) } }) } } func TestMakeAddrInfos(t *testing.T) { pid, _ := lp2ppeer.Decode("12D3KooWCwQZt8UriVXobQHPXPR8m83eceXVoeT6brPNiBHomebc") tests := []struct { name string inputAddrs []string expectedPis []lp2ppeer.AddrInfo }{ { inputAddrs: []string{ "/ip4/127.0.0.1/tcp/1234/p2p/12D3KooWCwQZt8UriVXobQHPXPR8m83eceXVoeT6brPNiBHomebc", "/ip6/::1/tcp/5678/p2p/12D3KooWCwQZt8UriVXobQHPXPR8m83eceXVoeT6brPNiBHomebc", "/dns4/example.com/tcp/4001/p2p/12D3KooWCwQZt8UriVXobQHPXPR8m83eceXVoeT6brPNiBHomebc", }, expectedPis: []lp2ppeer.AddrInfo{ { ID: pid, Addrs: []multiaddr.Multiaddr{ multiaddr.StringCast("/ip4/127.0.0.1/tcp/1234"), }, }, { ID: pid, Addrs: []multiaddr.Multiaddr{ multiaddr.StringCast("/ip6/::1/tcp/5678"), }, }, { ID: pid, Addrs: []multiaddr.Multiaddr{ multiaddr.StringCast("/dns4/example.com/tcp/4001"), }, }, }, }, { inputAddrs: []string{ "/ip4/127.0.0.1/tcp/1234", // No peer id }, expectedPis: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualPis, actualError := MakeAddrInfos(tt.inputAddrs) if tt.expectedPis != nil { assert.Equal(t, tt.expectedPis, actualPis) require.NoError(t, actualError) } else { require.Error(t, actualError) assert.Nil(t, actualPis) } }) } } func TestIPToMultiAddr(t *testing.T) { tests := []struct { ip string port int expected string }{ {"127.0.0.1", 8080, "/ip4/127.0.0.1/tcp/8080"}, {"192.168.1.1", 1234, "/ip4/192.168.1.1/tcp/1234"}, {"::1", 80, "/ip6/::1/tcp/80"}, {"invalid_ip", 80, ""}, } for _, tt := range tests { t.Run(tt.expected, func(t *testing.T) { ma, err := IPToMultiAddr(tt.ip, tt.port) if tt.expected != "" { require.NoError(t, err) assert.Equal(t, tt.expected, ma.String()) } else { require.Error(t, err) } }) } } func TestHasPID(t *testing.T) { pids := []lp2ppeer.ID{"peer1", "peer2", "peer3"} assert.True(t, HasPID(pids, lp2ppeer.ID("peer1"))) assert.False(t, HasPID(pids, lp2ppeer.ID("peer4"))) } func TestSubnetsToFilters(t *testing.T) { sns := PrivateSubnets() filter := SubnetsToFilters(sns, multiaddr.ActionDeny) ma1, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0") ma2, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1") ma3, _ := multiaddr.NewMultiaddr("/ip4/8.8.8.8") assert.False(t, filter.AddrBlocked(ma1)) assert.True(t, filter.AddrBlocked(ma2)) assert.False(t, filter.AddrBlocked(ma3)) } func TestMessageIdFunc(t *testing.T) { m := &lp2pspb.Message{Data: []byte("pactus")} id := MessageIDFunc(m) assert.Equal(t, id, string([]byte{ 0xea, 0x02, 0x0a, 0xce, 0x5c, 0x96, 0x8f, 0x75, 0x5d, 0xfc, 0x1b, 0x59, 0x21, 0xe5, 0x74, 0x19, 0x1c, 0xd9, 0xff, 0x43, })) } ================================================ FILE: node/node.go ================================================ package node import ( "context" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/config" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/sync" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/version" wltmgr "github.com/pactus-project/pactus/wallet/manager" "github.com/pactus-project/pactus/wallet/provider/local" "github.com/pactus-project/pactus/www/grpc" "github.com/pactus-project/pactus/www/html" "github.com/pactus-project/pactus/www/http" "github.com/pactus-project/pactus/www/jsonrpc" "github.com/pactus-project/pactus/www/zmq" "github.com/pkg/errors" ) type Node struct { ctx context.Context genesisDoc *genesis.Genesis config *config.Config state state.Facade store store.Store txPool txpool.TxPool consV1Mgr consmgr.Manager // Deprecated:: replaced by new consensus algorithm consV2Mgr consmgr.Manager network network.Network sync sync.Synchronizer walletMgr wltmgr.IManager grpc *grpc.Server html *html.Server http *http.Server jsonrpc *jsonrpc.Server zeromq *zmq.Server broadcastPipe pipeline.Pipeline[message.Message] networkPipe pipeline.Pipeline[network.Event] eventPipe pipeline.Pipeline[any] } func NewNode(ctx context.Context, genDoc *genesis.Genesis, conf *config.Config, valKeys []*bls.ValidatorKey, rewardAddrs []crypto.Address, ) (*Node, error) { // Initialize the logger logger.InitGlobalLogger(ctx, conf.Logger) chainType := genDoc.ChainType() broadcastPipe := pipeline.New[message.Message](ctx, pipeline.WithName("Broadcast Pipeline"), pipeline.WithBufferSize(512)) networkPipe := pipeline.New[network.Event](ctx, pipeline.WithName("Network Pipeline"), pipeline.WithBufferSize(1024)) eventPipe := pipeline.New[any](ctx, pipeline.WithName("Event Pipeline"), pipeline.WithBufferSize(512)) store, err := store.NewStore(conf.Store) if err != nil { return nil, err } logger.Info("You are running a Pactus blockchain", "version", version.NodeVersion().StringWithAlias(), "network", chainType, "pruned", store.IsPruned()) txPool := txpool.NewTxPool(conf.TxPool, store, broadcastPipe, eventPipe) state, err := state.LoadOrNewState(genDoc, valKeys, store, txPool, eventPipe) if err != nil { return nil, err } net, err := network.NewNetwork(ctx, conf.Network, networkPipe) if err != nil { return nil, err } consV1Mgr := consmgr.NewManagerV1(ctx, conf.Consensus, state, valKeys, rewardAddrs, broadcastPipe) consV2Mgr := consmgr.NewManagerV2(ctx, conf.ConsensusV2, state, valKeys, rewardAddrs, broadcastPipe) if !store.IsPruned() { conf.Sync.Services.Append(service.FullNode) } sync, err := sync.NewSynchronizer(ctx, conf.Sync, valKeys, state, consV1Mgr, consV2Mgr, net, broadcastPipe, networkPipe) if err != nil { return nil, err } enableHTTPAuth := (conf.GRPC.BasicAuth != "") zeromqServer, err := zmq.New(ctx, conf.ZeroMq, eventPipe) if err != nil { return nil, err } curConsMgr := consV1Mgr if consV1Mgr.IsDeprecated() { curConsMgr = consV2Mgr } walletProvider := local.NewLocalBlockchainProvider(state) walletMgr, err := wltmgr.NewManager(ctx, conf.WalletManager, walletProvider, eventPipe) if err != nil { return nil, err } grpcServer := grpc.NewServer(ctx, conf.GRPC, state, sync, net, curConsMgr, walletMgr, zeromqServer.Publishers()) htmlServer := html.NewServer(ctx, conf.HTML, enableHTTPAuth) httpServer := http.NewServer(ctx, conf.HTTP) jsonrpcServer := jsonrpc.NewServer(ctx, conf.JSONRPC) node := &Node{ ctx: ctx, config: conf, genesisDoc: genDoc, network: net, state: state, txPool: txPool, consV1Mgr: consV1Mgr, consV2Mgr: consV2Mgr, sync: sync, store: store, walletMgr: walletMgr, grpc: grpcServer, html: htmlServer, http: httpServer, jsonrpc: jsonrpcServer, zeromq: zeromqServer, broadcastPipe: broadcastPipe, networkPipe: networkPipe, eventPipe: eventPipe, } return node, nil } func (n *Node) Start() error { now := time.Now() genTime := n.genesisDoc.GenesisTime() if genTime.After(now) { logger.Info("💤 Genesis time is in the future. Sleeping until then...", "duration", genTime.Sub(now), "genesis_hash", n.genesisDoc.Hash()) time.Sleep(genTime.Sub(now) - 1*time.Second) } if err := n.network.Start(); err != nil { return errors.Wrap(err, "could not start Network") } // Wait for network to start time.Sleep(1 * time.Second) if err := n.sync.Start(); err != nil { return errors.Wrap(err, "could not start Sync") } curConsMgr := n.consV1Mgr if n.consV1Mgr.IsDeprecated() { curConsMgr = n.consV2Mgr } curConsMgr.MoveToNewHeight() err := n.walletMgr.Start() if err != nil { return errors.Wrap(err, "could not start Wallet Manager") } err = n.grpc.StartServer() if err != nil { return errors.Wrap(err, "could not start gRPC server") } err = n.html.StartServer(n.grpc.Address()) if err != nil { return errors.Wrap(err, "could not start HTML server") } err = n.http.StartServer(n.grpc.Address()) if err != nil { return errors.Wrap(err, "could not start HTTP-API server") } err = n.jsonrpc.StartServer(n.grpc.Address()) if err != nil { return errors.Wrap(err, "could not start JSON-RPC server") } return nil } func (n *Node) Stop() { logger.Info("stopping Node") n.broadcastPipe.Close() n.networkPipe.Close() n.eventPipe.Close() // Wait for one second time.Sleep(1 * time.Second) n.network.Stop() // Wait for network to stop time.Sleep(1 * time.Second) n.sync.Stop() n.state.Close() n.store.Close() n.walletMgr.Stop() n.grpc.StopServer() n.html.StopServer() n.http.StopServer() n.jsonrpc.StopServer() n.zeromq.Close() } // these methods are using by GUI. func (n *Node) ConsManager() consmgr.ManagerReader { return n.consV1Mgr } func (n *Node) Sync() sync.Synchronizer { return n.sync } func (n *Node) State() state.Facade { return n.state } func (n *Node) GRPC() *grpc.Server { return n.grpc } func (n *Node) Network() network.Network { return n.network } func (n *Node) WalletManager() wltmgr.IManager { return n.walletMgr } ================================================ FILE: node/node_test.go ================================================ package node import ( "path/filepath" "testing" "time" "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/wallet" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRunningNode(t *testing.T) { ts := testsuite.NewTestSuite(t) // Prevent log from messing the workspace logger.LogFilename = util.TempFilePath() pub, _ := ts.RandBLSKeyPair() acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) val := validator.NewValidator(pub, 0) gen := genesis.MakeGenesis(time.Now(), map[crypto.Address]*account.Account{crypto.TreasuryAddress: acc}, []*validator.Validator{val}, genesis.DefaultGenesisParams()) conf := config.DefaultConfigMainnet() conf.GRPC.Enable = true conf.GRPC.Listen = "0.0.0.0:0" conf.HTML.Enable = true conf.HTML.Listen = "0.0.0.0:0" conf.HTTP.Enable = true conf.HTTP.Listen = "0.0.0.0:0" conf.JSONRPC.Enable = true conf.JSONRPC.Listen = "0.0.0.0:0" conf.Store.Path = util.TempDirPath() conf.Network.EnableRelay = false conf.Network.NetworkKey = util.TempFilePath() conf.Network.PeerStorePath = util.TempFilePath() conf.WalletManager.WalletsDir = util.TempDirPath() walletPath := filepath.Join(conf.WalletManager.WalletsDir, "default_wallet") mnemonic, _ := wallet.GenerateMnemonic(128) wlt, err := wallet.Create(t.Context(), walletPath, mnemonic, "", genesis.Mainnet) require.NoError(t, err) wlt.Close() valKeys := []*bls.ValidatorKey{ts.RandValKey(), ts.RandValKey()} rewardAddrs := []crypto.Address{ts.RandAccAddress(), ts.RandAccAddress()} node, err := NewNode(t.Context(), gen, conf, valKeys, rewardAddrs) require.NoError(t, err) assert.True(t, conf.Sync.Services.IsFullNode()) assert.True(t, conf.Sync.Services.IsPrunedNode()) assert.Equal(t, hash.UndefHash, node.state.LastBlockHash()) err = node.Start() require.NoError(t, err) consHeight, _ := node.ConsManager().HeightRound() assert.Equal(t, types.Height(1), consHeight) lastBlockTime := node.State().LastBlockTime() assert.Equal(t, gen.GenesisTime(), lastBlockTime) syncSelfID := node.Sync().SelfID() netSelfID := node.Network().SelfID() assert.Equal(t, syncSelfID, netSelfID) assert.NotEmpty(t, node.GRPC().Address()) wallets, err := node.WalletManager().ListWallets() require.NoError(t, err) assert.NotEmpty(t, wallets) node.Stop() } ================================================ FILE: sandbox/interface.go ================================================ package sandbox import ( "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" ) type Sandbox interface { Account(crypto.Address) *account.Account MakeNewAccount(crypto.Address) *account.Account UpdateAccount(crypto.Address, *account.Account) CommitTransaction(trx *tx.Tx) RecentTransaction(txID tx.ID) bool IsBanned(crypto.Address) bool Validator(crypto.Address) *validator.Validator MakeNewValidator(*bls.PublicKey) *validator.Validator UpdateValidator(*validator.Validator) JoinedToCommittee(crypto.Address) IsJoinedCommittee(crypto.Address) bool UpdatePowerDelta(delta int64) PowerDelta() int64 AccumulatedFee() amount.Amount VerifyProof(types.Height, sortition.Proof, *validator.Validator) bool Committee() committee.Reader Params() *param.Params CurrentHeight() types.Height IsMainnet() bool IterateAccounts(consumer func(crypto.Address, *account.Account, bool)) IterateValidators(consumer func(*validator.Validator, bool, bool)) } ================================================ FILE: sandbox/mock.go ================================================ package sandbox import ( "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" ) var _ Sandbox = &MockSandbox{} // MockSandbox is a mock implementation of the Sandbox interface for testing. type MockSandbox struct { ts *testsuite.TestSuite TestParams *param.Params TestStore *store.MockStore TestCommittee committee.Committee TestAcceptSortition bool TestJoinedValidators map[crypto.Address]bool TestCommittedTrxs map[tx.ID]*tx.Tx TestPowerDelta int64 } func MockingSandbox(ts *testsuite.TestSuite) *MockSandbox { cmt, _ := ts.GenerateTestCommittee(7) params := param.FromGenesis(genesis.MainnetGenesis()) params.BlockVersion = protocol.ProtocolVersion3 sbx := &MockSandbox{ ts: ts, TestParams: params, TestStore: store.MockingStore(ts), TestCommittee: cmt, TestJoinedValidators: make(map[crypto.Address]bool), TestCommittedTrxs: make(map[tx.ID]*tx.Tx), } treasuryAmt := amount.Amount(21_000_000 * 1e9) for i, val := range cmt.Validators() { acc := account.NewAccount(int32(i + 1)) acc.AddToBalance(10000 * 1e9) sbx.UpdateAccount(val.Address(), acc) sbx.UpdateValidator(val) treasuryAmt -= val.Stake() treasuryAmt -= acc.Balance() } acc0 := account.NewAccount(0) acc0.AddToBalance(treasuryAmt) sbx.UpdateAccount(crypto.TreasuryAddress, acc0) return sbx } func (m *MockSandbox) Account(addr crypto.Address) *account.Account { acc, _ := m.TestStore.Account(addr) return acc } func (m *MockSandbox) MakeNewAccount(_ crypto.Address) *account.Account { acc := account.NewAccount(m.TestStore.TotalAccounts()) return acc } func (m *MockSandbox) UpdateAccount(addr crypto.Address, acc *account.Account) { m.TestStore.UpdateAccount(addr, acc) } func (m *MockSandbox) RecentTransaction(txID tx.ID) bool { if m.TestCommittedTrxs[txID] != nil { return true } return m.TestStore.RecentTransaction(txID) } func (m *MockSandbox) Validator(addr crypto.Address) *validator.Validator { val, _ := m.TestStore.Validator(addr) return val } func (m *MockSandbox) JoinedToCommittee(addr crypto.Address) { m.TestJoinedValidators[addr] = true } func (m *MockSandbox) IsJoinedCommittee(addr crypto.Address) bool { return m.TestJoinedValidators[addr] } func (m *MockSandbox) MakeNewValidator(pub *bls.PublicKey) *validator.Validator { val := validator.NewValidator(pub, m.TestStore.TotalValidators()) return val } func (m *MockSandbox) UpdateValidator(val *validator.Validator) { m.TestStore.UpdateValidator(val) } func (m *MockSandbox) CurrentHeight() types.Height { return m.TestStore.LastHeight + 1 } func (*MockSandbox) IsMainnet() bool { return true } func (m *MockSandbox) Params() *param.Params { return m.TestParams } func (m *MockSandbox) IterateAccounts(consumer func(crypto.Address, *account.Account, bool)) { m.TestStore.IterateAccounts(func(addr crypto.Address, acc *account.Account) bool { consumer(addr, acc, true) return false }) } func (m *MockSandbox) IterateValidators(consumer func(*validator.Validator, bool, bool)) { m.TestStore.IterateValidators(func(val *validator.Validator) bool { consumer(val, true, m.TestJoinedValidators[val.Address()]) return false }) } func (m *MockSandbox) Committee() committee.Reader { return m.TestCommittee } func (m *MockSandbox) UpdatePowerDelta(delta int64) { m.TestPowerDelta += delta } func (m *MockSandbox) PowerDelta() int64 { return m.TestPowerDelta } func (m *MockSandbox) VerifyProof(types.Height, sortition.Proof, *validator.Validator) bool { return m.TestAcceptSortition } func (m *MockSandbox) CommitTransaction(trx *tx.Tx) { m.TestCommittedTrxs[trx.ID()] = trx } func (m *MockSandbox) AccumulatedFee() amount.Amount { return m.ts.RandAmount() } func (*MockSandbox) IsBanned(crypto.Address) bool { return false } ================================================ FILE: sandbox/sandbox.go ================================================ package sandbox import ( "sync" "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/logger" ) var _ Sandbox = &sandbox{} type sandbox struct { lk sync.RWMutex store store.Reader committee committee.Reader accounts map[crypto.Address]*sandboxAccount validators map[crypto.Address]*sandboxValidator committedTrxs map[tx.ID]*tx.Tx params *param.Params isMainnet bool height types.Height totalAccounts int32 totalValidators int32 totalPower int64 powerDelta int64 accumulatedFee amount.Amount } type sandboxValidator struct { validator *validator.Validator updated bool joined bool // Is joined committee } type sandboxAccount struct { account *account.Account updated bool } func NewSandbox(height types.Height, store store.Reader, params *param.Params, committee committee.Reader, totalPower int64, isMainnet bool, ) Sandbox { sbx := &sandbox{ height: height, store: store, committee: committee, totalPower: totalPower, params: params, isMainnet: isMainnet, } sbx.accounts = make(map[crypto.Address]*sandboxAccount) sbx.validators = make(map[crypto.Address]*sandboxValidator) sbx.committedTrxs = make(map[tx.ID]*tx.Tx) sbx.totalAccounts = sbx.store.TotalAccounts() sbx.totalValidators = sbx.store.TotalValidators() return sbx } func (*sandbox) shouldPanicForDuplicatedAddress() { // // Why is it necessary to panic here? // // An attempt is made to create a new item that already exists in the store. // logger.Panic("duplicated address") } func (*sandbox) shouldPanicForUnknownAddress() { // // Why is it necessary to panic here? // // We only update accounts or validators that are already present within the sandbox. // This can be achieved either by creating a new account using MakeNewAccount or // retrieving it from the store using Account. // logger.Panic("unknown address") } func (sb *sandbox) Account(addr crypto.Address) *account.Account { sb.lk.Lock() defer sb.lk.Unlock() s, ok := sb.accounts[addr] if ok { return s.account.Clone() } acc, err := sb.store.Account(addr) if err != nil { return nil } sb.accounts[addr] = &sandboxAccount{ account: acc, } return acc.Clone() } func (sb *sandbox) MakeNewAccount(addr crypto.Address) *account.Account { sb.lk.Lock() defer sb.lk.Unlock() if sb.store.HasAccount(addr) { sb.shouldPanicForDuplicatedAddress() } acc := account.NewAccount(sb.totalAccounts) sb.accounts[addr] = &sandboxAccount{ account: acc, updated: true, } sb.totalAccounts++ return acc.Clone() } // This function takes ownership of the account pointer. // It is important that the caller should not modify the account data and // keep it immutable. func (sb *sandbox) UpdateAccount(addr crypto.Address, acc *account.Account) { sb.lk.Lock() defer sb.lk.Unlock() s, ok := sb.accounts[addr] if !ok { sb.shouldPanicForUnknownAddress() } s.account = acc s.updated = true } func (sb *sandbox) RecentTransaction(txID tx.ID) bool { if sb.committedTrxs[txID] != nil { return true } return sb.store.RecentTransaction(txID) } func (sb *sandbox) Validator(addr crypto.Address) *validator.Validator { sb.lk.Lock() defer sb.lk.Unlock() s, ok := sb.validators[addr] if ok { return s.validator.Clone() } val, err := sb.store.Validator(addr) if err != nil { return nil } sb.validators[addr] = &sandboxValidator{ validator: val, } return val.Clone() } func (sb *sandbox) JoinedToCommittee(addr crypto.Address) { sb.lk.Lock() defer sb.lk.Unlock() s, ok := sb.validators[addr] if !ok { sb.shouldPanicForUnknownAddress() } s.joined = true } func (sb *sandbox) IsJoinedCommittee(addr crypto.Address) bool { sb.lk.Lock() defer sb.lk.Unlock() s, ok := sb.validators[addr] if ok { return s.joined } return false } func (sb *sandbox) MakeNewValidator(pub *bls.PublicKey) *validator.Validator { sb.lk.Lock() defer sb.lk.Unlock() addr := pub.ValidatorAddress() if sb.store.HasValidator(addr) { sb.shouldPanicForDuplicatedAddress() } val := validator.NewValidator(pub, sb.totalValidators) sb.validators[addr] = &sandboxValidator{ validator: val, updated: true, } sb.totalValidators++ return val.Clone() } // This function takes ownership of the validator pointer. // It is important that the caller should not modify the validator data and // keep it immutable. func (sb *sandbox) UpdateValidator(val *validator.Validator) { sb.lk.Lock() defer sb.lk.Unlock() addr := val.Address() sbVal, ok := sb.validators[addr] if !ok { sb.shouldPanicForUnknownAddress() } sbVal.validator = val sbVal.updated = true } func (sb *sandbox) Params() *param.Params { return sb.params } func (sb *sandbox) CurrentHeight() types.Height { sb.lk.RLock() defer sb.lk.RUnlock() return sb.height + 1 } func (sb *sandbox) IsMainnet() bool { return sb.isMainnet } func (sb *sandbox) IterateAccounts( consumer func(crypto.Address, *account.Account, bool), ) { sb.lk.RLock() defer sb.lk.RUnlock() for addr, sa := range sb.accounts { consumer(addr, sa.account, sa.updated) } } func (sb *sandbox) IterateValidators( consumer func(*validator.Validator, bool, bool), ) { sb.lk.RLock() defer sb.lk.RUnlock() for _, sv := range sb.validators { consumer(sv.validator, sv.updated, sv.joined) } } func (sb *sandbox) Committee() committee.Reader { return sb.committee } // UpdatePowerDelta updates the change in the total power of the blockchain. // The delta is the amount of change in the total power and can be either positive or negative. func (sb *sandbox) UpdatePowerDelta(delta int64) { sb.lk.Lock() defer sb.lk.Unlock() sb.powerDelta += delta } func (sb *sandbox) PowerDelta() int64 { sb.lk.RLock() defer sb.lk.RUnlock() return sb.powerDelta } // VerifyProof verifies proof of a sortition transaction. func (sb *sandbox) VerifyProof(blockHeight types.Height, proof sortition.Proof, val *validator.Validator) bool { sb.lk.RLock() defer sb.lk.RUnlock() seed := sb.store.SortitionSeed(blockHeight) if seed == nil { return false } return sortition.VerifyProof(*seed, proof, val.PublicKey(), sb.totalPower, val.Power()) } func (sb *sandbox) CommitTransaction(trx *tx.Tx) { sb.lk.Lock() defer sb.lk.Unlock() sb.committedTrxs[trx.ID()] = trx sb.accumulatedFee += trx.Fee() } func (sb *sandbox) AccumulatedFee() amount.Amount { sb.lk.RLock() defer sb.lk.RUnlock() return sb.accumulatedFee } func (sb *sandbox) IsBanned(addr crypto.Address) bool { sb.lk.RLock() defer sb.lk.RUnlock() return sb.store.IsBanned(addr) } ================================================ FILE: sandbox/sandbox_test.go ================================================ package sandbox import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) type testData struct { *testsuite.TestSuite valKeys []*bls.ValidatorKey store *store.MockStore sbx *sandbox } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) mockStore := store.MockingStore(ts) genDoc := genesis.MainnetGenesis() cmt, valKeys := ts.GenerateTestCommittee(21) acc := account.NewAccount(0) acc.AddToBalance(21 * 1e14) mockStore.UpdateAccount(crypto.TreasuryAddress, acc) totalPower := int64(0) for _, val := range cmt.Validators() { // For testing purpose, we create some test accounts first. // Account number is the validator number plus one, // since account #0 is the Treasury account. newAcc := account.NewAccount(val.Number() + 1) mockStore.UpdateValidator(val) mockStore.UpdateAccount(val.Address(), newAcc) totalPower += val.Power() } lastHeight := types.Height(21) for height := types.Height(1); height < lastHeight; height++ { blk, cert := ts.GenerateTestBlock(height) mockStore.SaveBlock(blk, cert) } sbx := NewSandbox(mockStore.LastHeight, mockStore, param.FromGenesis(genDoc), cmt, totalPower, true).(*sandbox) assert.Equal(t, lastHeight, sbx.CurrentHeight()) assert.Equal(t, param.FromGenesis(genDoc), sbx.Params()) return &testData{ TestSuite: ts, valKeys: valKeys, store: mockStore, sbx: sbx, } } func TestAccountChange(t *testing.T) { td := setup(t) t.Run("Should returns nil for invalid address", func(t *testing.T) { invAddr := td.RandAccAddress() assert.Nil(t, td.sbx.Account(invAddr)) td.sbx.IterateAccounts(func(_ crypto.Address, _ *account.Account, _ bool) { panic("should be empty") }) }) t.Run("Retrieve an account from store and update it", func(t *testing.T) { acc, addr := td.GenerateTestAccount() bal := acc.Balance() td.store.UpdateAccount(addr, acc) sbAcc1 := td.sbx.Account(addr) assert.Equal(t, acc, sbAcc1) sbAcc1.AddToBalance(1) assert.False(t, td.sbx.accounts[addr].updated) assert.Equal(t, bal, td.sbx.Account(addr).Balance()) td.sbx.UpdateAccount(addr, sbAcc1) assert.True(t, td.sbx.accounts[addr].updated) assert.Equal(t, bal+1, td.sbx.Account(addr).Balance()) t.Run("Update the same account again", func(t *testing.T) { sbAcc2 := td.sbx.Account(addr) sbAcc2.AddToBalance(1) assert.True(t, td.sbx.accounts[addr].updated, "it is updated before") assert.Equal(t, bal+1, td.sbx.Account(addr).Balance()) td.sbx.UpdateAccount(addr, sbAcc2) assert.True(t, td.sbx.accounts[addr].updated) assert.Equal(t, bal+2, td.sbx.Account(addr).Balance()) }) t.Run("Should be iterated", func(t *testing.T) { td.sbx.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { assert.Equal(t, addr, a) assert.True(t, updated) assert.Equal(t, bal+2, acc.Balance()) }) }) }) t.Run("Make new account", func(t *testing.T) { addr := td.RandAccAddress() acc := td.sbx.MakeNewAccount(addr) acc.AddToBalance(1) td.sbx.UpdateAccount(addr, acc) sbAcc := td.sbx.Account(addr) assert.Equal(t, acc, sbAcc) t.Run("Should be iterated", func(t *testing.T) { td.sbx.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { if a == addr { assert.True(t, updated) assert.Equal(t, amount.Amount(1), acc.Balance()) } }) }) }) } func TestRecentTransaction(t *testing.T) { td := setup(t) randTx1 := td.GenerateTestTransferTx() randTx2 := td.GenerateTestTransferTx() td.sbx.CommitTransaction(randTx1) td.sbx.CommitTransaction(randTx2) assert.True(t, td.sbx.RecentTransaction(randTx1.ID())) assert.True(t, td.sbx.RecentTransaction(randTx2.ID())) totalTxFees := randTx1.Fee() + randTx2.Fee() assert.Equal(t, totalTxFees, td.sbx.AccumulatedFee()) } func TestValidatorChange(t *testing.T) { td := setup(t) t.Run("Should returns nil for invalid address", func(t *testing.T) { invAddr := td.RandAccAddress() assert.Nil(t, td.sbx.Validator(invAddr)) td.sbx.IterateValidators(func(_ *validator.Validator, _ bool, _ bool) { panic("should be empty") }) }) t.Run("Retrieve an validator from store and update it", func(t *testing.T) { val := td.GenerateTestValidator() addr := val.Address() stk := val.Stake() td.store.UpdateValidator(val) sbVal1 := td.sbx.Validator(addr) assert.Equal(t, val.Hash(), sbVal1.Hash()) sbVal1.AddToStake(1) assert.False(t, td.sbx.validators[addr].updated) assert.Equal(t, stk, td.sbx.Validator(addr).Stake()) td.sbx.UpdateValidator(sbVal1) assert.True(t, td.sbx.validators[sbVal1.Address()].updated) assert.Equal(t, stk+1, td.sbx.Validator(addr).Stake()) t.Run("Update the same validator again", func(t *testing.T) { sbVal2 := td.sbx.Validator(addr) sbVal2.AddToStake(1) assert.True(t, td.sbx.validators[addr].updated, "it is updated before") assert.Equal(t, stk+1, td.sbx.Validator(addr).Stake()) td.sbx.UpdateValidator(sbVal2) assert.True(t, td.sbx.validators[sbVal1.Address()].updated) assert.Equal(t, stk+2, td.sbx.Validator(addr).Stake()) }) t.Run("Should be iterated", func(t *testing.T) { td.sbx.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { assert.True(t, updated) assert.False(t, joined) assert.Equal(t, stk+2, val.Stake()) }) }) }) t.Run("Make new validator", func(t *testing.T) { pub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(pub) val.AddToStake(1) td.sbx.UpdateValidator(val) sbVal := td.sbx.Validator(val.Address()) assert.Equal(t, val, sbVal) t.Run("Should be iterated", func(t *testing.T) { td.sbx.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { if val.PublicKey() == pub { assert.True(t, updated) assert.False(t, joined) assert.Equal(t, amount.Amount(1), val.Stake()) } }) }) }) } func TestTotalAccountCounter(t *testing.T) { td := setup(t) t.Run("Should update total account counter", func(t *testing.T) { totalAccs := td.store.TotalAccounts() acc1 := td.sbx.MakeNewAccount(td.RandAccAddress()) assert.Equal(t, totalAccs, acc1.Number()) acc2 := td.sbx.MakeNewAccount(td.RandAccAddress()) assert.Equal(t, totalAccs+1, acc2.Number()) }) } func TestTotalValidatorCounter(t *testing.T) { td := setup(t) t.Run("Should update total validator counter", func(t *testing.T) { totalVals := td.store.TotalValidators() pub, _ := td.RandBLSKeyPair() pub2, _ := td.RandBLSKeyPair() val1 := td.sbx.MakeNewValidator(pub) assert.Equal(t, totalVals, val1.Number()) val2 := td.sbx.MakeNewValidator(pub2) assert.Equal(t, totalVals+1, val2.Number()) }) } func TestCreateDuplicated(t *testing.T) { td := setup(t) t.Run("Try creating duplicated account, Should panic", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("The code did not panic") } }() addr := crypto.TreasuryAddress td.sbx.MakeNewAccount(addr) }) t.Run("Try creating duplicated validator, Should panic", func(t *testing.T) { assert.Panics(t, func() { pub := td.valKeys[3].PublicKey() td.sbx.MakeNewValidator(pub) }) }) } func TestUpdateFromOutsideTheSandbox(t *testing.T) { td := setup(t) t.Run("Try update an account from outside the sandbox, Should panic", func(t *testing.T) { assert.Panics(t, func() { acc, addr := td.GenerateTestAccount() td.sbx.UpdateAccount(addr, acc) }) }) t.Run("Try update a validator from outside the sandbox, Should panic", func(t *testing.T) { assert.Panics(t, func() { val := td.GenerateTestValidator() td.sbx.UpdateValidator(val) }) }) } func TestAccountDeepCopy(t *testing.T) { td := setup(t) t.Run("non existing account", func(t *testing.T) { addr := td.RandAccAddress() acc := td.sbx.MakeNewAccount(addr) acc.AddToBalance(1) assert.NotEqual(t, acc, td.sbx.Account(addr)) }) t.Run("existing account", func(t *testing.T) { addr := crypto.TreasuryAddress acc := td.sbx.Account(addr) acc.AddToBalance(1) assert.NotEqual(t, acc, td.sbx.Account(addr)) }) t.Run("sandbox account", func(t *testing.T) { addr := crypto.TreasuryAddress acc := td.sbx.Account(addr) acc.AddToBalance(1) assert.NotEqual(t, acc, td.sbx.Account(addr)) }) } func TestValidatorDeepCopy(t *testing.T) { td := setup(t) t.Run("non existing validator", func(t *testing.T) { pub, _ := td.RandBLSKeyPair() val := td.sbx.MakeNewValidator(pub) val.AddToStake(1) assert.NotEqual(t, val, td.sbx.Validator(pub.ValidatorAddress())) }) val0, _ := td.store.ValidatorByNumber(0) addr := val0.Address() t.Run("existing validator", func(t *testing.T) { val := td.sbx.Validator(addr) val.AddToStake(1) assert.NotEqual(t, val, td.sbx.Validator(addr)) }) t.Run("sandbox validator", func(t *testing.T) { val := td.sbx.Validator(addr) val.AddToStake(1) assert.NotEqual(t, val, td.sbx.Validator(addr)) }) } func TestPowerDelta(t *testing.T) { td := setup(t) assert.Zero(t, td.sbx.PowerDelta()) td.sbx.UpdatePowerDelta(1) assert.Equal(t, int64(1), td.sbx.PowerDelta()) td.sbx.UpdatePowerDelta(-1) assert.Zero(t, td.sbx.PowerDelta()) } func TestVerifyProof(t *testing.T) { td := setup(t) lastCert := td.store.LastCertificate() lastHeight := lastCert.Height() vals := td.sbx.committee.Validators() // Try to evaluate a valid sortition var validProof sortition.Proof var validLockTime types.Height var validVal *validator.Validator for height := lastHeight; height > 0; height-- { block := td.store.Blocks[height] for index, valKey := range td.valKeys { ok, proof := sortition.EvaluateSortition( block.Header().SortitionSeed(), valKey.PrivateKey(), td.sbx.totalPower, vals[index].Power()) if ok { validProof = proof validLockTime = height validVal = vals[index] } } } t.Run("invalid proof", func(t *testing.T) { invalidProof := td.RandProof() assert.False(t, td.sbx.VerifyProof(validLockTime, invalidProof, validVal)) }) t.Run("invalid height", func(t *testing.T) { assert.False(t, td.sbx.VerifyProof(td.RandHeight(), validProof, validVal)) }) t.Run("genesis block height", func(t *testing.T) { assert.False(t, td.sbx.VerifyProof(0, validProof, validVal)) }) t.Run("Ok", func(t *testing.T) { assert.True(t, td.sbx.VerifyProof(validLockTime, validProof, validVal)) }) } ================================================ FILE: scripts/snapshot.py ================================================ # Pactus Blockchain Snapshot tool # # This script first stops the Pactus node if it is running, then creates a backup of the blockchain data by copying # or compressing it based on the specified options. The backup is stored in a timestamped snapshot directory along # with a `metadata.json` file that contains detailed information about the snapshot, including file paths and # checksums. Finally, the script manages the retention of snapshots, ensuring only a specified number of recent # backups are kept. # # Arguments # # - `--service_path`: This argument specifies the path to the `pactus` service file to manage systemctl service. # - `--data_path`: This argument specifies the path to the Pactus data folder to create snapshots. # - Windows: `C:\Users\{user}\pactus\data` # - Linux or Mac: `/home/{user}/pactus/data` # - `--compress`: This argument specifies the compression method based on your choice ['none', 'zip', 'tar'], # with 'none' being without compression. # - `--retention`: This argument sets the number of snapshots to keep. # - `--snapshot_path`: This argument sets a custom path for snapshots, with the default being the current # working directory of the script. # # How to run? # # For create snapshots just run this command: # # sudo python3 snapshot.py --service_path /etc/systemd/system/pactus.service --data_path /home/{user}/pactus/data # --compress zip --retention 3 import argparse import os import shutil import subprocess import hashlib import json import logging import zipfile import time from datetime import datetime def setup_logging(): logging.basicConfig( format="[%(asctime)s] %(message)s", datefmt="%Y-%m-%d-%H:%M", level=logging.INFO ) def get_timestamp_str(): return datetime.now().strftime("%Y%m%d%H%M%S") def get_current_time_iso(): return datetime.now().isoformat() class Metadata: @staticmethod def sha256(file_path): hash_sha = hashlib.sha256() with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha.update(chunk) return hash_sha.hexdigest() @staticmethod def update_metadata_file(snapshot_path, snapshot_metadata): metadata_file = os.path.join(snapshot_path, "metadata.json") if os.path.isfile(metadata_file): logging.info(f"Updating existing metadata file '{metadata_file}'") with open(metadata_file, "r") as f: metadata = json.load(f) else: logging.info(f"Creating new metadata file '{metadata_file}'") metadata = [] formatted_metadata = { "name": snapshot_metadata["name"], "created_at": snapshot_metadata["created_at"], "compress": snapshot_metadata["compress"], "data": snapshot_metadata["data"], } metadata.append(formatted_metadata) with open(metadata_file, "w") as f: json.dump(metadata, f, indent=4) @staticmethod def update_metadata_after_removal(snapshots_dir, removed_snapshots): metadata_file = os.path.join(snapshots_dir, "metadata.json") if not os.path.isfile(metadata_file): return logging.info(f"Updating metadata file '{metadata_file}' after snapshot removal") with open(metadata_file, "r") as f: metadata = json.load(f) updated_metadata = [ entry for entry in metadata if entry["name"] not in removed_snapshots ] with open(metadata_file, "w") as f: json.dump(updated_metadata, f, indent=4) @staticmethod def create_snapshot_json(data_dir, snapshot_subdir): files = [] for root, _, filenames in os.walk(data_dir): for filename in filenames: file_path = os.path.join(root, filename) rel_path = os.path.relpath(file_path, data_dir) snapshot_rel_path = os.path.join(snapshot_subdir, rel_path).replace( "\\", "/" ) file_info = { "name": filename, "path": snapshot_rel_path, "sha": Metadata.sha256(file_path), } files.append(file_info) return {"data": files} @staticmethod def create_compressed_snapshot_json(compressed_file, rel_path): compressed_file_size = os.path.getsize(compressed_file) file_info = { "name": os.path.basename(compressed_file), "path": rel_path, "sha": Metadata.sha256(compressed_file), "size": compressed_file_size, } return {"data": file_info} def run_command(command): logging.info(f"Running command: {' '.join(command)}") try: result = subprocess.run( command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) if result.stdout.strip(): logging.info(f"Command output: {result.stdout.strip()}") if result.stderr.strip(): # Downgrade from error to info for successful commands logging.info(f"Command stderr: {result.stderr.strip()}") return result.stdout.strip() except subprocess.CalledProcessError as e: logging.error(f"Command failed with error: {e.stderr.strip()}") return f"Error: {e.stderr.strip()}" def get_service_name(service_path): base_name = os.path.basename(service_path) service_name = os.path.splitext(base_name)[0] return service_name class DaemonManager: @staticmethod def start_service(service_path=None, docker_compose_path=None, docker_service_name=None): if docker_compose_path and docker_service_name: logging.info(f"Starting Docker Compose service '{docker_service_name}' at '{docker_compose_path}'") return run_command(["docker", "compose", "-f", docker_compose_path, "start", docker_service_name]) elif service_path: sv = get_service_name(service_path) logging.info(f"Starting systemctl service '{sv}'") return run_command(["sudo", "systemctl", "start", sv]) return None @staticmethod def stop_service(service_path=None, docker_compose_path=None, docker_service_name=None): if docker_compose_path and docker_service_name: logging.info(f"Stopping Docker Compose service '{docker_service_name}' at '{docker_compose_path}'") return run_command(["docker", "compose", "-f", docker_compose_path, "stop", docker_service_name]) elif service_path: sv = get_service_name(service_path) logging.info(f"Stopping systemctl service '{sv}'") return run_command(["sudo", "systemctl", "stop", sv]) return None class SnapshotManager: def __init__(self, args): self.args = args def manage_snapshots(self): snapshots_dir = self.args.snapshot_path logging.info(f"Managing snapshots in '{snapshots_dir}'") if not os.path.exists(snapshots_dir): logging.info( f"Snapshots directory '{snapshots_dir}' does not exist. Creating it." ) os.makedirs(snapshots_dir) snapshots = sorted( [s for s in os.listdir(snapshots_dir) if s != "metadata.json"] ) logging.info(f"Found snapshots: {snapshots}") logging.info(f"Retention policy is to keep {self.args.retention} snapshots") if len(snapshots) >= self.args.retention: num_to_remove = len(snapshots) - self.args.retention + 1 to_remove = snapshots[:num_to_remove] logging.info(f"Snapshots to remove: {to_remove}") for snapshot in to_remove: snapshot_path = os.path.join(snapshots_dir, snapshot) logging.info(f"Removing old snapshot '{snapshot_path}'") shutil.rmtree(snapshot_path) Metadata.update_metadata_after_removal(snapshots_dir, to_remove) def create_snapshot(self): timestamp_str = get_timestamp_str() snapshot_dir = os.path.join(self.args.snapshot_path, timestamp_str) logging.info(f"Creating snapshot directory '{snapshot_dir}'") os.makedirs(snapshot_dir, exist_ok=True) data_dir = os.path.join(snapshot_dir, "data") if self.args.compress == "none": logging.info(f"Copying data from '{self.args.data_path}' to '{data_dir}'") shutil.copytree(self.args.data_path, data_dir) snapshot_metadata = Metadata.create_snapshot_json(data_dir, timestamp_str) elif self.args.compress == "zip": zip_file = os.path.join(snapshot_dir, "data.zip") rel = os.path.relpath(zip_file, snapshot_dir) meta_path = os.path.join(timestamp_str, rel) logging.info(f"Creating ZIP archive '{zip_file}'") with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zipf: for root, _, files in os.walk(self.args.data_path): for file in files: full_path = os.path.join(root, file) rel_path = os.path.relpath(full_path, self.args.data_path) zipf.write(full_path, os.path.join("data", rel_path)) snapshot_metadata = Metadata.create_compressed_snapshot_json( zip_file, meta_path ) elif self.args.compress == "tar": tar_file = os.path.join(snapshot_dir, "data.tar.gz") rel = os.path.relpath(tar_file, snapshot_dir) meta_path = os.path.join(timestamp_str, rel) logging.info(f"Creating TAR.GZ archive '{tar_file}'") subprocess.run(["tar", "-czvf", tar_file, "-C", self.args.data_path, "."]) snapshot_metadata = Metadata.create_compressed_snapshot_json( tar_file, meta_path ) snapshot_metadata["name"] = timestamp_str snapshot_metadata["created_at"] = get_current_time_iso() snapshot_metadata["compress"] = self.args.compress Metadata.update_metadata_file(self.args.snapshot_path, snapshot_metadata) class Validation: @staticmethod def validate_args(args): logging.info("Validating arguments") # Ensure at least one service method is provided if not args.service_path and not args.docker_compose_path: raise ValueError("Either --service_path or --docker_compose_path must be provided.") # Validate systemctl service path if provided if args.service_path: if not os.path.isfile(args.service_path): raise ValueError(f"Service file '{args.service_path}' does not exist.") logging.info(f"Service file '{args.service_path}' exists") # Validate docker-compose if provided if args.docker_compose_path: if not os.path.isfile(args.docker_compose_path): raise ValueError(f"Docker Compose file '{args.docker_compose_path}' does not exist.") if not args.docker_service_name: raise ValueError("--docker_service_name is required when using --docker_compose_path") logging.info(f"Docker Compose file '{args.docker_compose_path}' exists") logging.info(f"Docker service name is '{args.docker_service_name}'") # Common validations if not os.path.isdir(args.data_path): raise ValueError(f"Data path '{args.data_path}' does not exist.") logging.info(f"Data path '{args.data_path}' exists") if not os.access(args.data_path, os.W_OK): raise PermissionError( f"No permission to access data path '{args.data_path}'." ) logging.info(f"Permission to access data path '{args.data_path}' confirmed") if args.compress == "zip" and not shutil.which("zip"): raise EnvironmentError("The 'zip' command is not available.") elif args.compress == "zip": logging.info("The 'zip' command is available") if args.compress == "tar" and not shutil.which("tar"): raise EnvironmentError("The 'tar' command is not available.") elif args.compress == "tar": logging.info("The 'tar' command is available") if args.retention <= 0: raise ValueError("Retention value must be greater than 0.") logging.info(f"Retention value is set to {args.retention}") if not os.access(args.snapshot_path, os.W_OK): raise PermissionError( f"No permission to access snapshot path '{args.snapshot_path}'." ) logging.info( f"Permission to access snapshot path '{args.snapshot_path}' confirmed" ) if not os.path.isdir(args.snapshot_path): logging.info("Snapshots directory does not exist, creating it") os.makedirs(args.snapshot_path) else: logging.info("Snapshots directory exists") class ProcessBackup: def __init__(self, args): self.args = args Validation.validate_args(self.args) def run(self): DaemonManager.stop_service( service_path=self.args.service_path, docker_compose_path=self.args.docker_compose_path, docker_service_name=self.args.docker_service_name ) # sleeps for 5 seconds time.sleep(5) snapshot_manager = SnapshotManager(self.args) snapshot_manager.manage_snapshots() snapshot_manager.create_snapshot() DaemonManager.start_service( service_path=self.args.service_path, docker_compose_path=self.args.docker_compose_path, docker_service_name=self.args.docker_service_name ) def parse_args(): user_home = os.path.expanduser("~") default_data_path = os.path.join(user_home, "pactus") parser = argparse.ArgumentParser(description="Pactus Blockchain Snapshot Tool") parser.add_argument( "--service_path", help="Path to pactus systemctl service" ) parser.add_argument( "--docker_compose_path", help="Path to docker-compose.yml file to manage Docker-based service" ) parser.add_argument( "--docker_service_name", help="Name of the Docker service in the Compose file" ) parser.add_argument( "--data_path", default=default_data_path, help="Path to data directory" ) parser.add_argument( "--compress", choices=["none", "zip", "tar"], default="none", help="Compression type", ) parser.add_argument( "--retention", type=int, default=3, help="Number of snapshots to retain" ) parser.add_argument( "--snapshot_path", default=os.getcwd(), help="Path to store snapshots" ) return parser.parse_args() def main(): setup_logging() args = parse_args() process_backup = ProcessBackup(args) process_backup.run() if __name__ == "__main__": main() ================================================ FILE: sortition/proof.go ================================================ package sortition import ( "encoding/hex" "errors" ) type Proof [48]byte func ProofFromString(text string) (Proof, error) { data, err := hex.DecodeString(text) if err != nil { return Proof{}, err } return ProofFromBytes(data) } func ProofFromBytes(data []byte) (Proof, error) { if len(data) != 48 { return Proof{}, errors.New("invalid proof length") } p := Proof{} copy(p[:], data) return p, nil } ================================================ FILE: sortition/proof_test.go ================================================ package sortition import ( "testing" "github.com/stretchr/testify/require" ) func TestProofFromString(t *testing.T) { _, err := ProofFromString("inv") require.Error(t, err) _, err = ProofFromBytes([]byte{0}) require.Error(t, err) } ================================================ FILE: sortition/seed.go ================================================ package sortition import ( "encoding/hex" "errors" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" ) type VerifiableSeed [48]byte var UndefVerifiableSeed = VerifiableSeed{} func VerifiableSeedFromString(text string) (VerifiableSeed, error) { data, err := hex.DecodeString(text) if err != nil { return UndefVerifiableSeed, err } return VerifiableSeedFromBytes(data) } func VerifiableSeedFromBytes(data []byte) (VerifiableSeed, error) { if len(data) != 48 { return UndefVerifiableSeed, errors.New("invalid seed length") } s := UndefVerifiableSeed copy(s[:], data) return s, nil } func (s *VerifiableSeed) GenerateNext(prv *bls.PrivateKey) VerifiableSeed { h := hash.CalcHash(s[:]) sig := prv.Sign(h.Bytes()) newSeed, _ := VerifiableSeedFromBytes(sig.Bytes()) return newSeed } func (s *VerifiableSeed) Verify(public *bls.PublicKey, prevSeed VerifiableSeed) bool { sig, err := bls.SignatureFromBytes(s[:]) if err != nil { return false } h := hash.CalcHash(prevSeed[:]) return public.Verify(h.Bytes(), sig) == nil } ================================================ FILE: sortition/seed_test.go ================================================ package sortition_test import ( "testing" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSeedFromString(t *testing.T) { _, err := sortition.VerifiableSeedFromString("inv") require.Error(t, err) _, err = sortition.VerifiableSeedFromBytes([]byte{0}) require.Error(t, err) } func TestValidate(t *testing.T) { ts := testsuite.NewTestSuite(t) valKey := ts.RandValKey() seed1 := ts.RandSeed() seed2 := seed1.GenerateNext(valKey.PrivateKey()) seed3 := sortition.VerifiableSeed{} seed4, _ := sortition.VerifiableSeedFromString( "C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") assert.True(t, seed2.Verify(valKey.PublicKey(), seed1)) assert.False(t, seed1.Verify(valKey.PublicKey(), seed2)) assert.False(t, seed2.Verify(valKey.PublicKey(), ts.RandSeed())) assert.False(t, seed3.Verify(valKey.PublicKey(), seed1)) assert.False(t, seed4.Verify(valKey.PublicKey(), seed1)) } ================================================ FILE: sortition/sortition.go ================================================ package sortition import ( "github.com/pactus-project/pactus/crypto/bls" ) func EvaluateSortition(seed VerifiableSeed, prv *bls.PrivateKey, total, threshold int64) (bool, Proof) { index, proof := Evaluate(seed, prv, uint64(total)) if int64(index) < threshold { return true, proof } return false, Proof{} } func VerifyProof(seed VerifiableSeed, proof Proof, pub *bls.PublicKey, total, threshold int64) bool { index, result := Verify(seed, pub, proof, uint64(total)) if !result { return false } return int64(index) < threshold } ================================================ FILE: sortition/sortition_test.go ================================================ package sortition_test import ( "fmt" "testing" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestEvaluation(t *testing.T) { ts := testsuite.NewTestSuite(t) prv, _ := bls.PrivateKeyFromString( "SECRET1P838V87AW42JS8YWLYYK0AYFJQ9445VR72H23D6LR7GEJ8KW9UQ0QVE8WHE") seed, _ := sortition.VerifiableSeedFromString( "b63179137423ab2da8279d7aa3726d7ad05ae7d3ab3f744db0a9a719d12a720e72dc1d1e9222360243007f2f4adf7009") valKey := bls.NewValidatorKey(prv) t.Run("Total stake is zero", func(t *testing.T) { threshold := ts.RandInt64Max(int64(1e14)) ok, proof := sortition.EvaluateSortition(seed, valKey.PrivateKey(), 0, threshold) require.True(t, ok) ok = sortition.VerifyProof(seed, proof, valKey.PublicKey(), 0, threshold) require.True(t, ok) }) t.Run("Total stake is not zero, but validator stake is zero", func(t *testing.T) { total := ts.RandInt64Max(int64(1e14)) ok, _ := sortition.EvaluateSortition(seed, valKey.PrivateKey(), total, 0) require.False(t, ok) }) t.Run("OK!", func(t *testing.T) { proof1, _ := sortition.ProofFromString( "8cb689ec126465ddadd32493b71dc7ee3bfa2ef5a0a0f4b9b8aa777fb915a5f88def3305a3579e97b96ac862a6d67316") total := int64(1 * 1e14) ok, proof2 := sortition.EvaluateSortition(seed, valKey.PrivateKey(), total, total/100) require.True(t, ok) require.Equal(t, proof1, proof2) require.True(t, sortition.VerifyProof(seed, proof1, valKey.PublicKey(), total, total/100)) require.False(t, sortition.VerifyProof(seed, proof1, valKey.PublicKey(), total, 0)) require.False(t, sortition.VerifyProof(seed, ts.RandProof(), valKey.PublicKey(), total, total/10)) require.False(t, sortition.VerifyProof(seed, sortition.Proof{}, valKey.PublicKey(), total, total/10)) require.False(t, sortition.VerifyProof(ts.RandSeed(), proof1, valKey.PublicKey(), total, total/10)) }) } func TestInvalidProof(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid proof (Zero proof)", func(t *testing.T) { total := ts.RandInt64Max(int64(1e14)) seed := ts.RandSeed() pub, _ := ts.RandBLSKeyPair() proof, _ := sortition.ProofFromString( "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") require.False(t, sortition.VerifyProof(seed, proof, pub, total, total)) }) t.Run("Invalid proof (Infinity proof)", func(t *testing.T) { total := ts.RandInt64Max(int64(1e14)) seed := ts.RandSeed() pub, _ := ts.RandBLSKeyPair() proof, _ := sortition.ProofFromString( "C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") require.False(t, sortition.VerifyProof(seed, proof, pub, total, total)) }) } func TestSortitionMedian(t *testing.T) { ts := testsuite.NewTestSuite(t) total := int64(1 * 1e9) valKey := ts.RandValKey() count := 1000 median := 0 for j := 0; j < count; j++ { seed := ts.RandSeed() ok, _ := sortition.EvaluateSortition(seed, valKey.PrivateKey(), total, total/10) if ok { median++ } } // Should be about 10% fmt.Printf("%v%% \n", median*100/count) assert.GreaterOrEqual(t, median*100/count, 5) assert.LessOrEqual(t, median*100/count, 15) assert.NotZero(t, median*100/count) } ================================================ FILE: sortition/vrf.go ================================================ package sortition import ( "math/big" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" ) var denominator *big.Int func init() { denominator = &big.Int{} denominator.SetString("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16) } // Evaluate returns a provable random number between [0, max) along with a proof. // It returns the random number and the proof that can regenerate the random number using // the public key of the signer, without revealing the private key. func Evaluate(seed VerifiableSeed, prv *bls.PrivateKey, max uint64) (uint64, Proof) { signData := make([]byte, 0, bls.SignatureSize+bls.PublicKeySize) signData = append(signData, seed[:]...) signData = append(signData, prv.PublicKey().Bytes()...) sig := prv.Sign(signData) proof, _ := ProofFromBytes(sig.Bytes()) index := GetIndex(proof, max) return index, proof } // Verify checks if the provided proof, based on the seed and public key, is valid. // If the proof is valid, it calculates the random number that // can be generated based on the given proof. func Verify(seed VerifiableSeed, pub *bls.PublicKey, proof Proof, max uint64) (uint64, bool) { proofSig, err := bls.SignatureFromBytes(proof[:]) if err != nil { return 0, false } // Verify signature (proof) signData := make([]byte, 0, bls.SignatureSize+bls.PublicKeySize) signData = append(signData, seed[:]...) signData = append(signData, pub.Bytes()...) if err := pub.Verify(signData, proofSig); err != nil { return 0, false } index := GetIndex(proof, max) return index, true } func GetIndex(proof Proof, max uint64) uint64 { hash := hash.CalcHash(proof[:]) // construct the numerator and denominator for normalizing the proof uint bigRnd := &big.Int{} bigMax := &big.Int{} numerator := &big.Int{} bigRnd.SetBytes(hash.Bytes()) bigMax.SetUint64(max) numerator = numerator.Mul(bigRnd, bigMax) // divide numerator and denominator to get the election ratio for this block height index := big.NewInt(0) index = index.Div(numerator, denominator) return index.Uint64() } ================================================ FILE: sortition/vrf_test.go ================================================ package sortition_test import ( "fmt" "testing" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestVRF(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, prv := ts.RandBLSKeyPair() valKey := bls.NewValidatorKey(prv) for i := 0; i < 100; i++ { seed := ts.RandSeed() t.Logf("seed is: %x \n", seed) maxSize := uint64(1 * 1e6) index, proof := sortition.Evaluate(seed, valKey.PrivateKey(), maxSize) assert.LessOrEqual(t, index, maxSize) index2, result := sortition.Verify(seed, pub, proof, maxSize) assert.True(t, result) assert.Equal(t, index, index2) } } // TestRandomUint64 exercises the randomness of the random number generator on // the system by ensuring the probability of the generated numbers. If the RNG // is evenly distributed as a proper cryptographic RNG should be, there really // should only be 1 number < 2^56 in 2^8 tries for a 64-bit number. However, // use a higher number of 5 to really ensure the test doesn't fail unless the // RNG is just horrendous. func TestRandomUint64(t *testing.T) { ts := testsuite.NewTestSuite(t) tries := 1 << 8 // 2^8 watermark := uint64(1 << 56) // 2^56 maxHits := 5 badRNG := "The random number generator on this system is clearly " + "terrible since we got %d values less than %d in %d runs " + "when only %d was expected" _, pv := ts.RandBLSKeyPair() valKey := bls.NewValidatorKey(pv) numHits := 0 for i := 0; i < tries; i++ { seed := ts.RandSeed() nonce, _ := sortition.Evaluate(seed, valKey.PrivateKey(), util.MaxUint64) if nonce < watermark { numHits++ } if numHits > maxHits { str := fmt.Sprintf(badRNG, numHits, watermark, tries, maxHits) t.Errorf("Random Uint64 iteration %d failed - %v", i, str) return } } } func TestGetIndex(t *testing.T) { // The expected values // // Total: 1,000,000 // // proof: 0x1719b896ec1cc66a0f44c4bf90890d988e341cb2c1a808907780af844c854291536c12fdaef9a526bb7ef80da17c0b03 // proofH: 0xa7b8166584387f4ea76f9caa0969bd6b0bb8df4c3bb8e87f8b6e4dad62bf3359 // // proofH * 1000000 / denominator = 655152.7021258341 proof1, _ := sortition.ProofFromString( "1719b896ec1cc66a0f44c4bf90890d988e341cb2c1a808907780af844c854291536c12fdaef9a526bb7ef80da17c0b03") assert.Equal(t, uint64(655152), sortition.GetIndex(proof1, 1*1e6)) // proof: 45180defab2daae377977bf09dcdd7d76ff4fc96d1b50cc8ac5a1601c0522fb11641c3ed0fefd4b1e1808c498d699396 // proofH: 80212979d1de1ca4ce1258fc0be66a4453b3804e64a5ca8d95f7def2c291c7fe // // proofH * 1000000 / denominator = 500506.0121928797 proof2, _ := sortition.ProofFromString( "45180defab2daae377977bf09dcdd7d76ff4fc96d1b50cc8ac5a1601c0522fb11641c3ed0fefd4b1e1808c498d699396") assert.Equal(t, uint64(500506), sortition.GetIndex(proof2, 1*1e6)) } ================================================ FILE: state/errors.go ================================================ package state import ( "errors" "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/vote" ) // ErrInvalidBlockVersion indicates that the block version is not valid. var ErrInvalidBlockVersion = errors.New("invalid block version") // ErrInvalidSubsidyTransaction indicates that the subsidy transaction is not valid. var ErrInvalidSubsidyTransaction = errors.New("invalid subsidy transaction") // ErrDuplicatedSubsidyTransaction indicates that there is more than one subsidy transaction // inside the block. var ErrDuplicatedSubsidyTransaction = errors.New("duplicated subsidy transaction") // ErrInvalidSortitionSeed indicates that the block's sortition seed is either invalid or unverifiable. var ErrInvalidSortitionSeed = errors.New("invalid sortition seed") // ErrInvalidCertificate indicates that the block certificate is invalid. var ErrInvalidCertificate = errors.New("invalid certificate") // InvalidSubsidyAmountError is returned when the amount of the subsidy transaction is not as expected. type InvalidSubsidyAmountError struct { Expected amount.Amount Got amount.Amount } func (e InvalidSubsidyAmountError) Error() string { return fmt.Sprintf("invalid subsidy amount, expected: %v, got: %v", e.Expected, e.Got) } // InvalidVoteForCertificateError is returned when an attempt to update // the last certificate with an invalid vote is made. type InvalidVoteForCertificateError struct { Vote *vote.Vote } func (e InvalidVoteForCertificateError) Error() string { return fmt.Sprintf("invalid vote to update the last certificate: %s", e.Vote.Type().String()) } // InvalidStateRootHashError is returned when the state root hash of the block // does not match the current state root hash. type InvalidStateRootHashError struct { Expected hash.Hash Got hash.Hash } func (e InvalidStateRootHashError) Error() string { return fmt.Sprintf("invalid state root hash, expected: %s, got: %s", e.Expected, e.Got) } // InvalidProposerError is returned when the block proposer is not as expected. type InvalidProposerError struct { Expected crypto.Address Got crypto.Address } func (e InvalidProposerError) Error() string { return fmt.Sprintf("invalid block proposer, expected: %s, got: %s", e.Expected, e.Got) } // InvalidBlockTimeError is returned when the block time is not valid. type InvalidBlockTimeError struct { Reason string } func (e InvalidBlockTimeError) Error() string { return fmt.Sprintf("invalid block time: %s", e.Reason) } ================================================ FILE: state/execution.go ================================================ package state import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/execution" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" ) func (st *state) executeBlock(blk *block.Block, sbx sandbox.Sandbox, check bool) error { proposerAddr := blk.Header().ProposerAddress() for i, trx := range blk.Transactions() { if check { // The first transaction should be subsidy transaction shouldBeSubsidyTx := (i == 0) err := st.checkSubsidy(trx, proposerAddr, shouldBeSubsidyTx) if err != nil { return err } err = execution.CheckAndExecute(trx, sbx, true) if err != nil { return err } } else { err := execution.Execute(trx, sbx) if err != nil { return err } } } subsidyTrx := blk.Transactions().Subsidy() accumulatedFee := sbx.AccumulatedFee() subsidyAmt := st.params.BlockReward + sbx.AccumulatedFee() if subsidyTrx.Payload().Value() != subsidyAmt { return InvalidSubsidyAmountError{ Expected: subsidyAmt, Got: subsidyTrx.Payload().Value(), } } // Claim accumulated fees acc := sbx.Account(crypto.TreasuryAddress) acc.AddToBalance(accumulatedFee) sbx.UpdateAccount(crypto.TreasuryAddress, acc) return nil } func (st *state) checkSubsidy(trx *tx.Tx, proposerAddr crypto.Address, shouldBeSubsidyTx bool) error { if !shouldBeSubsidyTx { if trx.IsSubsidyTx() { return ErrDuplicatedSubsidyTransaction } return nil } if !trx.IsSubsidyTx() { return ErrInvalidSubsidyTransaction } lockTime := trx.LockTime() batchTrx, ok := trx.Payload().(*payload.BatchTransferPayload) if !ok { return ErrInvalidSubsidyTransaction } if batchTrx.Recipients[0].Amount != st.params.FoundationReward { return ErrInvalidSubsidyTransaction } addressIndex := int(lockTime) % len(st.params.FoundationAddress) foundationAddress := st.params.FoundationAddress[addressIndex] if batchTrx.Recipients[0].To != foundationAddress { return ErrInvalidSubsidyTransaction } val, err := st.store.Validator(proposerAddr) if err != nil { return ErrInvalidSubsidyTransaction } if val.IsDelegated() { if val.DelegateShare() > 0 { if batchTrx.Recipients[1].To != val.DelegateOwner() || batchTrx.Recipients[1].Amount < val.DelegateShare() { return ErrInvalidSubsidyTransaction } } } else { // 2 recipients: foundation + validator if len(batchTrx.Recipients) != 2 { return ErrInvalidSubsidyTransaction } } return nil } ================================================ FILE: state/execution_test.go ================================================ package state import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/execution/executor" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestProposeBlock(t *testing.T) { td := setup(t) lockTime := td.state.LastBlockHeight() dupSubsidyTx := td.GenerateTestSubsidyTx(testsuite.TransactionWithLockTime(lockTime)) invTransferTx := td.GenerateTestTransferTx() invBondTx := td.GenerateTestBondTx() invSortitionTx := td.GenerateTestSortitionTx() validTrx1 := td.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(td.genAccKey)) validTrx2 := td.GenerateTestTransferTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithSigner(td.genAccKey)) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{ invTransferTx, invBondTx, invSortitionTx, dupSubsidyTx, validTrx1, validTrx2, }).Times(1) rewardAddr := td.RandAccAddress() proposerKey := td.proposerKey(t, 0) blk, err := td.state.ProposeBlock(proposerKey, rewardAddr) require.NoError(t, err) blockTrxs := blk.Transactions() rewardTrx := blockTrxs[0] assert.Equal(t, protocol.ProtocolVersionLatest, blk.Header().Version()) assert.Equal(t, td.state.Proposer(0).Address(), blk.Header().ProposerAddress()) assert.Equal(t, td.state.LastBlockHash(), blk.Header().PrevBlockHash()) assert.Equal(t, block.Txs{rewardTrx, validTrx1, validTrx2}, blockTrxs) assert.Equal(t, td.state.params.BlockReward+validTrx1.Fee()+validTrx2.Fee(), rewardTrx.Payload().Value()) } func TestExecuteBlock(t *testing.T) { td := setup(t) invTransferTx := td.GenerateTestTransferTx() validTx1 := td.GenerateTestTransferTx( testsuite.TransactionWithLockTime(1), testsuite.TransactionWithSigner(td.genAccKey)) blockHeight := td.state.LastBlockHeight() + 1 proposerAddr := td.proposerKey(t, 0).Address() invSubsidyTx := td.state.createSubsidyTx(proposerAddr, td.RandAccAddress(), validTx1.Fee()+1) validSubsidyTx := td.state.createSubsidyTx(proposerAddr, td.RandAccAddress(), validTx1.Fee()) t.Run("Block has invalid subsidy amount", func(t *testing.T) { txs := block.NewTxs() txs.Append(invSubsidyTx) txs.Append(validTx1) invBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(proposerAddr), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() err := td.state.executeBlock(invBlock, sb, true) require.ErrorIs(t, err, InvalidSubsidyAmountError{ Expected: 1e9 + validTx1.Fee(), Got: 1e9 + validTx1.Fee() + 1, }) }) t.Run("Block has an invalid transaction", func(t *testing.T) { txs := block.NewTxs() txs.Append(validSubsidyTx) txs.Append(invTransferTx) invBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(proposerAddr), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() err := td.state.executeBlock(invBlock, sb, true) require.ErrorIs(t, err, executor.AccountNotFoundError{ Address: invTransferTx.Payload().Signer(), }) }) t.Run("Subsidy is not first transaction in block", func(t *testing.T) { txs := block.NewTxs() txs.Append(validTx1) txs.Append(validSubsidyTx) invBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(proposerAddr), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() err := td.state.executeBlock(invBlock, sb, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Block has no subsidy transaction", func(t *testing.T) { txs := block.NewTxs() txs.Append(validTx1) invBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(proposerAddr), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() err := td.state.executeBlock(invBlock, sb, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Block has two subsidy transactions", func(t *testing.T) { txs := block.NewTxs() txs.Append(validSubsidyTx) txs.Append(validSubsidyTx) invBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(proposerAddr), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() err := td.state.executeBlock(invBlock, sb, true) require.ErrorIs(t, err, ErrDuplicatedSubsidyTransaction) }) t.Run("Block has invalid proposer", func(t *testing.T) { txs := block.NewTxs() txs.Append(validSubsidyTx) txs.Append(validTx1) invBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(td.RandValAddress()), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() err := td.state.executeBlock(invBlock, sb, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("OK", func(t *testing.T) { txs := block.NewTxs() txs.Append(validSubsidyTx) txs.Append(validTx1) validBlock, _ := td.GenerateTestBlock(blockHeight, testsuite.BlockWithProposer(proposerAddr), testsuite.BlockWithStateHash(td.state.stateRoot()), testsuite.BlockWithPrevCert(td.state.lastInfo.Certificate()), testsuite.BlockWithPrevHash(td.state.lastInfo.BlockHash()), testsuite.BlockWithSeed(td.state.lastInfo.SortitionSeed()), testsuite.BlockWithTransactions(txs)) sb := td.state.concreteSandbox() require.NoError(t, td.state.executeBlock(validBlock, sb, true)) // Check if fee is claimed treasury := sb.Account(crypto.TreasuryAddress) assert.Equal(t, 21*1e15-(amount.Amount(blockHeight)*td.state.params.BlockReward), treasury.Balance()) }) } func TestSubsidyTransaction(t *testing.T) { td := setup(t) proposerAddr := td.state.Proposer(0).Address() t.Run("Legacy Reward", func(t *testing.T) { trx := tx.NewTransferTx(td.RandHeight(), crypto.TreasuryAddress, td.RandAccAddress(), td.RandAmount(), 0) err := td.state.checkSubsidy(trx, proposerAddr, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Split Reward With No Foundation Address", func(t *testing.T) { recipients := []payload.BatchRecipient{ { To: td.RandAccAddress(), Amount: td.RandAmount(), }, } trx := td.GenerateTestSubsidyTx(testsuite.TransactionWithRecipients(recipients)) err := td.state.checkSubsidy(trx, proposerAddr, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Split Reward With Invalid Foundation Address", func(t *testing.T) { recipients := []payload.BatchRecipient{ { To: td.RandAccAddress(), Amount: td.state.params.FoundationReward, }, { To: td.RandAccAddress(), Amount: td.RandAmount(), }, } trx := td.GenerateTestSubsidyTx(testsuite.TransactionWithRecipients(recipients)) err := td.state.checkSubsidy(trx, proposerAddr, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Split Reward: Ok", func(t *testing.T) { lockTime := td.RandHeight() recipients := []payload.BatchRecipient{ { To: td.state.params.FoundationAddress[lockTime%100], Amount: td.state.params.FoundationReward, }, { To: td.RandAccAddress(), Amount: td.RandAmount(), }, } trx := td.GenerateTestSubsidyTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithRecipients(recipients)) err := td.state.checkSubsidy(trx, proposerAddr, true) require.NoError(t, err) }) t.Run("Non-delegated proposer rejects 3-recipient subsidy", func(t *testing.T) { lockTime := td.RandHeight() val, err := td.state.store.Validator(proposerAddr) require.NoError(t, err) td.state.store.UpdateValidator(val) recipients := []payload.BatchRecipient{ { To: td.state.params.FoundationAddress[lockTime%100], Amount: td.state.params.FoundationReward, }, { To: td.RandAccAddress(), Amount: td.RandAmount(), }, { To: td.RandAccAddress(), Amount: 0, }, } trx := td.GenerateTestSubsidyTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithRecipients(recipients)) err = td.state.checkSubsidy(trx, proposerAddr, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Delegated proposer accepts valid 3-recipient subsidy", func(t *testing.T) { delegateOwner := td.RandAccAddress() delegateShare := amount.Amount(2e8) lockTime := td.RandHeight() val, err := td.state.store.Validator(proposerAddr) require.NoError(t, err) val.SetDelegation(delegateOwner, delegateShare, td.RandHeight()) td.state.store.UpdateValidator(val) recipients := []payload.BatchRecipient{ { To: td.state.params.FoundationAddress[lockTime%100], Amount: td.state.params.FoundationReward, }, { To: delegateOwner, Amount: delegateShare, }, { To: td.RandAccAddress(), Amount: td.state.params.BlockReward - td.state.params.FoundationReward - delegateShare, }, } trx := td.GenerateTestSubsidyTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithRecipients(recipients)) err = td.state.checkSubsidy(trx, proposerAddr, true) require.NoError(t, err) }) t.Run("Delegated proposer rejects invalid owner amount/address in 3-recipient subsidy", func(t *testing.T) { delegateOwner := td.RandAccAddress() delegateShare := amount.Amount(0.3e9) lockTime := td.RandHeight() val, err := td.state.store.Validator(proposerAddr) require.NoError(t, err) val.SetDelegation(delegateOwner, delegateShare, td.RandHeight()) td.state.store.UpdateValidator(val) badRecipients := []payload.BatchRecipient{ { To: td.state.params.FoundationAddress[lockTime%100], Amount: td.state.params.FoundationReward, }, { To: td.RandAccAddress(), Amount: td.state.params.BlockReward - td.state.params.FoundationReward - delegateShare, }, { To: td.RandAccAddress(), Amount: delegateShare + 1, }, } trx := td.GenerateTestSubsidyTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithRecipients(badRecipients)) err = td.state.checkSubsidy(trx, proposerAddr, true) require.ErrorIs(t, err, ErrInvalidSubsidyTransaction) }) t.Run("Delegated proposer with zero share for owner", func(t *testing.T) { lockTime := td.RandHeight() val, err := td.state.store.Validator(proposerAddr) require.NoError(t, err) val.SetDelegation(td.RandAccAddress(), 0, td.RandHeight()) td.state.store.UpdateValidator(val) recipients := []payload.BatchRecipient{ { To: td.state.params.FoundationAddress[lockTime%100], Amount: td.state.params.FoundationReward, }, { To: td.RandAccAddress(), Amount: td.RandAmount(), }, } trx := td.GenerateTestSubsidyTx( testsuite.TransactionWithLockTime(lockTime), testsuite.TransactionWithRecipients(recipients)) err = td.state.checkSubsidy(trx, proposerAddr, true) require.NoError(t, err) }) } ================================================ FILE: state/facade.go ================================================ package state import ( "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" ) type ChainInfo struct { LastBlockHeight types.Height LastBlockHash hash.Hash LastBlockTime time.Time TotalPower int64 CommitteePower int64 CommitteeSize int TotalAccounts int32 TotalValidators int32 ActiveValidators int32 AverageScore float64 IsPruned bool PruningHeight types.Height } // CommitteeInfo holds committee validators, protocol versions, and total power. type CommitteeInfo struct { Validators []*validator.Validator ProtocolVersions map[protocol.Version]float64 CommitteePower int64 } type Facade interface { Genesis() *genesis.Genesis Params() *param.Params LastBlockHeight() types.Height LastBlockHash() hash.Hash LastBlockTime() time.Time LastCertificate() *certificate.Certificate UpdateLastCertificate(v *vote.Vote) error ProposeBlock(valKey *bls.ValidatorKey, rewardAddr crypto.Address) (*block.Block, error) ValidateBlock(blk *block.Block, round types.Round) error CommitBlock(blk *block.Block, cert *certificate.Certificate) error CommitteeValidators() []*validator.Validator CommitteeInfo() *CommitteeInfo IsInCommittee(addr crypto.Address) bool Proposer(round types.Round) *validator.Validator IsProposer(addr crypto.Address, round types.Round) bool PendingTx(txID tx.ID) *tx.Tx AddPendingTx(trx *tx.Tx) error AddPendingTxAndBroadcast(trx *tx.Tx) error CommittedBlock(height types.Height) (*store.CommittedBlock, error) CommittedTx(txID tx.ID) (*store.CommittedTx, error) BlockHash(height types.Height) hash.Hash BlockHeight(h hash.Hash) types.Height AccountByAddress(addr crypto.Address) (*account.Account, error) ValidatorByAddress(addr crypto.Address) (*validator.Validator, error) ValidatorByNumber(number int32) (*validator.Validator, error) ValidatorAddresses() []crypto.Address UpdateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) CalculateFee(amt amount.Amount, payloadType payload.Type) amount.Amount PublicKey(addr crypto.Address) (crypto.PublicKey, error) AvailabilityScore(valNum int32) float64 AllPendingTxs() []*tx.Tx ChainInfo() *ChainInfo CheckTransaction(trx *tx.Tx) error Close() } ================================================ FILE: state/lastinfo/last_info.go ================================================ package lastinfo import ( "fmt" "time" "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/logger" ) type LastInfo struct { lastSortitionSeed sortition.VerifiableSeed lastBlockHash hash.Hash lastCert *certificate.Certificate lastBlockTime time.Time lastValidators []*validator.Validator } func NewLastInfo() *LastInfo { return &LastInfo{} } func (li *LastInfo) SortitionSeed() sortition.VerifiableSeed { return li.lastSortitionSeed } func (li *LastInfo) BlockHeight() types.Height { if li.lastCert == nil { return 0 } return li.lastCert.Height() } func (li *LastInfo) BlockHash() hash.Hash { return li.lastBlockHash } func (li *LastInfo) Certificate() *certificate.Certificate { return li.lastCert } func (li *LastInfo) BlockTime() time.Time { return li.lastBlockTime } func (li *LastInfo) Validators() []*validator.Validator { return li.lastValidators } func (li *LastInfo) UpdateSortitionSeed(lastSortitionSeed sortition.VerifiableSeed) { li.lastSortitionSeed = lastSortitionSeed } func (li *LastInfo) UpdateBlockHash(lastBlockHash hash.Hash) { li.lastBlockHash = lastBlockHash } func (li *LastInfo) UpdateCertificate(lastCertificate *certificate.Certificate) { li.lastCert = lastCertificate } func (li *LastInfo) UpdateBlockTime(lastBlockTime time.Time) { li.lastBlockTime = lastBlockTime } func (li *LastInfo) UpdateValidators(vals []*validator.Validator) { li.lastValidators = vals } func (li *LastInfo) RestoreLastInfo(store store.Store, committeeSize int) ( committee.Committee, protocol.Version, error, ) { lastCert := store.LastCertificate() lastHeight := lastCert.Height() logger.Debug("try to restore last state info", "height", lastHeight) sb, err := store.Block(lastHeight) if err != nil { return nil, 0, fmt.Errorf("unable to retrieve block %v: %w", lastHeight, err) } lastBlock, err := sb.ToBlock() if err != nil { return nil, 0, err } li.lastCert = lastCert li.lastSortitionSeed = lastBlock.Header().SortitionSeed() li.lastBlockHash = lastBlock.Hash() li.lastBlockTime = lastBlock.Header().Time() cmt, err := li.restoreCommittee(store, lastBlock, committeeSize) if err != nil { return nil, 0, err } return cmt, lastBlock.Header().Version(), nil } func (li *LastInfo) restoreCommittee(store store.Store, lastBlock *block.Block, committeeSize int, ) (committee.Committee, error) { joinedVals := make([]*validator.Validator, 0) for _, trx := range lastBlock.Transactions() { // If there is any sortition transaction in the last block, // we should update the last committee. if trx.IsSortitionTx() { pld := trx.Payload().(*payload.SortitionPayload) val, err := store.Validator(pld.Validator) if err != nil { return nil, fmt.Errorf("unable to retrieve validator %s: %w", pld.Validator, err) } joinedVals = append(joinedVals, val) } } proposerIndex := -1 curCommitteeSize := len(li.lastCert.Committers()) vals := make([]*validator.Validator, len(li.lastCert.Committers())) for i, num := range li.lastCert.Committers() { val, err := store.ValidatorByNumber(num) if err != nil { return nil, fmt.Errorf("unable to retrieve committee member %v: %w", num, err) } if lastBlock.Header().ProposerAddress() == val.Address() { proposerIndex = i } vals[i] = val } li.lastValidators = vals // First, we restore the previous committee; then, we update it to get the latest committee. proposerIndex = (proposerIndex + curCommitteeSize - (int(li.lastCert.Round()) % curCommitteeSize)) % curCommitteeSize cmt, err := committee.NewCommittee(vals, committeeSize, vals[proposerIndex].Address()) if err != nil { return nil, fmt.Errorf("unable to create last committee: %w", err) } cmt.Update(li.lastCert.Round(), joinedVals) return cmt, nil } ================================================ FILE: state/lastinfo/last_info_test.go ================================================ package lastinfo import ( "testing" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // The best way to test this module is by writing test code in the `state.CommitBlock` function // to restore the state after each commit. type testData struct { *testsuite.TestSuite store *store.MockStore lastInfo *LastInfo } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) mockStore := store.MockingStore(ts) lastInfo := NewLastInfo() require.Zero(t, lastInfo.BlockHeight()) require.Equal(t, hash.UndefHash, lastInfo.BlockHash()) pub0, _ := ts.RandBLSKeyPair() pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() pub3, _ := ts.RandBLSKeyPair() pub4, prv4 := ts.RandBLSKeyPair() val0 := validator.NewValidator(pub0, 0) val1 := validator.NewValidator(pub1, 1) val2 := validator.NewValidator(pub2, 2) val3 := validator.NewValidator(pub3, 3) val4 := validator.NewValidator(pub4, 4) val0.AddToStake(100) val1.AddToStake(100) val2.AddToStake(100) val3.AddToStake(100) val4.AddToStake(100) val0.UpdateLastSortitionHeight(0) val1.UpdateLastSortitionHeight(0) val2.UpdateLastSortitionHeight(0) val3.UpdateLastSortitionHeight(0) val4.UpdateLastSortitionHeight(100) mockStore.UpdateValidator(val0) mockStore.UpdateValidator(val1) mockStore.UpdateValidator(val2) mockStore.UpdateValidator(val3) mockStore.UpdateValidator(val4) // Last block committers := []int32{0, 1, 2, 3} trx := tx.NewSortitionTx(1, pub4.ValidatorAddress(), ts.RandProof()) ts.HelperSignTransaction(prv4, trx) prevHash := ts.RandHash() lastHeight := ts.RandHeight() prevCert := ts.GenerateTestCertificate(lastHeight - 1) lastSeed := ts.RandSeed() lastBlock := block.MakeBlock(protocol.ProtocolVersion2, time.Now(), block.Txs{trx}, prevHash, ts.RandHash(), prevCert, lastSeed, val2.Address()) sig := ts.RandBLSSignature() lastCert := certificate.NewCertificate(lastHeight, 0) lastCert.SetSignature(committers, []int32{}, sig) mockStore.SaveBlock(lastBlock, lastCert) assert.Equal(t, lastHeight, mockStore.LastHeight) lastInfo.UpdateSortitionSeed(lastSeed) lastInfo.UpdateBlockHash(lastBlock.Hash()) lastInfo.UpdateCertificate(lastCert) lastInfo.UpdateBlockTime(lastBlock.Header().Time()) lastInfo.UpdateValidators([]*validator.Validator{val0, val1, val2, val3}) return &testData{ TestSuite: ts, store: mockStore, lastInfo: lastInfo, } } func TestRestoreCommittee(t *testing.T) { td := setup(t) lastInfo := NewLastInfo() cmt, _, err := lastInfo.RestoreLastInfo(td.store, 4) require.NoError(t, err) val0, _ := td.store.ValidatorByNumber(0) val1, _ := td.store.ValidatorByNumber(1) val2, _ := td.store.ValidatorByNumber(2) val3, _ := td.store.ValidatorByNumber(3) assert.Equal(t, td.lastInfo.SortitionSeed(), lastInfo.SortitionSeed()) assert.Equal(t, td.lastInfo.BlockHeight(), lastInfo.BlockHeight()) assert.Equal(t, td.lastInfo.BlockHash(), lastInfo.BlockHash()) assert.Equal(t, td.lastInfo.Certificate().Hash(), lastInfo.Certificate().Hash()) assert.Equal(t, td.lastInfo.BlockTime(), lastInfo.BlockTime()) assert.Equal(t, []*validator.Validator{val0, val1, val2, val3}, td.lastInfo.Validators()) assert.Equal(t, []int32{1, 4, 2, 3}, cmt.Committers()) } func TestRestoreFailed(t *testing.T) { td := setup(t) t.Run("Unable to get validator from store", func(t *testing.T) { setup(t) li := NewLastInfo() td.store.Validators = make(map[crypto.Address]*validator.Validator) // Reset Validators _, _, err := li.RestoreLastInfo(td.store, 4) require.Error(t, err) }) t.Run("Unable to get block from store", func(t *testing.T) { setup(t) li := NewLastInfo() td.store.Blocks = make(map[types.Height]*block.Block) // Reset Blocks _, _, err := li.RestoreLastInfo(td.store, 4) require.Error(t, err) }) } ================================================ FILE: state/mock.go ================================================ package state import ( "sync" "time" "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" ) var _ Facade = &MockState{} // MockState is a mock implementation of the State interface for testing. type MockState struct { // This locks prevents the Data Race in tests lk sync.RWMutex ts *testsuite.TestSuite TestGenesis *genesis.Genesis TestStore *store.MockStore MockTxPool *txpool.MockTxPool TestCommittee committee.Committee TestValKeys []*bls.ValidatorKey TestParams *param.Params } func MockingState(ts *testsuite.TestSuite) *MockState { cmt, valKeys := ts.GenerateTestCommittee(21) genDoc := genesis.MainnetGenesis() return &MockState{ ts: ts, TestGenesis: genDoc, TestStore: store.MockingStore(ts), MockTxPool: txpool.NewMockTxPool(ts.Ctrl), TestCommittee: cmt, TestValKeys: valKeys, TestParams: param.FromGenesis(genDoc), } } func (m *MockState) CommitTestBlocks(num int) { for i := 0; i < num; i++ { height := m.TestStore.LastHeight + 1 blk, cert := m.ts.GenerateTestBlock(height) m.TestStore.SaveBlock(blk, cert) } } func (m *MockState) Genesis() *genesis.Genesis { return m.TestGenesis } func (m *MockState) LastBlockHeight() types.Height { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.LastHeight } func (m *MockState) LastBlockHash() hash.Hash { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.BlockHash(m.TestStore.LastHeight) } func (m *MockState) LastBlockTime() time.Time { m.lk.RLock() defer m.lk.RUnlock() if len(m.TestStore.Blocks) > 0 { return m.TestStore.Blocks[m.TestStore.LastHeight].Header().Time() } return m.Genesis().GenesisTime() } func (m *MockState) LastCertificate() *certificate.Certificate { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.LastCert } func (*MockState) UpdateLastCertificate(_ *vote.Vote) error { return nil } func (m *MockState) CommitBlock(blk *block.Block, cert *certificate.Certificate) error { m.lk.Lock() defer m.lk.Unlock() m.TestStore.SaveBlock(blk, cert) return nil } func (*MockState) Close() {} func (m *MockState) ProposeBlock(valKey *bls.ValidatorKey, _ crypto.Address) (*block.Block, error) { blk, _ := m.ts.GenerateTestBlock(m.TestStore.LastHeight, testsuite.BlockWithProposer(valKey.Address())) return blk, nil } func (*MockState) ValidateBlock(_ *block.Block, _ types.Round) error { return nil } func (m *MockState) CommitteeValidators() []*validator.Validator { return m.TestCommittee.Validators() } func (m *MockState) IsInCommittee(addr crypto.Address) bool { return m.TestCommittee.Contains(addr) } func (m *MockState) Proposer(round types.Round) *validator.Validator { return m.TestCommittee.Proposer(round) } func (m *MockState) IsProposer(addr crypto.Address, round types.Round) bool { return m.TestCommittee.IsProposer(addr, round) } func (m *MockState) IsValidator(addr crypto.Address) bool { return m.TestStore.HasValidator(addr) } func (m *MockState) CommittedBlock(height types.Height) (*store.CommittedBlock, error) { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.Block(height) } func (m *MockState) CommittedTx(txID tx.ID) (*store.CommittedTx, error) { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.Transaction(txID) } func (m *MockState) BlockHash(height types.Height) hash.Hash { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.BlockHash(height) } func (m *MockState) BlockHeight(h hash.Hash) types.Height { m.lk.RLock() defer m.lk.RUnlock() return m.TestStore.BlockHeight(h) } func (m *MockState) AccountByAddress(addr crypto.Address) (*account.Account, error) { a, _ := m.TestStore.Account(addr) return a, nil } func (m *MockState) ValidatorAddresses() []crypto.Address { return m.TestStore.ValidatorAddresses() } func (m *MockState) ValidatorByAddress(addr crypto.Address) (*validator.Validator, error) { v, _ := m.TestStore.Validator(addr) return v, nil } func (m *MockState) ValidatorByNumber(n int32) (*validator.Validator, error) { v, _ := m.TestStore.ValidatorByNumber(n) return v, nil } func (m *MockState) PendingTx(txID tx.ID) *tx.Tx { return m.MockTxPool.PendingTx(txID) } func (m *MockState) AddPendingTx(trx *tx.Tx) error { return m.MockTxPool.AppendTx(trx) } func (m *MockState) AddPendingTxAndBroadcast(trx *tx.Tx) error { return m.MockTxPool.AppendTxAndBroadcast(trx) } func (m *MockState) Params() *param.Params { return m.TestParams } func (m *MockState) CalculateFee(amt amount.Amount, payloadType payload.Type) amount.Amount { return m.MockTxPool.EstimatedFee(amt, payloadType) } func (m *MockState) PublicKey(addr crypto.Address) (crypto.PublicKey, error) { return m.TestStore.PublicKey(addr) } func (*MockState) AvailabilityScore(_ int32) float64 { return 0.987 } func (m *MockState) AllPendingTxs() []*tx.Tx { return m.MockTxPool.AllPendingTxs() } func (m *MockState) UpdateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) { m.TestStore.UpdateValidatorProtocolVersion(addr, ver) } func (m *MockState) CommitteeInfo() *CommitteeInfo { return &CommitteeInfo{ Validators: m.TestCommittee.Validators(), ProtocolVersions: m.TestCommittee.ProtocolVersions(), CommitteePower: m.TestCommittee.TotalPower(), } } func (m *MockState) ChainInfo() *ChainInfo { return &ChainInfo{ LastBlockHeight: m.LastBlockHeight(), LastBlockHash: m.LastBlockHash(), LastBlockTime: m.LastBlockTime(), TotalPower: m.TestCommittee.TotalPower(), CommitteePower: m.TestCommittee.TotalPower(), CommitteeSize: m.TestCommittee.Size(), TotalAccounts: m.TestStore.TotalAccounts(), TotalValidators: m.TestStore.TotalValidators(), ActiveValidators: m.TestStore.ActiveValidators(), AverageScore: 0, IsPruned: m.TestStore.IsPruned(), PruningHeight: m.TestStore.PruningHeight(), } } func (*MockState) CheckTransaction(*tx.Tx) error { return nil } ================================================ FILE: state/param/foundation_mainnet.json ================================================ [ "pc1z0k5ctvn02hsxvl9t3d2efnkv2d5k46ayfddzxg", "pc1zrv84qnh96pmkg2sykedtz5mlu0q72st2l5c6gg", "pc1zuyqdsewxl4leth4rsmzhme2qxwwsvv5qvp6lfl", "pc1zslj5zcrsz8f83dn04yd06pjfntn8fqstxusp2q", "pc1z4pus6lp0nd35nqvhl0u22aquh6dh5lkq9pkx8t", "pc1zpjjm2vjqvcrktsxhr0d4k46u83cv2q4nrtteft", "pc1z524hsllxjd25n2mzjew9np9ymwte2mg3kf3jqx", "pc1zvnjnprk99wt6jq85saqz8ymc4n8n0utzm9gkq8", "pc1zzepy0rdc70eagaj0h9ypvy9nt2y8l3gyav00s8", "pc1zr9q4cg8zltkdndc2cadmskvptrftsghgzh8emx", "pc1z4zvhmkp4q6pwasea6wc2yp7vvk58wnlcqp7c08", "pc1zum42zls02q7hys0gyn0lkk9rhr58jylwkv8xc8", "pc1z4zn4z5tqa23qu0lckn0jd0n8r0l3dxynlrv5fc", "pc1zu9xnuwppsx57htmhkm8dah4crkv3yxuepuxvts", "pc1z9e22jhexznp4v3a5je2f5uhp7u2nnd8528j4u3", "pc1zktyzkpld8qjzw9uy32xchssh5ajkp0uhqrhuvx", "pc1zxcexp09alrfvdzettn6v7a9c6wxr6tgt7zu23d", "pc1z7zgxvg457nsevl30utyhpr5pne6l7vuwmxmu0y", "pc1z8vzqyr3rdw0ut89yezfs9rmzd3ju05m7t6ume9", "pc1z23mrkftlg6tgfh3y7pw053tlx8k7e8cuq6v4gk", "pc1zfwdvv7paddhz3hpj5re4tvqavklc8lcn3laqpj", "pc1zs29lv7gxcglsf48k9zx0gewcewh86u05v7q2jd", "pc1zzhvnqgklwg9x6kukkg2at5298rqwq7r3zntmcd", "pc1zaqt8f58zlwj6ujft8hqtlmgequxlgh53z7m2va", "pc1zamglslh02haafxwcnlvtmaqk2q7zy6el3ul8ty", "pc1z9cqfp98qzue0wyhv4eqf5sc4rphv9jz066fjkp", "pc1ztjzwvxx5hva8f4uneualr7w8rfgnyq2w022y6d", "pc1zhefja2m90z82lwg07w2l82g672x9l3gl5cuyd8", "pc1z4l6mxwl09rjag99e0hvayj93zagt4m3apt4ydg", "pc1zmww5k5xzwzapkg9hwuppvqsmgjgcf7xe8t3skn", "pc1zazjcm67d9gcr227s673cmzl049ey7s9eeqntcu", "pc1zufm93ys6xe0axcclxlw43c9ygfslggdpqakc4g", "pc1znup58n2karq46ulgy64l43znc538h5wnthdnr7", "pc1zzekctnhk7unqa6e9gw76q3csmd22r8adzth2h7", "pc1zwdrghnnyrymsul52c6lz9g0etn5nr7k76f0e0n", "pc1zs2dag7jn8szjq5rau5jacy0fcn2z20wk0xmgtf", "pc1zc2mqdajamhsphmaqpcc3htytverdarl99v55my", "pc1z2cmlxtyz4yaruggar84kelp2kakma6lt3v2wp5", "pc1zg9duch5lavgnrxh8p7e4vw4f4u8v45e0264f4n", "pc1zxayue97rjzdwrs6xe3jmzzt43r5m6z7ua0xemf", "pc1z2lupx42vt3ydx7gxldg7j2870rxw437zk6g270", "pc1z30p2aht7lyxvj0xy0s663q0x8hrf9qz2as2kte", "pc1z030a9vkt7nmd5qdk9m8jrgj457degeuy3yes06", "pc1z644fc3ftd2d5fj83ppjq0dnnetzp3u3sa4zvdn", "pc1z9usnds5wqgmr78dqrf8q8ce9axsj2hpj5yjhcy", "pc1zt3mpyy79uf4zu2pdaw09s2cgg3e0plwja0hehz", "pc1ze65ate4uxj9jpusfjzezs94peln8h82q4uw3mu", "pc1zqs0lv79xlqd68rrqc97lgt9853f2yngrwpmt0p", "pc1zxhw5sghlzs44aylqlpg5wzjca63f7y83dpukqp", "pc1zakefesc7kdveptfyv7aklxat44r0clk2tmxxmq", "pc1zlzws4ellhspcast96f7l6pqtzy762x08th7tgz", "pc1z4tdnddwmxeppa3pcaquxhq4rrc5adcx7t3qfj0", "pc1zmn43x36e0jcjtqqewxj50n5rjeh8sus7e9ty2j", "pc1zn6e3wcg7epkq36eqmupdksy7xtcezlenwhzw4s", "pc1ze7fwpmqv0fq3g8c2xsl2tmqh6tsgltpncgyr0j", "pc1z8dwn7ewj357624cugsvpcahd9z50qk5u8lv0hu", "pc1zzj0hcgywnh9lx3678yfg8362ap2xvw68mwp6px", "pc1zq2242trf7w04qp65kz8w4c8vzmnfzv4qkq5nx9", "pc1z433apczddfy94agee5du2c7lwgagq0r3qzpwfg", "pc1zanv4v6a686g56z4zppw4yfh9tzhr0vu3ex37y4", "pc1zw9wy204u2y5mr90ufl6zkqysyxk2mymp947dkd", "pc1z6nn9qxzl62c69t0wrd2e6fnf62mdsavvqv7wh9", "pc1zk7vz7s0ejk05x2cl7e3z04kjmgwj0lva3jzjuh", "pc1zc7h8x3z6etyvmxk04l9h2p5mmpvcmf6wtywvq0", "pc1zx6z6ymvl9lud4zes4lelrzzl70cl9tyrx92yp2", "pc1zsscy3xneaz6jagmzrnhwccfps7xjauzge8l8pc", "pc1zvvfm7l7g670vjsnup3g3z5jajhgdk8zpz6djzs", "pc1zl4ryxj2etw9ulv4yst9cm5fwl7g0se7j8hh9fp", "pc1zyj4rfns3p7uaat42rpm5hk72frss8uzu63y7ds", "pc1zcc9a34x6ckw6jf46e0e5emrcy5kdpvn6ahazlc", "pc1zgu6qxesu5ceux0582nf38vp0nmfr6a59qm8wzk", "pc1z20p3fkzre4ved2fkuuvfkusr3ejusgx5frt4eh", "pc1zqhxs703hhttk8mgjy096uxc98tz20a637alxdd", "pc1zqettg2qcm4kejsf39895ua8vau8j4p7j38ws3j", "pc1zxz5myr8evp54ces0zfdxz3ftrfx8kyunq504zl", "pc1zqtlu57upjzhzpkxdldj4cw8vc847pm7yvezx96", "pc1zhg4gc6ezpvndph964p3qd3plzupuf792jk2xxq", "pc1z6e4v3q2quj5kxazxck5uv8pczdkusmzquptx47", "pc1z67kjqzr02wcwryt3fym0td8ugt7mk7zmmzqm8d", "pc1zrqs39vs5l84pk4efplg6qsz5t0q70qejp47qrh", "pc1z3d692p24watvepg9hgm8p3f8rr28m5wxct3lhz", "pc1zlx8gr05vdrqcttvwhaav6npqpanzcfld8v7zw8", "pc1z6ceypvm6r88uqtfm7nqepwlxm03dydwucdzkas", "pc1zgqysx75cu8jw6v54pagtgr0qyqen0tvftxydz8", "pc1zcvtmzxllvkal3qk2dtk5j8cdkszgtlvqpfwsud", "pc1z9hy6mgtpwe8zkfhs9f6pl7rqz29ncq0xylw0qc", "pc1z7dteekv7007xzj7evxvjh8kuanfr3klyhkqs35", "pc1zv3uvz8taq66hv5rlff77nv06f6a6eww5ydfg8q", "pc1z8sne0w5twj6ayexyq9y9t6em0un7u4pdv0ytr7", "pc1zevt5r6h35eg70dygsfnffphn8hv4qx39wukvey", "pc1zw8zp3mm9f3723unpcfymyjms5uvpl3gp007uwg", "pc1zsq02f2ukn63pw4rpywksl75ku3s5kcjzh4p2cg", "pc1ztvxet33xzc0h52syujk0jf3wyncwn0ucp56vqy", "pc1zakujzs606fk049xvnuts75hll5gmkhzp3xx2gq", "pc1zluxwytlxaesa4mdskpjh90mqjuc5uxcsxymvtm", "pc1znrjpkruxcmqrwq60zlc67nz5sft7eetf9r4h40", "pc1zmy564huaxd4cmzgyujqe55dr3pgsg336pp4m3l", "pc1zre6lx6m27g9jsrdxt70a2qrtvsqsmshje9e34m", "pc1zphprc83wqy3xpqyequ4andeuuz22t2pdd9whg2", "pc1zgqq766nf3782gxvrncv8cvfszdda4ss20y4e7a" ] ================================================ FILE: state/param/foundation_testnet.json ================================================ [ "tpc1zkkjnu6hqkkedmtlvs7v6y0z6txk7eqhwg5cr38", "tpc1zxu54fm05fqg6t5u7j96rl9fthaj3g64yg288nt", "tpc1z3n27d7x9xu3l0lss448vytpczdsxgc8j2ltwhf", "tpc1z9zsen2expdgpny8xgjsepwaz4mf9y0wrf9ttur", "tpc1zngaf3q08vtqe96rydu5ppplvzqyzeu0nv8t97u", "tpc1zr5h235l3q6ehktrpjuudxpfl8kt63863zehxva", "tpc1z4gd6ansakknll4hkmppg4j3gkyadfpxs802rts", "tpc1zj5uvweqwam0230xug4z64uhd8jgf4tzmtu7tqq", "tpc1z9rudal827f3550km8s3kny9rtaav8aeq9tzs8m", "tpc1ze0vggdekzlsuljtdzwgzhjmsd37pexq6jywv3n", "tpc1zahzuun0tds9qm458pkysnkws6nthnqv84zdxxn", "tpc1z3krskej32sgqjllwehrds6ztgqt7lz5zj0aspp", "tpc1z65ddexykp3sc7rdnpeme38rp3u340hg9lecgr0", "tpc1z7fjv0vsg4q0ml67zgkn8dn5zvmjrzjnw92zdmw", "tpc1zjsujauvurgm0n46y7396k2eghfcxhfzqxjr5xl", "tpc1z52daa8euyx7t73fx5pvmwr2pgvrw2w4lamlmte", "tpc1z8us3l07alk4nacftdsf265mg970zdjf4g8c4fp", "tpc1zj0tpzsvw23fyzxp3mqfrs7fezydnc5uqe9nxy4", "tpc1zcuw2h8geklrskr8s90nyuqdz20cu7rfuy05dkv", "tpc1zme9yn5kzd0agre00nekcyvx6v0tpy0yt0nukql", "tpc1zuctmks9purfw4qku6k5ncls2kghfh4qdwq24d7", "tpc1zm38604zk8r3rv5yjnaz6xwypp93u6qefeld9ay", "tpc1zkw32fhnuu83nxa564m6hhn3pdxqess2qfzey3a", "tpc1zshqkful8yps6w6ph0ej2yhtgup3tl3jqacw9c5", "tpc1z29kxc8zuph7jgxupdyp6l53y5j2vzcp35suvzq", "tpc1zndv9zxeuc7xycqfy0qfy5yfd9feca5qu0j3als", "tpc1z4gzlyzdc2v44tprynakrnluu9t4a2wxz0dhws9", "tpc1zlfm6a6sy8f87cwa0a5sajgcmr75lq0jfw0mk4v", "tpc1zd69kgvks9dz32t509fakv3jf9sdmej0see4mut", "tpc1zu3efcymqu2efv203fw6jd8stqn8xlhgr74rup9", "tpc1zr057yp3cyj7l7hp5lnnka0gzlcdg062dq8v29x", "tpc1zmu5afwq9sc9szt733x7nrmdjr50z0lteu6shtl", "tpc1zwu7wf0mwgh9sep3zjnuun8fmzu5dl2afevgwdp", "tpc1zkrc5m9p9nkmn8tmd7nat5d2fn7zg3qxx2lv06m", "tpc1zxjuaau588jqsk7nqplpx9h488nns0wa5ke3clx", "tpc1zd8cvnsrk7n0ey3cglyyl6zf9pntllfpayhhq35", "tpc1zwayssykgh9c96xm5wnvvxnrqmum73rfat5fag2", "tpc1zvcexewgfhetqpptfrlwe7fzvj2vlkh0qdjzmsh", "tpc1zgenmk09t0xr55uxvadwxn3d3rvy3vdz3lkhv97", "tpc1zawmp27uv9ys3lakrmkuwjszft34yf8rg082eaz", "tpc1zyxehwn3ytw2aeu79qhx3uc2p53vlkljg0vl7qv", "tpc1z9m6cp6f7hfmxjczm0qgjl48pvdzn2wed383yhj", "tpc1zmmdjq90sk796ndr22sxjkydfca09wkdggyua9v", "tpc1zgl99cyqe54r3nv6sh9latz7j6yyv0u23teky4r", "tpc1zppppga0szm0xmfrx3gjq9q4q07nw368n6djpce", "tpc1z0skj2cw84nwpzlcw2h4ksj4njhfcy0fegrwqte", "tpc1zl4c0g5cl77h8l0wysd7lmcvjqd4u7zkl549rys", "tpc1zlpryhzv4yat30454p8cmefwjsa9smpu6xmkavg", "tpc1z3dshr6rqand03h5uzwxgm6c5hum7eu90ct8x3e", "tpc1zrt2ps85uukmywyw9e3wvgv2hf0ksp8xxyg45fe", "tpc1z6myk3rs8hsvkcm7ydwzwlc2z66zwmw62guzge0", "tpc1z08k4fwvjt82xewlrnnxz77860flg4qhsdpuetu", "tpc1zpxqky3yqukm79qyz8yz6545qwj2xv75mkhedv6", "tpc1zpffh95pgdlh60hkhc4qunrshw5xhndrs6xdcjz", "tpc1zcsyffvs8yc32qkcdyjkwuy2t0qjr02cflqcanx", "tpc1zstedmhxykve30wd35c5n6stu9pk9wcnkey5jyc", "tpc1zc76hgn8c9vtedhw776jd0cv2yxeya2azjeu3p3", "tpc1zvsreq53869uywetf84ha5nrs4vg5f3fuvqheup", "tpc1z002d7zu4w3r7f9rcdru38eh04nekj7fh45umdn", "tpc1zv6f34pe3pdwlf24nvz7nevf8r4f0eun9glstxr", "tpc1zq2ll9qmglr3etd4038mfzvazhw0xkz03m3lw5z", "tpc1zqwqfykfkzzlr7gcw3z0vkau0vu2j8ezycldefq", "tpc1zhly6dlr20x02tqh2zraz2x9l82pq30lpmpaa06", "tpc1za6ymx6ud8xtdve5jc3w7st44kwrjtslj43x8dj", "tpc1zu8he7z6eq2qdt0dv00l4nvlmjr4eawdh0jemz0", "tpc1zem8uevskqn3esy5sewysk2pawrht2t0wshny7d", "tpc1zvel9wp8fq8n7yrm0uy3lxvtz6f8cw0ecnafln8", "tpc1zagmwzqaxmr5x37ftmjrhzvn33s9lty3yrvkl0w", "tpc1zph9vvh9yq049gd9gdladck6r47aweluquzy3g4", "tpc1zljvq36a54g7fdx98r9559c425xyy3w9078kxw4", "tpc1zgnn4d6fa4rjumn9wgaap0naqwzf4dvh3cxreds", "tpc1zku76xy2d52m95rtnrhtelnqeexky3js24mxdw5", "tpc1zxactzwcucm882je5hkvwak8u9m6jzdsqmxfd9l", "tpc1z8lqsc83p7axv6qddjekm723m2k7r364rp0m8vy", "tpc1z0aatm57eqe6yj8zqn6lk4x3rykvdj6dntmcysu", "tpc1zqxtfmfjx0qutlhwfvuejmeuzx38v3dh32laaf7", "tpc1zfawja200zwymq930m0z3etcpla5axs0k5ardrm", "tpc1z3tpez707ekhamury657x4wn5dyfeh4m006aee0", "tpc1z890x2mt3gnqeu5hcnej98yngnumjq8lfjt6tj0", "tpc1zwh7mnrk703uuaxsgkgdua8rhksy8fvyygenxut", "tpc1zulykmttfv8kwesu9pfx7p6ypvzq2m2468cs9us", "tpc1zskshqxt6492a9hak2a880l0gd09lnge6ts5p22", "tpc1znnxhfd83d2frcf694sh4qx4pgr84ynnz80pwpw", "tpc1z8ng6xxw9jgqypxz0gqprc5u8lnd8kay4jg9ka5", "tpc1zskln40663ttaj72gj0jamuh79lrgch0pu8ter5", "tpc1zwkthy0ujk232ek9ryva5whkf2w2zj7qqeuyv4q", "tpc1zrvulzwzv3x7sdc6u5ynffng8rv76f8v8j7whra", "tpc1zr0zwwgzdtw7wcsh06qzymm6cvgsfwfgq9mye5a", "tpc1zvxjhz9fewhas6vtr23u64mxhf8ht4q9rq2n4xy", "tpc1zg0uctnpta9n2knf0vv8tda7tmvn7047t6t0g77", "tpc1z5y6qvanklwwegrqcd8w7vc34hs886dsmdlcyed", "tpc1zuec2x4t8hv72ymnf0w7aaf5yumq308taje7p02", "tpc1zutwaj2xh9c5zzcs0llxunqsfc295r2dz6prm0e", "tpc1z9a5rmjysa0qaa5aagt3lv2fu9qdpwdaw8kn45v", "tpc1z2pdc6kwxct48l9qnfmjgmj48ss7ndgwkr8ntv3", "tpc1zx4lxdnfaar9hrzt0kv6lqw59rv6ev7vzda3yjg", "tpc1zjdar58w6gmfu96qgvq22h8yfsk6mwah4u6vssj", "tpc1zp63pwuefzj9r6xed8v0he45mwpquk5tjpluk4l", "tpc1z4k8m2drc6dqea80rsnj36y8tghn8ap9fskrtnc", "tpc1zhvu0tvqczpjx24uwhhzrfmuph7vxurdxpdcnrn" ] ================================================ FILE: state/param/param.go ================================================ package param import ( _ "embed" "encoding/json" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" ) //go:embed foundation_testnet.json var foundationTestnetBytes []byte //go:embed foundation_mainnet.json var foundationMainnetBytes []byte // MaxDelegateOwnerRewardShare is the maximum stake-owner share of the block reward // under PIP-49 validator delegation (0.7 PAC in nano PAC). const MaxDelegateOwnerRewardShare = amount.Amount(0.7 * amount.NanoPACPerPAC) // Params is the parameters of the Pactus protocol. // These parameters are fixed among all the nodes in the network. // TODO: Save them in DB and load them on startng the node. type Params struct { BlockVersion protocol.Version BlockIntervalInSecond int MaxTransactionsPerBlock int CommitteeSize int BlockReward amount.Amount TransactionToLiveInterval uint32 BondInterval uint32 UnbondInterval uint32 SortitionInterval uint32 MinimumStake amount.Amount MaximumStake amount.Amount FoundationReward amount.Amount FoundationAddress []crypto.Address } func FromGenesis(genDoc *genesis.Genesis) *Params { params := &Params{ // genesis parameters BlockVersion: genDoc.Params().BlockVersion, BlockIntervalInSecond: genDoc.Params().BlockIntervalInSecond, CommitteeSize: genDoc.Params().CommitteeSize, BlockReward: genDoc.Params().BlockReward, TransactionToLiveInterval: genDoc.Params().TransactionToLiveInterval, BondInterval: genDoc.Params().BondInterval, UnbondInterval: genDoc.Params().UnbondInterval, SortitionInterval: genDoc.Params().SortitionInterval, MaximumStake: genDoc.Params().MaximumStake, MinimumStake: genDoc.Params().MinimumStake, // chain parameters MaxTransactionsPerBlock: 1000, FoundationAddress: make([]crypto.Address, 0, 100), FoundationReward: amount.Amount(300_000_000), } foundationAddressList := make([]string, 0) switch genDoc.ChainType() { case genesis.Mainnet: if err := json.Unmarshal(foundationMainnetBytes, &foundationAddressList); err != nil { panic(err) } case genesis.Testnet: if err := json.Unmarshal(foundationTestnetBytes, &foundationAddressList); err != nil { panic(err) } case genesis.Localnet: for i := 0; i < 100; i++ { buf := hash.CalcHash([]byte{byte(i)}).Bytes() prv, _ := bls.PrivateKeyFromBytes(buf) foundationAddressList = append(foundationAddressList, prv.PublicKeyNative().AccountAddress().String()) } } for _, addrStr := range foundationAddressList { addr, err := crypto.AddressFromString(addrStr) if err != nil { panic(err) } params.FoundationAddress = append(params.FoundationAddress, addr) } return params } func (p *Params) BlockInterval() time.Duration { return time.Duration(p.BlockIntervalInSecond) * time.Second } ================================================ FILE: state/score/score.go ================================================ package score import ( "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" ) type scoreData struct { inCommittee int // Number of times a validator was in the committee absent int // Number of times a validator was absent from the committee (not voted) } type Manager struct { certs map[types.Height]*certificate.Certificate vals map[int32]*scoreData maxCert uint32 } func NewScoreManager(maxCert uint32) *Manager { return &Manager{ certs: make(map[types.Height]*certificate.Certificate), vals: make(map[int32]*scoreData), maxCert: maxCert, } } func (sm *Manager) SetCertificate(cert *certificate.Certificate) { lastHeight := cert.Height() sm.certs[lastHeight] = cert for _, num := range cert.Committers() { data, ok := sm.vals[num] if !ok { data = new(scoreData) sm.vals[num] = data } data.inCommittee++ } for _, num := range cert.Absentees() { data := sm.vals[num] sm.vals[num] = data data.absent++ } oldHeight := lastHeight.SafeDecrease(sm.maxCert) oldCert, ok := sm.certs[oldHeight] if ok { for _, num := range oldCert.Committers() { data := sm.vals[num] data.inCommittee-- } for _, num := range oldCert.Absentees() { data := sm.vals[num] data.absent-- } delete(sm.certs, oldHeight) } } func (sm *Manager) AvailabilityScore(valNum int32) float64 { data, ok := sm.vals[valNum] if ok { if data.inCommittee == 0 { return 1.0 } return 1 - (float64(data.absent) / float64(data.inCommittee)) } return 1.0 } ================================================ FILE: state/score/score_test.go ================================================ package score import ( "testing" "github.com/pactus-project/pactus/types/certificate" "github.com/stretchr/testify/assert" ) func TestScoreManager(t *testing.T) { maxCert := uint32(3) scoreMgr := NewScoreManager(maxCert) cert1 := certificate.NewCertificate(1, 0) cert1.SetSignature([]int32{0, 1, 2, 3}, []int32{0}, nil) cert2 := certificate.NewCertificate(2, 0) cert2.SetSignature([]int32{0, 1, 2, 3}, []int32{3}, nil) cert3 := certificate.NewCertificate(3, 0) cert3.SetSignature([]int32{1, 2, 3, 4}, []int32{2}, nil) cert4 := certificate.NewCertificate(4, 0) cert4.SetSignature([]int32{1, 2, 3, 4}, []int32{2}, nil) cert5 := certificate.NewCertificate(5, 0) cert5.SetSignature([]int32{1, 2, 3, 4}, []int32{2}, nil) tests := []struct { cert *certificate.Certificate score0 float64 score1 float64 score2 float64 score3 float64 score4 float64 }{ {cert1, 0, 1, 1, 1, 1}, {cert2, 0.5, 1, 1, 0.5, 1}, {cert3, 0.5, 1, 1 - (float64(1) / float64(3)), 1 - (float64(1) / float64(3)), 1}, {cert4, 1, 1, 1 - (float64(2) / float64(3)), 1 - (float64(1) / float64(3)), 1}, {cert5, 1, 1, 0, 1, 1}, } for no, tt := range tests { scoreMgr.SetCertificate(tt.cert) score0 := scoreMgr.AvailabilityScore(0) assert.InDelta(t, tt.score0, score0, 0.00001, "#%v: invalid score0, expected %v, got %v", no, tt.score0, score0) score1 := scoreMgr.AvailabilityScore(1) assert.InDelta(t, tt.score1, score1, 0.00001, "#%v: invalid score1, expected %v, got %v", no, tt.score1, score1) score2 := scoreMgr.AvailabilityScore(2) assert.InDelta(t, tt.score2, score2, 0.00001, "#%v: invalid score2, expected %v, got %v", no, tt.score2, score2) score3 := scoreMgr.AvailabilityScore(3) assert.InDelta(t, tt.score3, score3, 0.00001, "#%v: invalid score3, expected %v, got %v", no, tt.score3, score3) score4 := scoreMgr.AvailabilityScore(4) assert.InDelta(t, tt.score4, score4, 0.00001, "#%v: invalid score4, expected %v, got %v", no, tt.score4, score4) } } ================================================ FILE: state/state.go ================================================ package state import ( "bytes" "fmt" "slices" "sync" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/execution" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/state/lastinfo" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/state/score" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/persistentmerkle" "github.com/pactus-project/pactus/util/simplemerkle" "github.com/pactus-project/pactus/version" ) type state struct { lk sync.RWMutex valKeys []*bls.ValidatorKey genDoc *genesis.Genesis store store.Store params *param.Params txPool txpool.TxPool committee committee.Committee totalPower int64 lastInfo *lastinfo.LastInfo accountMerkle *persistentmerkle.Tree validatorMerkle *persistentmerkle.Tree scoreMgr *score.Manager logger *logger.SubLogger eventPipe pipeline.Pipeline[any] } func LoadOrNewState( genDoc *genesis.Genesis, valKeys []*bls.ValidatorKey, store store.Store, txPool txpool.TxPool, eventPipe pipeline.Pipeline[any], ) (Facade, error) { state := &state{ valKeys: valKeys, genDoc: genDoc, txPool: txPool, params: param.FromGenesis(genDoc), store: store, lastInfo: lastinfo.NewLastInfo(), accountMerkle: persistentmerkle.New(), validatorMerkle: persistentmerkle.New(), eventPipe: eventPipe, } state.logger = logger.NewSubLogger("_state", state) state.store = store // If there is no certificate, we are at the genesis height. // Only the genesis block has no certificate. if store.LastCertificate() == nil { // Initialize the state at genesis. err := state.makeGenesisState(genDoc) if err != nil { return nil, err } } else { // Otherwise, try to restore the last known state. err := state.tryLoadLastInfo() if err != nil { return nil, err } } state.totalPower = state.retrieveTotalPower() state.loadMerkels() txPool.SetNewSandboxAndRecheck(state.concreteSandbox()) // Restoring score manager state.logger.Info("calculating the availability scores...") scoreWindow := uint32(60000) startHeight := types.Height(2) endHeight := state.lastInfo.BlockHeight() if uint32(endHeight) > scoreWindow { startHeight = endHeight.SafeDecrease(scoreWindow) } scoreMgr := score.NewScoreManager(scoreWindow) for h := startHeight; h <= endHeight; h++ { cBlk, err := state.store.Block(h) if err != nil { return nil, err } // This code decodes the block certificate from the block data // without decoding the header and transactions. r := bytes.NewReader(cBlk.Data[138:]) // Block header is 138 bytes cert := new(certificate.Certificate) err = cert.Decode(r) if err != nil { return nil, err } scoreMgr.SetCertificate(cert) } state.scoreMgr = scoreMgr for _, num := range state.committee.Committers() { state.logger.Debug("availability score", "val", num, "score", state.scoreMgr.AvailabilityScore(num)) } // Set ProtocolVersion for own validators. for _, key := range valKeys { val, _ := store.Validator(key.Address()) if val == nil { continue } store.UpdateValidatorProtocolVersion(val.Address(), version.NodeAgent.ProtocolVersion) } state.logger.Debug("last info", "committers", state.committee.Committers(), "state_root", state.stateRoot()) return state, nil } func (st *state) concreteSandbox() sandbox.Sandbox { return sandbox.NewSandbox(st.lastInfo.BlockHeight(), st.store, st.params, st.committee, st.totalPower, st.genDoc.ChainType().IsMainnet()) } func (st *state) tryLoadLastInfo() error { logger.Debug("try to restore the last state") committeeInstance, blockVersion, err := st.lastInfo.RestoreLastInfo(st.store, st.params.CommitteeSize) if err != nil { return err } st.committee = committeeInstance st.params.BlockVersion = blockVersion logger.Info("last state restored", "last height", st.lastInfo.BlockHeight(), "last block time", st.lastInfo.BlockTime()) return nil } func (st *state) makeGenesisState(genDoc *genesis.Genesis) error { accs := genDoc.Accounts() for addr, acc := range accs { st.store.UpdateAccount(addr, acc) } vals := genDoc.Validators() for _, val := range vals { st.store.UpdateValidator(val) } err := st.store.WriteBatch() if err != nil { return err } cmt, err := committee.NewCommittee(vals, st.params.CommitteeSize, vals[0].Address()) if err != nil { return err } st.committee = cmt st.lastInfo.UpdateBlockTime(genDoc.GenesisTime()) return nil } func (st *state) loadMerkels() { st.store.IterateAccounts(func(_ crypto.Address, acc *account.Account) bool { st.accountMerkle.SetHash(acc.Number(), acc.Hash()) return false }) st.store.IterateValidators(func(val *validator.Validator) bool { st.validatorMerkle.SetHash(val.Number(), val.Hash()) return false }) } func (st *state) retrieveTotalPower() int64 { totalPower := int64(0) st.store.IterateValidators(func(val *validator.Validator) bool { totalPower += val.Power() return false }) return totalPower } func (st *state) stateRoot() hash.Hash { accRoot := st.accountMerkle.Root() valRoot := st.validatorMerkle.Root() stateRoot := simplemerkle.HashMerkleBranches(&accRoot, &valRoot) return *stateRoot } func (st *state) Close() { st.lk.RLock() defer st.lk.RUnlock() st.store.Close() } func (st *state) Genesis() *genesis.Genesis { st.lk.RLock() defer st.lk.RUnlock() return st.genDoc } func (st *state) LastBlockHeight() types.Height { st.lk.RLock() defer st.lk.RUnlock() return st.lastInfo.BlockHeight() } func (st *state) LastBlockHash() hash.Hash { st.lk.RLock() defer st.lk.RUnlock() return st.lastInfo.BlockHash() } func (st *state) LastBlockTime() time.Time { st.lk.RLock() defer st.lk.RUnlock() return st.lastInfo.BlockTime() } func (st *state) LastCertificate() *certificate.Certificate { st.lk.RLock() defer st.lk.RUnlock() return st.lastInfo.Certificate() } func (st *state) UpdateLastCertificate(vte *vote.Vote) error { st.lk.Lock() defer st.lk.Unlock() lastCert := st.lastInfo.Certificate() if vte.Type() != vote.VoteTypePrecommit || vte.Height() != lastCert.Height() || vte.Round() != lastCert.Round() { return InvalidVoteForCertificateError{ Vote: vte, } } val, err := st.store.Validator(vte.Signer()) if err != nil { return err } if !slices.Contains(lastCert.Absentees(), val.Number()) { return InvalidVoteForCertificateError{ Vote: vte, } } err = vte.Verify(val.PublicKey()) if err != nil { return err } // prevent race condition cloneLastCert := lastCert.Clone() cloneLastCert.AddSignature(val.Number(), vte.Signature()) st.lastInfo.UpdateCertificate(cloneLastCert) st.logger.Debug("certificate updated", "validator", val.Address(), "power", val.Power()) return nil } func (st *state) createSubsidyTx(valAddr, rewardAddr crypto.Address, accumulatedFee amount.Amount) *tx.Tx { lockTime := st.lastInfo.BlockHeight() + 1 addressIndex := int(lockTime) % len(st.params.FoundationAddress) foundationAddress := st.params.FoundationAddress[addressIndex] recipients := make([]payload.BatchRecipient, 0, 3) recipients = append(recipients, payload.BatchRecipient{ To: foundationAddress, Amount: st.params.FoundationReward, }) val, _ := st.store.Validator(valAddr) if val.IsDelegated() { // Base on PIP-49, the maximum delegate share is 0.7 PAC. // If the delegate share is equal to 0 PAC, the delegate owner should not receive any reward. // If the delegate share is equal to 0.7 PAC, the delegate owner receives // all the remaining reward, and transaction fee. dlgOwnerAddr := val.DelegateOwner() dlgOwnerShare := val.DelegateShare() if dlgOwnerShare > 0 { amount := dlgOwnerShare if dlgOwnerShare == param.MaxDelegateOwnerRewardShare { amount += accumulatedFee } recipients = append(recipients, payload.BatchRecipient{ To: dlgOwnerAddr, Amount: amount, }) } if dlgOwnerShare < param.MaxDelegateOwnerRewardShare { recipients = append(recipients, payload.BatchRecipient{ To: rewardAddr, Amount: st.params.BlockReward + accumulatedFee - st.params.FoundationReward - dlgOwnerShare, }) } } else { recipients = append(recipients, payload.BatchRecipient{ To: rewardAddr, Amount: st.params.BlockReward + accumulatedFee - st.params.FoundationReward, }) } return tx.NewSubsidyTx(lockTime, recipients) } func (st *state) ProposeBlock(valKey *bls.ValidatorKey, rewardAddr crypto.Address) (*block.Block, error) { st.lk.Lock() defer st.lk.Unlock() // Create new sandbox and execute transactions sbx := st.concreteSandbox() // Re-check all transactions strictly and remove invalid ones txs := st.txPool.PrepareBlockTransactions() txs = util.Trim(txs, st.params.MaxTransactionsPerBlock-1) for i := 0; i < txs.Len(); i++ { // Only one subsidy transaction per block if txs[i].IsSubsidyTx() { st.logger.Error("found duplicated subsidy transaction", "tx", txs[i]) txs.Remove(i) i-- continue } if err := execution.CheckAndExecute(txs[i], sbx, true); err != nil { st.logger.Debug("found invalid transaction", "tx", txs[i], "error", err) txs.Remove(i) i-- } } valAddr := valKey.Address() subsidyTx := st.createSubsidyTx(valAddr, rewardAddr, sbx.AccumulatedFee()) txs.Prepend(subsidyTx) prevSeed := st.lastInfo.SortitionSeed() blk := block.MakeBlock( st.params.BlockVersion, st.proposeNextBlockTime(), txs, st.lastInfo.BlockHash(), st.stateRoot(), st.lastInfo.Certificate(), prevSeed.GenerateNext(valKey.PrivateKey()), valAddr) return blk, nil } func (st *state) ValidateBlock(blk *block.Block, round types.Round) error { st.lk.Lock() defer st.lk.Unlock() if err := st.validateBlock(blk, round); err != nil { return err } t := blk.Header().Time() if err := st.validateBlockTime(t); err != nil { return err } sb := st.concreteSandbox() return st.executeBlock(blk, sb, true) } func (st *state) CommitBlock(blk *block.Block, cert *certificate.Certificate) error { st.lk.Lock() defer st.lk.Unlock() height := cert.Height() if height != st.lastInfo.BlockHeight()+1 { st.logger.Debug("block is committed before", "height", height) return nil } err := st.validateCurCertificate(cert, blk.Hash()) if err != nil { return err } // There are two modules that can commit a block: Consensus and Sync. // The Consensus engine is ours, we have full control over that, and we know when // and why a block should be committed. // On the other hand, Sync module receives new blocks from the network and // tries to commit them. // We should never have a fork in our blockchain. // But if it happens, here we can catch it. if blk.Header().PrevBlockHash() != st.lastInfo.BlockHash() { st.logger.Panic("a possible fork is detected", "our hash", st.lastInfo.BlockHash(), "block hash", blk.Header().PrevBlockHash()) } err = st.validateBlock(blk, cert.Round()) if err != nil { return err } // ----------------------------------- // Execute block sbx := st.concreteSandbox() if err := st.executeBlock(blk, sbx, false); err != nil { return err } // ----------------------------------- // Commit block st.lastInfo.UpdateBlockHash(blk.Hash()) st.lastInfo.UpdateBlockTime(blk.Header().Time()) st.lastInfo.UpdateSortitionSeed(blk.Header().SortitionSeed()) st.lastInfo.UpdateCertificate(cert) st.lastInfo.UpdateValidators(st.committee.Validators()) // Commit and update the committee st.commitSandbox(sbx, cert.Round()) st.store.SaveBlock(blk, cert) if err := st.store.WriteBatch(); err != nil { st.logger.Panic("unable to update state", "error", err) } // Remove transactions from pool and update consumption st.txPool.HandleCommittedBlock(blk) st.logger.Info("new block committed", "block", blk, "round", cert.Round()) st.evaluateSortition() // ----------------------------------- // At this point we can assign a new sandbox to tx pool st.txPool.SetNewSandboxAndRecheck(st.concreteSandbox()) // ----------------------------------- // Updating the score manager: // This code updates the availability scores. // To enhance syncing process, only blocks with timestamps from the last 10 days are considered. if blk.Header().Time().After(time.Now().AddDate(0, 0, -10)) { prevCert := blk.PrevCertificate() if prevCert != nil { st.scoreMgr.SetCertificate(prevCert) } } // publish committed block to event channel zeromq st.publishEvent(blk) return nil } func (st *state) evaluateSortition() bool { evaluated := false for _, key := range st.valKeys { val, _ := st.store.Validator(key.Address()) if val == nil { // We are not a validator continue } if st.lastInfo.BlockHeight().SafeSub(val.LastBondingHeight()) < st.params.BondInterval { // Bonding period continue } if val.IsUnbonded() { // we have Unbonded continue } ok, proof := sortition.EvaluateSortition(st.lastInfo.SortitionSeed(), key.PrivateKey(), st.totalPower, int64(val.Stake())) if ok { trx := tx.NewSortitionTx(st.lastInfo.BlockHeight(), val.Address(), proof) sig := key.Sign(trx.SignBytes()) trx.SetSignature(sig) trx.SetPublicKey(key.PublicKey()) err := st.txPool.AppendTxAndBroadcast(trx) if err == nil { st.logger.Info("sortition transaction broadcasted", "address", key.Address(), "power", val.Power(), "tx", trx) evaluated = true } else { st.logger.Error("our sortition transaction is invalid!", "address", key.Address(), "power", val.Power(), "tx", trx, "error", err) } } } return evaluated } // LogString returns a concise string representation intended for use in logs. func (st *state) LogString() string { return fmt.Sprintf("{#%d ⌘ %v 🕣 %v}", st.lastInfo.BlockHeight(), st.lastInfo.BlockHash().LogString(), st.lastInfo.BlockTime().Format("15.04.05")) } func (st *state) commitSandbox(sbx sandbox.Sandbox, round types.Round) { joiningCommittee := make([]*validator.Validator, 0) sbx.IterateValidators(func(val *validator.Validator, _ bool, joined bool) { if joined { st.logger.Debug("new validator joined", "address", val.Address(), "power", val.Power()) joiningCommittee = append(joiningCommittee, val) } }) st.committee.Update(round, joiningCommittee) sbx.IterateAccounts(func(addr crypto.Address, acc *account.Account, updated bool) { if updated { st.store.UpdateAccount(addr, acc) st.accountMerkle.SetHash(acc.Number(), acc.Hash()) } }) sbx.IterateValidators(func(val *validator.Validator, updated bool, _ bool) { if updated { st.store.UpdateValidator(val) st.validatorMerkle.SetHash(val.Number(), val.Hash()) } }) st.totalPower += sbx.PowerDelta() } func (st *state) validateBlockTime(blockTime time.Time) error { if blockTime.Second()%st.params.BlockIntervalInSecond != 0 { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is not rounded", blockTime.String()), } } if blockTime.Before(st.lastInfo.BlockTime()) { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is before the last block time (%s)", blockTime.String(), st.lastInfo.BlockTime()), } } if blockTime.Equal(st.lastInfo.BlockTime()) { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is same as the last block time", blockTime.String()), } } proposeTime := st.proposeNextBlockTime() threshold := st.params.BlockInterval() if blockTime.After(proposeTime.Add(threshold)) { return InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is more than threshold (%s)", blockTime.String(), proposeTime.String()), } } return nil } func (st *state) proposeNextBlockTime() time.Time { timestamp := st.lastInfo.BlockTime().Add(st.params.BlockInterval()) now := time.Now() if now.After(timestamp.Add(10 * time.Second)) { st.logger.Debug("it looks the last block had delay", "delay", now.Sub(timestamp)) timestamp = util.RoundNow(st.params.BlockIntervalInSecond) } return timestamp } func (st *state) CommitteeValidators() []*validator.Validator { st.lk.RLock() defer st.lk.RUnlock() return st.committee.Validators() } func (st *state) IsInCommittee(addr crypto.Address) bool { st.lk.RLock() defer st.lk.RUnlock() return st.committee.Contains(addr) } func (st *state) Proposer(round types.Round) *validator.Validator { st.lk.RLock() defer st.lk.RUnlock() return st.committee.Proposer(round) } func (st *state) IsProposer(addr crypto.Address, round types.Round) bool { st.lk.RLock() defer st.lk.RUnlock() return st.committee.IsProposer(addr, round) } func (st *state) CommittedBlock(height types.Height) (*store.CommittedBlock, error) { return st.store.Block(height) } func (st *state) CommittedTx(txID tx.ID) (*store.CommittedTx, error) { return st.store.Transaction(txID) } func (st *state) BlockHash(height types.Height) hash.Hash { return st.store.BlockHash(height) } func (st *state) BlockHeight(h hash.Hash) types.Height { return st.store.BlockHeight(h) } func (st *state) AccountByAddress(addr crypto.Address) (*account.Account, error) { return st.store.Account(addr) } func (st *state) ValidatorAddresses() []crypto.Address { return st.store.ValidatorAddresses() } func (st *state) ValidatorByAddress(addr crypto.Address) (*validator.Validator, error) { return st.store.Validator(addr) } // ValidatorByNumber returns validator data based on validator number. func (st *state) ValidatorByNumber(n int32) (*validator.Validator, error) { return st.store.ValidatorByNumber(n) } func (st *state) PendingTx(txID tx.ID) *tx.Tx { return st.txPool.PendingTx(txID) } func (st *state) AddPendingTx(trx *tx.Tx) error { return st.txPool.AppendTx(trx) } func (st *state) AddPendingTxAndBroadcast(trx *tx.Tx) error { return st.txPool.AppendTxAndBroadcast(trx) } func (st *state) Params() *param.Params { return st.params } func (st *state) CalculateFee(amt amount.Amount, payloadType payload.Type) amount.Amount { return st.txPool.EstimatedFee(amt, payloadType) } func (st *state) PublicKey(addr crypto.Address) (crypto.PublicKey, error) { st.lk.RLock() defer st.lk.RUnlock() return st.store.PublicKey(addr) } func (st *state) AvailabilityScore(valNum int32) float64 { st.lk.RLock() defer st.lk.RUnlock() return st.scoreMgr.AvailabilityScore(valNum) } func (st *state) AllPendingTxs() []*tx.Tx { st.lk.RLock() defer st.lk.RUnlock() return st.txPool.AllPendingTxs() } func (st *state) publishEvent(msg any) { st.eventPipe.Send(msg) } func (st *state) UpdateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) { st.store.UpdateValidatorProtocolVersion(addr, ver) } func (st *state) CommitteeInfo() *CommitteeInfo { st.lk.RLock() defer st.lk.RUnlock() return &CommitteeInfo{ Validators: st.committee.Validators(), ProtocolVersions: st.committee.ProtocolVersions(), CommitteePower: st.committee.TotalPower(), } } func (st *state) ChainInfo() *ChainInfo { st.lk.RLock() defer st.lk.RUnlock() return &ChainInfo{ LastBlockHeight: st.lastInfo.BlockHeight(), LastBlockHash: st.lastInfo.BlockHash(), LastBlockTime: st.lastInfo.BlockTime(), TotalPower: st.totalPower, CommitteePower: st.committee.TotalPower(), CommitteeSize: st.committee.Size(), TotalAccounts: st.store.TotalAccounts(), TotalValidators: st.store.TotalValidators(), ActiveValidators: st.store.ActiveValidators(), AverageScore: st.calculateAverageScore(), IsPruned: st.store.IsPruned(), PruningHeight: st.store.PruningHeight(), } } func (st *state) calculateAverageScore() float64 { totalScore := 0.0 totalWithStake := 0.0 for _, key := range st.valKeys { val, _ := st.store.Validator(key.Address()) if val == nil { continue } if !val.IsActive() { continue } totalScore += st.scoreMgr.AvailabilityScore(val.Number()) totalWithStake++ } averageScore := 0.0 if totalWithStake > 0 { averageScore = (totalScore / totalWithStake) * 100 } return averageScore } func (st *state) CheckTransaction(trx *tx.Tx) error { st.lk.RLock() defer st.lk.RUnlock() return execution.CheckAndExecute(trx, st.concreteSandbox(), false) } ================================================ FILE: state/state_test.go ================================================ package state import ( "testing" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "golang.org/x/exp/slices" ) type testData struct { *testsuite.TestSuite state *state mockTxPool *txpool.MockTxPool genValKeys []*bls.ValidatorKey genAccKey *ed25519.PrivateKey } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) genValNum := 4 genValKeys := make([]*bls.ValidatorKey, 0, genValNum) genVals := make([]*validator.Validator, 0, genValNum) for i := 0; i < genValNum; i++ { valKey := ts.RandValKey() val := validator.NewValidator(valKey.PublicKey(), int32(i)) genValKeys = append(genValKeys, valKey) genVals = append(genVals, val) } numBlocks := ts.RandHeight( testsuite.HeightWithMin(1), testsuite.HeightWithMax(10)) mockTxPool := txpool.NewMockTxPool(ts.Ctrl) mockTxPool.EXPECT().SetNewSandboxAndRecheck(gomock.Any()).Return().AnyTimes() mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(int(numBlocks)) mockTxPool.EXPECT().HandleCommittedBlock(gomock.Any()).Return().AnyTimes() mockStore := store.MockingStore(ts) genTime := util.RoundNow(10).Add(-8640 * time.Second) genParams := genesis.DefaultGenesisParams() genParams.CommitteeSize = 7 genParams.BondInterval = 10 genParams.BlockVersion = protocol.ProtocolVersion3 genAcc1 := account.NewAccount(0) genAcc1.AddToBalance(21 * 1e15) // 21,000,000.000,000,000 genAcc2 := account.NewAccount(1) genAcc2.AddToBalance(21 * 1e15) // 21,000,000.000,000,000 genAccPubKey, genAccPrvKey := ts.RandEd25519KeyPair() genAccs := map[crypto.Address]*account.Account{ crypto.TreasuryAddress: genAcc1, genAccPubKey.AccountAddress(): genAcc2, } gnDoc := genesis.MakeGenesis(genTime, genAccs, genVals, genParams) // First validator is in the committee valKeys := []*bls.ValidatorKey{genValKeys[0], ts.RandValKey()} eventPipe := pipeline.New[any](t.Context()) st1, err := LoadOrNewState(gnDoc, valKeys, mockStore, mockTxPool, eventPipe) require.NoError(t, err) state, _ := st1.(*state) td := &testData{ TestSuite: ts, state: state, mockTxPool: mockTxPool, genValKeys: genValKeys, genAccKey: genAccPrvKey, } td.commitBlocks(t, numBlocks) return td } func (td *testData) proposerKey(t *testing.T, round types.Round) *bls.ValidatorKey { t.Helper() blockProposer := td.state.Proposer(round) valKeyIndex := slices.IndexFunc(td.genValKeys, func(e *bls.ValidatorKey) bool { return e.Address() == blockProposer.Address() }) return td.genValKeys[valKeyIndex] } func (td *testData) makeBlockAndCertificate(t *testing.T, round types.Round) ( *block.Block, *certificate.Certificate, ) { t.Helper() valKey := td.proposerKey(t, round) blk, _ := td.state.ProposeBlock(valKey, td.RandAccAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) return blk, cert } func (td *testData) makeCertificateAndSign(t *testing.T, blockHash hash.Hash, round types.Round, ) *certificate.Certificate { t.Helper() sigs := make([]*bls.Signature, 0, len(td.genValKeys)) height := td.state.LastBlockHeight() cert := certificate.NewCertificate(height+1, round) signBytes := cert.SignBytesPrecommit(blockHash) committers := []int32{0, 1, 2, 3} absentees := []int32{3} for _, key := range td.genValKeys[:len(td.genValKeys)-1] { sig := key.Sign(signBytes) sigs = append(sigs, sig) } aggSig, _ := bls.SignatureAggregate(sigs...) cert.SetSignature(committers, absentees, aggSig) return cert } func (td *testData) commitBlocks(t *testing.T, count types.Height) { t.Helper() for i := types.Height(0); i < count; i++ { blk, cert := td.makeBlockAndCertificate(t, 0) require.NoError(t, td.state.CommitBlock(blk, cert)) } } func TestClosingState(t *testing.T) { td := setup(t) td.state.Close() } func TestBlockSubsidyTx(t *testing.T) { td := setup(t) // Without reward address in config rewardAddr := td.RandAccAddress() proposerAddr := td.state.Proposer(0).Address() foundationAddr := td.state.params.FoundationAddress[td.state.LastBlockHeight()+1] tests := []struct { name string accumulatedFee amount.Amount expectedRecipients []payload.BatchRecipient }{ { name: "subsidy with zero transaction fee", accumulatedFee: 0, expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: rewardAddr, Amount: 0.7e9}, }, }, { name: "subsidy with transaction fee", accumulatedFee: 0.01e9, // 0.1 PAC expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: rewardAddr, Amount: 0.71e9}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { trx := td.state.createSubsidyTx(proposerAddr, rewardAddr, tt.accumulatedFee) err := td.state.checkSubsidy(trx, td.genValKeys[0].Address(), true) require.NoError(t, err) payload := trx.Payload().(*payload.BatchTransferPayload) for i, recipient := range payload.Recipients { assert.Equal(t, tt.expectedRecipients[i].To, recipient.To) assert.Equal(t, tt.expectedRecipients[i].Amount, recipient.Amount) } }) } } func TestBlockSubsidyWithDelegationTx(t *testing.T) { td := setup(t) // Without reward address in config rewardAddr := td.RandAccAddress() dlgOwnerAddr := td.RandAccAddress() proposerAddr := td.state.Proposer(0).Address() addressIndex := int(td.state.LastBlockHeight()+1) % len(td.state.params.FoundationAddress) foundationAddr := td.state.params.FoundationAddress[addressIndex] tests := []struct { name string accumulatedFee amount.Amount ownerShare amount.Amount expectedRecipients []payload.BatchRecipient }{ { name: "owner share 0, without transaction fee", accumulatedFee: 0, ownerShare: 0, expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: rewardAddr, Amount: 0.7e9}, }, }, { name: "owner share 0.2, without transaction fee", accumulatedFee: 0, ownerShare: 0.2e9, // 0.2 PAC expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: dlgOwnerAddr, Amount: 0.2e9}, {To: rewardAddr, Amount: 0.5e9}, }, }, { name: "owner share 0.7, without transaction fee", accumulatedFee: 0, ownerShare: 0.7e9, // 0.7 PAC expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: dlgOwnerAddr, Amount: 0.7e9}, }, }, { name: "owner share 0, with transaction fee", accumulatedFee: 0.01e9, // 0.01 PAC ownerShare: 0, expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: rewardAddr, Amount: 0.71e9}, }, }, { name: "owner share 0.2, with transaction fee", accumulatedFee: 0.01e9, // 0.01 PAC ownerShare: 0.2e9, // 0.2 PAC expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: dlgOwnerAddr, Amount: 0.2e9}, {To: rewardAddr, Amount: 0.51e9}, }, }, { name: "owner share 0.7, with transaction fee", accumulatedFee: 0.01e9, // 0.01 PAC ownerShare: 0.7e9, // 0.7 PAC expectedRecipients: []payload.BatchRecipient{ {To: foundationAddr, Amount: 0.3e9}, {To: dlgOwnerAddr, Amount: 0.71e9}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { val, _ := td.state.ValidatorByAddress(proposerAddr) val.SetDelegation(dlgOwnerAddr, tt.ownerShare, td.RandHeight()) td.state.store.UpdateValidator(val) trx := td.state.createSubsidyTx(proposerAddr, rewardAddr, tt.accumulatedFee) err := td.state.checkSubsidy(trx, proposerAddr, true) require.NoError(t, err) payload := trx.Payload().(*payload.BatchTransferPayload) for i, recipient := range payload.Recipients { assert.Equal(t, tt.expectedRecipients[i].To, recipient.To) assert.Equal(t, tt.expectedRecipients[i].Amount, recipient.Amount) } }) } } func TestTryCommitInvalidCertificate(t *testing.T) { td := setup(t) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(1) blk, _ := td.makeBlockAndCertificate(t, td.RandRound()) invCert := td.GenerateTestCertificate(td.state.LastBlockHeight() + 1) require.Error(t, td.state.CommitBlock(blk, invCert)) } func TestTryCommitValidBlocks(t *testing.T) { td := setup(t) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(1) blk, cert := td.makeBlockAndCertificate(t, 0) require.NoError(t, td.state.CommitBlock(blk, cert)) // Commit again // No error here but block is ignored, because the height is invalid require.NoError(t, td.state.CommitBlock(blk, cert)) assert.Equal(t, blk.Hash(), td.state.LastBlockHash()) assert.Equal(t, blk.Header().Time(), td.state.LastBlockTime()) assert.Equal(t, cert.Hash(), td.state.LastCertificate().Hash()) assert.Equal(t, cert.Height(), td.state.LastBlockHeight()) } func TestCommitSandbox(t *testing.T) { t.Run("Add new account", func(t *testing.T) { td := setup(t) addr := td.RandAccAddress() sb := td.state.concreteSandbox() newAcc := sb.MakeNewAccount(addr) newAcc.AddToBalance(td.RandAmount()) sb.UpdateAccount(addr, newAcc) td.state.commitSandbox(sb, 0) stateAcc, _ := td.state.AccountByAddress(addr) assert.Equal(t, stateAcc, newAcc) }) t.Run("Add new validator", func(t *testing.T) { td := setup(t) pub, _ := td.RandBLSKeyPair() sb := td.state.concreteSandbox() newVal := sb.MakeNewValidator(pub) newVal.AddToStake(td.RandAmount()) sb.UpdateValidator(newVal) td.state.commitSandbox(sb, 0) stateValByNumber, _ := td.state.ValidatorByAddress(pub.ValidatorAddress()) stateValByAddr, _ := td.state.ValidatorByAddress(pub.ValidatorAddress()) assert.Equal(t, stateValByNumber, newVal) assert.Equal(t, stateValByAddr, newVal) }) t.Run("Modify account", func(t *testing.T) { td := setup(t) sbx := td.state.concreteSandbox() addr := td.genAccKey.PublicKeyNative().AccountAddress() acc := sbx.Account(addr) bal := acc.Balance() amt := td.RandAmount() acc.SubtractFromBalance(amt) sbx.UpdateAccount(addr, acc) td.state.commitSandbox(sbx, 0) stateAcc, _ := td.state.AccountByAddress(addr) assert.Equal(t, bal-amt, stateAcc.Balance()) }) t.Run("Modify validator", func(t *testing.T) { td := setup(t) sbx := td.state.concreteSandbox() addr := td.genValKeys[0].Address() val := sbx.Validator(addr) stake := val.Stake() amt := td.RandAmount() val.AddToStake(amt) sbx.UpdateValidator(val) td.state.commitSandbox(sbx, 0) stateVal, _ := td.state.ValidatorByAddress(addr) assert.Equal(t, stake+amt, stateVal.Stake(), "%+v", val.Stake()) }) t.Run("Move committee", func(t *testing.T) { td := setup(t) proposer0 := td.state.committee.Proposer(0) proposer1 := td.state.committee.Proposer(1) assert.Equal(t, proposer0, td.state.committee.Proposer(0)) sb := td.state.concreteSandbox() td.state.commitSandbox(sb, 0) assert.Equal(t, proposer1, td.state.committee.Proposer(0)) }) t.Run("Move committee next round", func(t *testing.T) { td := setup(t) proposer0 := td.state.committee.Proposer(0) proposer1 := td.state.committee.Proposer(1) proposer2 := td.state.committee.Proposer(2) assert.Equal(t, proposer0, td.state.committee.Proposer(0)) assert.Equal(t, proposer1, td.state.committee.Proposer(1)) sb := td.state.concreteSandbox() td.state.commitSandbox(sb, 1) assert.Equal(t, proposer2, td.state.committee.Proposer(0)) }) } func TestUpdateLastCertificate(t *testing.T) { td := setup(t) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(1) blk, cert := td.makeBlockAndCertificate(t, 1) _ = td.state.CommitBlock(blk, cert) // the above `cert` is not signed by the last validators valKey1 := td.genValKeys[0] valKey4 := td.genValKeys[len(td.genValKeys)-1] invValKey := td.RandValKey() vote1 := vote.NewPrepareVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) vote2 := vote.NewPrecommitVote(blk.Hash(), cert.Height()+1, cert.Round(), valKey4.Address()) vote3 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round()-1, valKey4.Address()) vote4 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) vote5 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), invValKey.Address()) vote6 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey1.Address()) vote7 := vote.NewPrecommitVote(blk.Hash(), cert.Height(), cert.Round(), valKey4.Address()) td.HelperSignVote(valKey4, vote1) td.HelperSignVote(valKey4, vote2) td.HelperSignVote(valKey4, vote3) td.HelperSignVote(invValKey, vote4) td.HelperSignVote(invValKey, vote5) td.HelperSignVote(valKey4, vote6) td.HelperSignVote(valKey4, vote7) tests := []struct { vote *vote.Vote err error reason string }{ {vote1, InvalidVoteForCertificateError{Vote: vote1}, "invalid vote type"}, {vote2, InvalidVoteForCertificateError{Vote: vote2}, "invalid height"}, {vote3, InvalidVoteForCertificateError{Vote: vote3}, "invalid round"}, {vote4, crypto.ErrInvalidSignature, "invalid signature"}, {vote5, store.ErrNotFound, "unknown validator"}, {vote6, InvalidVoteForCertificateError{Vote: vote6}, "not in absentee"}, {vote7, nil, "ok"}, } for no, tt := range tests { err := td.state.UpdateLastCertificate(tt.vote) require.ErrorIs(t, err, tt.err, "error not matched for test %v", no) } } func TestForkDetection(t *testing.T) { td := setup(t) t.Run("Two blocks with different previous block hashes", func(t *testing.T) { td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(1) assert.Panics(t, func() { blk0, _ := td.makeBlockAndCertificate(t, 0) blkFork := block.MakeBlock( blk0.Header().Version(), blk0.Header().Time(), blk0.Transactions(), td.RandHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) certFork := td.makeCertificateAndSign(t, blkFork.Hash(), 0) _ = td.state.CommitBlock(blkFork, certFork) }) }) } func TestSortition(t *testing.T) { td := setup(t) valKey := td.state.valKeys[1] assert.False(t, td.state.evaluateSortition()) // not a validator assert.Equal(t, int64(4), td.state.ChainInfo().CommitteePower) trx := tx.NewBondTx(1, td.genAccKey.PublicKeyNative().AccountAddress(), valKey.Address(), valKey.PublicKey(), 1000000000, 100000) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{trx}).Times(1) td.commitBlocks(t, 1) assert.False(t, td.state.evaluateSortition()) // bonding period assert.Equal(t, int64(4), td.state.ChainInfo().CommitteePower) assert.False(t, td.state.committee.Contains(valKey.Address())) // Not in the committee // Committing another 10 blocks var sortitionTrx *tx.Tx td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(10) td.mockTxPool.EXPECT().AppendTxAndBroadcast(gomock.Any()).Do(func(trx *tx.Tx) { sortitionTrx = trx // Capture the input argument here }).Return(nil).Times(1) td.commitBlocks(t, 10) assert.Equal(t, payload.TypeSortition, sortitionTrx.Payload().Type()) assert.Equal(t, valKey.Address(), sortitionTrx.Payload().Signer()) assert.False(t, td.state.committee.Contains(valKey.Address())) // Still not in the committee td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{sortitionTrx}).Times(1) td.mockTxPool.EXPECT().AppendTxAndBroadcast(gomock.Any()).Return(nil).Times(1) td.commitBlocks(t, 1) assert.Equal(t, int64(1000000004), td.state.ChainInfo().CommitteePower) assert.True(t, td.state.committee.Contains(valKey.Address())) // In the committee } func TestValidateBlockTime(t *testing.T) { td := setup(t) t.Run("Time is not rounded", func(t *testing.T) { roundedNow := util.RoundNow(10) require.Error(t, td.state.validateBlockTime(roundedNow.Add(-15*time.Second))) require.Error(t, td.state.validateBlockTime(roundedNow.Add(-5*time.Second))) require.Error(t, td.state.validateBlockTime(roundedNow.Add(5*time.Second))) require.Error(t, td.state.validateBlockTime(roundedNow.Add(15*time.Second))) }) t.Run("Last block is committed 10 seconds ago", func(t *testing.T) { roundedNow := util.RoundNow(10) td.state.lastInfo.UpdateBlockTime(roundedNow.Add(-10 * time.Second)) // Before or same as the last block time require.Error(t, td.state.validateBlockTime(roundedNow.Add(-20*time.Second))) require.Error(t, td.state.validateBlockTime(roundedNow.Add(-10*time.Second))) // Ok require.NoError(t, td.state.validateBlockTime(roundedNow)) require.NoError(t, td.state.validateBlockTime(roundedNow.Add(10*time.Second))) // More than the threshold require.Error(t, td.state.validateBlockTime(roundedNow.Add(20*time.Second))) expectedProposeTime := roundedNow assert.Equal(t, expectedProposeTime, td.state.proposeNextBlockTime()) }) t.Run("Last block is committed one minute ago", func(t *testing.T) { roundedNow := util.RoundNow(10) td.state.lastInfo.UpdateBlockTime(roundedNow.Add(-1 * time.Minute)) // One minute ago lastBlockTime := td.state.LastBlockTime() // Before or same as the last block time require.Error(t, td.state.validateBlockTime(lastBlockTime.Add(-10*time.Second))) require.Error(t, td.state.validateBlockTime(lastBlockTime)) // Ok require.NoError(t, td.state.validateBlockTime(roundedNow.Add(-10*time.Second))) require.NoError(t, td.state.validateBlockTime(roundedNow)) require.NoError(t, td.state.validateBlockTime(roundedNow.Add(10*time.Second))) // More than the threshold require.Error(t, td.state.validateBlockTime(roundedNow.Add(30*time.Second))) expectedProposeTime := util.RoundNow(10) assert.Equal(t, expectedProposeTime, td.state.proposeNextBlockTime()) }) t.Run("Last block is committed in future", func(t *testing.T) { roundedNow := util.RoundNow(10) td.state.lastInfo.UpdateBlockTime(roundedNow.Add(1 * time.Minute)) // One minute later lastBlockTime := td.state.LastBlockTime() require.Error(t, td.state.validateBlockTime(lastBlockTime.Add(+1*time.Minute))) // Before the last block time require.Error(t, td.state.validateBlockTime(lastBlockTime.Add(-10*time.Second))) require.Error(t, td.state.validateBlockTime(lastBlockTime)) // Ok require.NoError(t, td.state.validateBlockTime(lastBlockTime.Add(10*time.Second))) require.NoError(t, td.state.validateBlockTime(lastBlockTime.Add(20*time.Second))) // More than the threshold require.Error(t, td.state.validateBlockTime(lastBlockTime.Add(30*time.Second))) expectedProposeTime := roundedNow.Add(1 * time.Minute).Add( time.Duration(td.state.params.BlockIntervalInSecond) * time.Second) assert.Equal(t, expectedProposeTime, td.state.proposeNextBlockTime()) }) } func TestValidatorHelpers(t *testing.T) { td := setup(t) t.Run("Should return error non-existing validator by address", func(t *testing.T) { _, err := td.state.ValidatorByAddress(td.RandValAddress()) require.Error(t, err) }) t.Run("Should return error for non-existing validator by number", func(t *testing.T) { _, err := td.state.ValidatorByNumber(10) require.Error(t, err) }) t.Run("Should return validator for existing validator by address", func(t *testing.T) { existingValidator, err := td.state.ValidatorByAddress(td.genValKeys[0].Address()) require.NoError(t, err) assert.Zero(t, existingValidator.Number()) }) t.Run("Should return validator for existing validator by number", func(t *testing.T) { existingValidator, err := td.state.ValidatorByNumber(0) require.NoError(t, err) assert.Zero(t, existingValidator.Number()) }) } func TestLoadState(t *testing.T) { td := setup(t) // Add a bond transactions to change total power (stake) pub, _ := td.RandBLSKeyPair() lockTime := td.state.LastBlockHeight() bondTrx := tx.NewBondTx(lockTime, td.genAccKey.PublicKeyNative().AccountAddress(), pub.ValidatorAddress(), pub, 1000000000, 100000) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{bondTrx}).Times(1) blk5, cert5 := td.makeBlockAndCertificate(t, 1) assert.Equal(t, 2, blk5.Transactions().Len()) require.NoError(t, td.state.CommitBlock(blk5, cert5)) td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).Times(1) blk6, cert6 := td.makeBlockAndCertificate(t, 0) // Load last state info eventPipe := pipeline.New[any](t.Context()) newState, err := LoadOrNewState(td.state.genDoc, td.state.valKeys, td.state.store, td.mockTxPool, eventPipe) require.NoError(t, err) assert.Equal(t, td.state.Params(), newState.Params()) assert.ElementsMatch(t, td.state.ValidatorAddresses(), newState.ValidatorAddresses()) assert.Equal(t, td.state.ChainInfo(), newState.ChainInfo()) // Try committing the next block require.NoError(t, newState.CommitBlock(blk6, cert6)) } func TestIsInCommittee(t *testing.T) { td := setup(t) proposer0 := td.proposerKey(t, 0).Address() proposer1 := td.proposerKey(t, 1).Address() assert.True(t, td.state.IsInCommittee(proposer0)) assert.True(t, td.state.IsProposer(proposer0, 0)) assert.True(t, td.state.IsInCommittee(proposer1)) assert.True(t, td.state.IsProposer(proposer1, 1)) addr := td.RandAccAddress() assert.False(t, td.state.IsInCommittee(addr)) assert.False(t, td.state.IsProposer(addr, 0)) assert.False(t, td.state.IsInCommittee(addr)) } func TestCalculateFee(t *testing.T) { td := setup(t) expectedFee := td.RandFee() td.mockTxPool.EXPECT().EstimatedFee(gomock.Any(), payload.TypeTransfer).Return(expectedFee).Times(1) fee := td.state.CalculateFee(td.RandAmount(), payload.TypeTransfer) assert.Equal(t, expectedFee, fee) } func TestCheckMaximumTransactionPerBlock(t *testing.T) { td := setup(t) txs := block.Txs{} td.state.params.MaxTransactionsPerBlock = 10 lockTime := td.state.LastBlockHeight() senderAddr := td.genAccKey.PublicKeyNative().AccountAddress() for i := 0; i < td.state.params.MaxTransactionsPerBlock+2; i++ { trx := tx.NewTransferTx(lockTime, senderAddr, td.RandAccAddress(), td.RandAmount(), td.RandFee()) txs = append(txs, trx) } td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(txs).Times(1) blk, err := td.state.ProposeBlock(td.state.valKeys[0], td.RandAccAddress()) require.NoError(t, err) assert.Equal(t, td.state.params.MaxTransactionsPerBlock, blk.Transactions().Len()) } func TestCommittedBlock(t *testing.T) { td := setup(t) t.Run("Block at 0", func(t *testing.T) { cBlkZero, err := td.state.CommittedBlock(0) require.Error(t, err) assert.Nil(t, cBlkZero) assert.Equal(t, hash.UndefHash, td.state.BlockHash(0)) assert.Equal(t, types.Height(0), td.state.BlockHeight(hash.UndefHash)) }) t.Run("First block (Genesis)", func(t *testing.T) { cBlkOne, err := td.state.CommittedBlock(1) require.NoError(t, err) blkOne, err := cBlkOne.ToBlock() require.NoError(t, err) assert.Nil(t, blkOne.PrevCertificate()) assert.Equal(t, hash.UndefHash, blkOne.Header().PrevBlockHash()) }) t.Run("Last block", func(t *testing.T) { cBlkLast, err := td.state.CommittedBlock(td.state.LastBlockHeight()) require.NoError(t, err) blkLast, err := cBlkLast.ToBlock() require.NoError(t, err) assert.Equal(t, blkLast.Hash(), td.state.LastBlockHash()) }) } func TestUpdateProptocolVersion(t *testing.T) { td := setup(t) val, err := td.state.ValidatorByAddress(td.state.valKeys[0].Address()) require.NoError(t, err) assert.Equal(t, protocol.ProtocolVersionLatest, val.ProtocolVersion()) } ================================================ FILE: state/validation.go ================================================ package state import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" ) func (st *state) validateBlock(blk *block.Block, round types.Round) error { if blk.Header().Version() > protocol.ProtocolVersionLatest || blk.Header().Version() < st.params.BlockVersion { return ErrInvalidBlockVersion } if blk.Header().StateRoot() != st.stateRoot() { return InvalidStateRootHashError{ Expected: st.stateRoot(), Got: blk.Header().StateRoot(), } } // Verify proposer proposer := st.committee.Proposer(round) if proposer.Address() != blk.Header().ProposerAddress() { return InvalidProposerError{ Expected: proposer.Address(), Got: blk.Header().ProposerAddress(), } } // Validate sortition seed seed := blk.Header().SortitionSeed() if !seed.Verify(proposer.PublicKey(), st.lastInfo.SortitionSeed()) { return ErrInvalidSortitionSeed } return st.validatePrevCertificate(blk.PrevCertificate(), blk.Header().PrevBlockHash()) } // validatePrevCertificate validates certificate for the previous block. func (st *state) validatePrevCertificate(cert *certificate.Certificate, blockHash hash.Hash) error { if cert == nil { if !st.lastInfo.BlockHash().IsUndef() { return ErrInvalidCertificate } } else { err := cert.ValidatePrecommit(st.lastInfo.Validators(), blockHash) if err != nil { return err } } return nil } // validateCurCertificate validates certificate for the current height. func (st *state) validateCurCertificate(cert *certificate.Certificate, blockHash hash.Hash) error { err := cert.ValidatePrecommit(st.committee.Validators(), blockHash) if err != nil { return err } return nil } ================================================ FILE: state/validation_test.go ================================================ package state import ( "fmt" "testing" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/stretchr/testify/require" ) func TestBlockValidation(t *testing.T) { td := setup(t) round := td.RandRound() td.mockTxPool.EXPECT().PrepareBlockTransactions().Return(block.Txs{}).AnyTimes() t.Run("Invalid version, greater than latest", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invBlockVersion := protocol.ProtocolVersionLatest + 1 blk := block.MakeBlock( invBlockVersion, blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, ErrInvalidBlockVersion) // Receiving a block with version 2 and rejects it. // It is possible that the same block would be considered valid by other nodes (Hard Fork). err = td.state.CommitBlock(blk, cert) require.ErrorIs(t, err, ErrInvalidBlockVersion) }) t.Run("Invalid version, less than current", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invBlockVersion := protocol.ProtocolVersion1 blk := block.MakeBlock( invBlockVersion, blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, ErrInvalidBlockVersion) // Receiving a block with version 2 and rejects it. // It is possible that the same block would be considered valid by other nodes (Hard Fork). err = td.state.CommitBlock(blk, cert) require.ErrorIs(t, err, ErrInvalidBlockVersion) }) t.Run("Invalid time", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invBlockTime := td.state.LastBlockTime().Add(-10 * time.Second) blk := block.MakeBlock( blk0.Header().Version(), invBlockTime, blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, InvalidBlockTimeError{ Reason: fmt.Sprintf("block time (%s) is before the last block time (%s)", invBlockTime, td.state.LastBlockTime()), }) err = td.state.CommitBlock(blk, cert) require.NoError(t, err) }) t.Run("Invalid StateRoot", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invStateRoot := td.RandHash() blk := block.MakeBlock( blk0.Header().Version(), blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), invStateRoot, blk0.PrevCertificate(), blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, InvalidStateRootHashError{ Expected: td.state.stateRoot(), Got: blk.Header().StateRoot(), }) err = td.state.CommitBlock(blk, cert) require.ErrorIs(t, err, InvalidStateRootHashError{ Expected: td.state.stateRoot(), Got: blk.Header().StateRoot(), }) }) t.Run("Invalid PrevCertificate", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invPrevCert := certificate.NewCertificate( blk0.PrevCertificate().Height(), blk0.PrevCertificate().Round(), ) invPrevCert.SetSignature( blk0.PrevCertificate().Committers(), blk0.PrevCertificate().Absentees(), td.RandBLSSignature()) blk := block.MakeBlock( blk0.Header().Version(), blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), invPrevCert, blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, crypto.ErrInvalidSignature) err = td.state.CommitBlock(blk, cert) require.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Invalid ProposerAddress", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invProposerAddress := td.RandValAddress() blk := block.MakeBlock( blk0.Header().Version(), blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), blk0.Header().SortitionSeed(), invProposerAddress) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, InvalidProposerError{ Expected: td.state.committee.Proposer(round).Address(), Got: invProposerAddress, }) err = td.state.CommitBlock(blk, cert) require.ErrorIs(t, err, InvalidProposerError{ Expected: td.state.committee.Proposer(round).Address(), Got: invProposerAddress, }) }) t.Run("Invalid SortitionSeed", func(t *testing.T) { blk0, _ := td.makeBlockAndCertificate(t, round) invSortitionSeed, _ := sortition.VerifiableSeedFromBytes(td.RandBLSSignature().Bytes()) blk := block.MakeBlock( blk0.Header().Version(), blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), invSortitionSeed, blk0.Header().ProposerAddress()) cert := td.makeCertificateAndSign(t, blk.Hash(), round) err := td.state.ValidateBlock(blk, round) require.ErrorIs(t, err, ErrInvalidSortitionSeed) err = td.state.CommitBlock(blk, cert) require.ErrorIs(t, err, ErrInvalidSortitionSeed) }) t.Run("Ok", func(t *testing.T) { blk, cert := td.makeBlockAndCertificate(t, round) require.NoError(t, td.state.ValidateBlock(blk, round)) require.NoError(t, td.state.CommitBlock(blk, cert)) }) } ================================================ FILE: store/account.go ================================================ package store import ( lru "github.com/hashicorp/golang-lru/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/util/logger" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/util" ) type accountStore struct { db *leveldb.DB accCache *lru.Cache[crypto.Address, *account.Account] total int32 } func accountKey(addr crypto.Address) []byte { return append(accountPrefix, addr.Bytes()...) } func newAccountStore(db *leveldb.DB, cacheSize int) *accountStore { total := int32(0) addrLruCache, err := lru.New[crypto.Address, *account.Account](cacheSize) if err != nil { logger.Panic("unable to create new instance of lru cache", "error", err) } r := util.BytesPrefix(accountPrefix) iter := db.NewIterator(r, nil) for iter.Next() { total++ } iter.Release() return &accountStore{ db: db, total: total, accCache: addrLruCache, } } func (as *accountStore) hasAccount(addr crypto.Address) bool { ok := as.accCache.Contains(addr) if !ok { ok = tryHas(as.db, accountKey(addr)) } return ok } func (as *accountStore) account(addr crypto.Address) (*account.Account, error) { acc, ok := as.accCache.Get(addr) if ok { return acc.Clone(), nil } rawData, err := tryGet(as.db, accountKey(addr)) if err != nil { return nil, err } acc, err = account.FromBytes(rawData) if err != nil { return nil, err } as.accCache.Add(addr, acc) return acc.Clone(), nil } func (as *accountStore) iterateAccounts(consumer func(crypto.Address, *account.Account) (stop bool)) { r := util.BytesPrefix(accountPrefix) iter := as.db.NewIterator(r, nil) for iter.Next() { key := iter.Key() value := iter.Value() acc, err := account.FromBytes(value) if err != nil { logger.Panic("unable to decode account", "error", err) } var addr crypto.Address copy(addr[:], key[1:]) stopped := consumer(addr, acc) if stopped { return } } iter.Release() } // This function takes ownership of the account pointer. // It is important that the caller should not modify the account data and // keep it immutable. func (as *accountStore) updateAccount(batch *leveldb.Batch, addr crypto.Address, acc *account.Account) { data, err := acc.Bytes() if err != nil { logger.Panic("unable to encode account", "error", err) } if !as.hasAccount(addr) { as.total++ } as.accCache.Add(addr, acc) batch.Put(accountKey(addr), data) } ================================================ FILE: store/account_test.go ================================================ package store import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAccountCounter(t *testing.T) { td := setup(t, nil) acc, addr := td.GenerateTestAccount() t.Run("Add new account, should increase the total accounts number", func(t *testing.T) { assert.Zero(t, td.store.TotalAccounts()) td.store.UpdateAccount(addr, acc) require.NoError(t, td.store.WriteBatch()) assert.Equal(t, int32(1), td.store.TotalAccounts()) }) t.Run("Update account, should not increase the total accounts number", func(t *testing.T) { acc.AddToBalance(1) td.store.UpdateAccount(addr, acc) require.NoError(t, td.store.WriteBatch()) assert.Equal(t, int32(1), td.store.TotalAccounts()) }) t.Run("Get account", func(t *testing.T) { acc1, err := td.store.Account(addr) require.NoError(t, err) assert.Equal(t, acc1.Hash(), acc.Hash()) assert.Equal(t, int32(1), td.store.TotalAccounts()) assert.True(t, td.store.HasAccount(addr)) }) } func TestAccountBatchSaving(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) t.Run("Add some accounts", func(t *testing.T) { for i := int32(0); i < total; i++ { acc, addr := td.GenerateTestAccount(testsuite.AccountWithNumber(i)) td.store.UpdateAccount(addr, acc) } require.NoError(t, td.store.WriteBatch()) assert.Equal(t, total, td.store.TotalAccounts()) }) t.Run("Close and load db", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) assert.Equal(t, total, store.TotalAccounts()) }) } func TestAccountByAddress(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) var lastAddr crypto.Address t.Run("Add some accounts", func(t *testing.T) { for i := int32(0); i < total; i++ { acc, addr := td.GenerateTestAccount(testsuite.AccountWithNumber(i)) td.store.UpdateAccount(addr, acc) lastAddr = addr } require.NoError(t, td.store.WriteBatch()) assert.Equal(t, total, td.store.TotalAccounts()) }) t.Run("Non existing account", func(t *testing.T) { addr := td.RandAccAddress() acc, err := td.store.Account(addr) has := td.store.HasAccount(addr) assert.False(t, has) require.Error(t, err) assert.Nil(t, acc) }) t.Run("Reopen the store", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) acc, err := store.Account(lastAddr) require.NoError(t, err) require.NotNil(t, acc) assert.Equal(t, total-1, acc.Number()) }) } func TestIterateAccounts(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) hashes1 := []hash.Hash{} for i := int32(0); i < total; i++ { acc, addr := td.GenerateTestAccount(testsuite.AccountWithNumber(i)) td.store.UpdateAccount(addr, acc) hashes1 = append(hashes1, acc.Hash()) } require.NoError(t, td.store.WriteBatch()) hashes2 := []hash.Hash{} td.store.IterateAccounts(func(_ crypto.Address, acc *account.Account) bool { hashes2 = append(hashes2, acc.Hash()) return false }) assert.ElementsMatch(t, hashes1, hashes2) stopped := false td.store.IterateAccounts(func(_ crypto.Address, acc *account.Account) bool { if acc.Hash() == hashes1[0] { stopped = true } return stopped }) assert.True(t, stopped) } func TestAccountDeepCopy(t *testing.T) { td := setup(t, nil) acc1, addr := td.GenerateTestAccount() td.store.UpdateAccount(addr, acc1) acc2, _ := td.store.Account(addr) acc2.AddToBalance(1) accCache, _ := td.store.accountStore.accCache.Get(addr) assert.NotEqual(t, acc2.Hash(), accCache.Hash()) } ================================================ FILE: store/block.go ================================================ package store import ( "bytes" lru "github.com/hashicorp/golang-lru/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/encoding" "github.com/pactus-project/pactus/util/pairslice" "github.com/syndtr/goleveldb/leveldb" ) func blockKey(height types.Height) []byte { return append(blockPrefix, height.BytesLE()...) } func publicKeyKey(addr crypto.Address) []byte { return append(publicKeyPrefix, addr.Bytes()...) } func blockHashKey(h hash.Hash) []byte { return append(blockHeightPrefix, h.Bytes()...) } type blockStore struct { db *leveldb.DB pubKeyCache *lru.Cache[crypto.Address, crypto.PublicKey] seedCache *pairslice.PairSlice[types.Height, *sortition.VerifiableSeed] seedCacheWindow uint32 } func newBlockStore(db *leveldb.DB, seedCacheWindow uint32, publicKeyCacheSize int) *blockStore { pubKeyCache, err := lru.New[crypto.Address, crypto.PublicKey](publicKeyCacheSize) if err != nil { return nil } return &blockStore{ db: db, seedCache: pairslice.New[types.Height, *sortition.VerifiableSeed](int(seedCacheWindow)), pubKeyCache: pubKeyCache, seedCacheWindow: seedCacheWindow, } } func (bs *blockStore) saveBlock(batch *leveldb.Batch, height types.Height, blk *block.Block) []blockRegion { blockHash := blk.Hash() regs := make([]blockRegion, blk.Transactions().Len()) buf := bytes.NewBuffer(make([]byte, 0, blk.SerializeSize()+hash.HashSize)) err := encoding.WriteElement(buf, &blockHash) if err != nil { panic(err) // Should we panic? } err = blk.Header().Encode(buf) if err != nil { panic(err) // Should we panic? } if blk.PrevCertificate() != nil { err = blk.PrevCertificate().Encode(buf) if err != nil { panic(err) // Should we panic? } } err = encoding.WriteVarInt(buf, uint64(blk.Transactions().Len())) if err != nil { panic(err) // Should we panic? } for i, trx := range blk.Transactions() { offset := buf.Len() regs[i].height = height regs[i].offset = uint32(offset) var encodeOpts []tx.EncodeOption pubKey := trx.PublicKey() if pubKey != nil { if !bs.hasPublicKey(trx.Payload().Signer()) { publicKeyKey := publicKeyKey(trx.Payload().Signer()) batch.Put(publicKeyKey, pubKey.Bytes()) } else { // we have indexed this public key, so we can skip encoding it encodeOpts = append(encodeOpts, tx.StripPublicKey()) } } err := trx.Encode(buf, encodeOpts...) if err != nil { panic(err) // Should we panic? } regs[i].length = uint32(buf.Len() - offset) } blockKey := blockKey(height) blockHashKey := blockHashKey(blockHash) batch.Put(blockKey, buf.Bytes()) batch.Put(blockHashKey, height.BytesLE()) sortitionSeed := blk.Header().SortitionSeed() bs.addToCache(height, sortitionSeed) return regs } func (bs *blockStore) block(height types.Height) ([]byte, error) { data, err := tryGet(bs.db, blockKey(height)) if err != nil { return nil, err } return data, nil } func (bs *blockStore) blockHeight(h hash.Hash) types.Height { data, err := tryGet(bs.db, blockHashKey(h)) if err != nil { return 0 } return types.HeightFromBytesLE(data) } func (bs *blockStore) sortitionSeed(blockHeight types.Height) *sortition.VerifiableSeed { startHeight, _, _ := bs.seedCache.First() if blockHeight < startHeight { return nil } index := blockHeight - startHeight _, sortitionSeed, ok := bs.seedCache.Get(int(index)) if !ok { return nil } return sortitionSeed } func (bs *blockStore) hasBlock(height types.Height) bool { return tryHas(bs.db, blockKey(height)) } func (bs *blockStore) publicKey(addr crypto.Address) (crypto.PublicKey, error) { if pubKey, ok := bs.pubKeyCache.Get(addr); ok { return pubKey, nil } data, err := tryGet(bs.db, publicKeyKey(addr)) if err != nil { return nil, err } var pubKey crypto.PublicKey switch addr.Type() { case crypto.AddressTypeValidator, crypto.AddressTypeBLSAccount: pubKey, err = bls.PublicKeyFromBytes(data) if err != nil { return nil, err } case crypto.AddressTypeEd25519Account: pubKey, err = ed25519.PublicKeyFromBytes(data) if err != nil { return nil, err } case crypto.AddressTypeTreasury: panic("unreachable") default: return nil, PublicKeyNotFoundError{Address: addr} } bs.pubKeyCache.Add(addr, pubKey) return pubKey, err } func (bs *blockStore) hasPublicKey(addr crypto.Address) bool { ok := bs.pubKeyCache.Contains(addr) if !ok { ok = tryHas(bs.db, publicKeyKey(addr)) } return ok } func (bs *blockStore) addToCache(blockHeight types.Height, sortitionSeed sortition.VerifiableSeed) { bs.seedCache.Append(blockHeight, &sortitionSeed) if bs.seedCache.Len() > int(bs.seedCacheWindow) { bs.seedCache.RemoveFirst() } } ================================================ FILE: store/block_test.go ================================================ package store import ( "bytes" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBlockStore(t *testing.T) { td := setup(t, nil) lastCert := td.store.LastCertificate() lastHeight := lastCert.Height() nextBlk, nextCert := td.GenerateTestBlock(lastHeight + 1) t.Run("Add block, don't batch write", func(t *testing.T) { td.store.SaveBlock(nextBlk, nextCert) b2, err := td.store.Block(lastHeight + 1) require.Error(t, err) assert.Nil(t, b2) }) t.Run("Add block, batch write", func(t *testing.T) { td.store.SaveBlock(nextBlk, nextCert) require.NoError(t, td.store.WriteBatch()) cBlk, err := td.store.Block(lastHeight + 1) require.NoError(t, err) assert.Equal(t, lastHeight+1, cBlk.Height) d, _ := nextBlk.Bytes() assert.True(t, bytes.Equal(cBlk.Data, d)) cert := td.store.LastCertificate() require.NoError(t, err) assert.Equal(t, nextCert.Hash(), cert.Hash()) }) } func TestSortitionSeed(t *testing.T) { conf := testConfig() conf.SeedCacheWindow = 7 td := setup(t, conf) lastHeight := td.store.LastCertificate().Height() t.Run("Test height zero", func(t *testing.T) { assert.Nil(t, td.store.SortitionSeed(0)) }) t.Run("Test non existing height", func(t *testing.T) { assert.Nil(t, td.store.SortitionSeed(lastHeight+1)) }) t.Run("Test not cached height", func(t *testing.T) { assert.Nil(t, td.store.SortitionSeed(3)) }) t.Run("OK", func(t *testing.T) { committedBlk, _ := td.store.Block(5) blk, _ := committedBlk.ToBlock() expectedSortition := blk.Header().SortitionSeed() assert.Equal(t, &expectedSortition, td.store.SortitionSeed(5)) }) } ================================================ FILE: store/config.go ================================================ package store import ( "path/filepath" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util" ) const blockPerDay = 8640 // Config defines parameters for the store module. type Config struct { Path string `toml:"path"` RetentionDays uint32 `toml:"retention_days"` // Private configs TxCacheWindow uint32 `toml:"-"` SeedCacheWindow uint32 `toml:"-"` AccountCacheSize int `toml:"-"` PublicKeyCacheSize int `toml:"-"` BannedAddrs map[crypto.Address]bool `toml:"-"` } func DefaultConfig() *Config { return &Config{ Path: "data", RetentionDays: 10, TxCacheWindow: 1024, SeedCacheWindow: 1024, AccountCacheSize: 1024, PublicKeyCacheSize: 1024, BannedAddrs: map[crypto.Address]bool{}, } } func (conf *Config) DataPath() string { return util.MakeAbs(conf.Path) } func (conf *Config) StorePath() string { return filepath.Join(conf.DataPath(), "store.db") } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { if !util.IsValidDirPath(conf.Path) { return ConfigError{ Reason: "path is not valid", } } if conf.TxCacheWindow == 0 || conf.SeedCacheWindow == 0 { return ConfigError{ Reason: "cache window set to zero", } } if conf.AccountCacheSize == 0 || conf.PublicKeyCacheSize == 0 { return ConfigError{ Reason: "cache size set to zero", } } if conf.RetentionDays < 10 { return ConfigError{ Reason: "retention days can't be less than 10 days", } } return nil } func (conf *Config) RetentionBlocks() uint32 { return conf.RetentionDays * blockPerDay } ================================================ FILE: store/config_test.go ================================================ package store import ( "runtime" "testing" "github.com/pactus-project/pactus/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConfigBasicCheck(t *testing.T) { tests := []struct { name string expectedErr error updateFn func(c *Config) }{ { name: "Invalid Path", expectedErr: ConfigError{ Reason: "path is not valid", }, updateFn: func(c *Config) { c.Path = "/invalid:path/\x00*folder?\\CON" }, }, { name: "Invalid TxCacheWindow", expectedErr: ConfigError{ Reason: "cache window set to zero", }, updateFn: func(c *Config) { c.TxCacheWindow = 0 }, }, { name: "Invalid AccountCacheSize", expectedErr: ConfigError{ Reason: "cache size set to zero", }, updateFn: func(c *Config) { c.AccountCacheSize = 0 }, }, { name: "Invalid RetentionDays", expectedErr: ConfigError{ Reason: "retention days can't be less than 10 days", }, updateFn: func(c *Config) { c.RetentionDays = 1 }, }, { name: "DefaultConfig", updateFn: func(*Config) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() tt.updateFn(conf) if tt.expectedErr != nil { err := conf.BasicCheck() require.ErrorIs(t, err, tt.expectedErr, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } func TestConfigStorePath(t *testing.T) { conf := DefaultConfig() conf.Path = util.TempDirPath() require.NoError(t, conf.BasicCheck()) if runtime.GOOS != "windows" { assert.Equal(t, conf.Path+"/store.db", conf.StorePath()) } else { assert.Equal(t, conf.Path+"\\store.db", conf.StorePath()) } } ================================================ FILE: store/errors.go ================================================ package store import ( "fmt" "github.com/pactus-project/pactus/crypto" ) // ConfigError is returned when the store configuration is invalid. type ConfigError struct { Reason string } func (e ConfigError) Error() string { return e.Reason } // PublicKeyNotFoundError is returned when the public key associated with an address // is not found in the store. type PublicKeyNotFoundError struct { Address crypto.Address } func (e PublicKeyNotFoundError) Error() string { return fmt.Sprintf("public key not found for: %s", e.Address.String()) } ================================================ FILE: store/interface.go ================================================ package store import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" ) // TODO: store blocks inside flat files (to reduce the size of levelDB) // Bitcoin impl: // https://github.com/btcsuite/btcd/blob/0886f1e5c1fd28ad24aaca4dbccc5f4ab85e58ca/database/ffldb/blockio.go // https://bitcoindev.network/understanding-the-data/ // TODO: How to undo or rollback at least for last 21 blocks type CommittedBlock struct { store Store BlockHash hash.Hash Height types.Height Data []byte } func (s *CommittedBlock) ToBlock() (*block.Block, error) { blk, err := block.FromBytes(s.Data) if err != nil { return nil, err } trxs := blk.Transactions() for i := 0; i < trxs.Len(); i++ { trx := trxs[i] if trx.IsPublicKeyStriped() { pub, err := s.store.PublicKey(trx.Payload().Signer()) if err != nil { return nil, PublicKeyNotFoundError{ Address: trx.Payload().Signer(), } } trx.SetPublicKey(pub) } } return blk, nil } type CommittedTx struct { store *store TxID tx.ID Height types.Height BlockTime uint32 Data []byte } func (s *CommittedTx) ToTx() (*tx.Tx, error) { trx, err := tx.FromBytes(s.Data) if err != nil { return nil, err } if trx.IsPublicKeyStriped() { pub, err := s.store.PublicKey(trx.Payload().Signer()) if err != nil { return nil, PublicKeyNotFoundError{ Address: trx.Payload().Signer(), } } trx.SetPublicKey(pub) } return trx, nil } type Reader interface { Block(height types.Height) (*CommittedBlock, error) BlockHeight(h hash.Hash) types.Height BlockHash(height types.Height) hash.Hash SortitionSeed(blockHeight types.Height) *sortition.VerifiableSeed Transaction(txID tx.ID) (*CommittedTx, error) RecentTransaction(txID tx.ID) bool PublicKey(addr crypto.Address) (crypto.PublicKey, error) HasPublicKey(addr crypto.Address) bool HasAccount(crypto.Address) bool Account(addr crypto.Address) (*account.Account, error) TotalAccounts() int32 HasValidator(addr crypto.Address) bool ValidatorAddresses() []crypto.Address Validator(addr crypto.Address) (*validator.Validator, error) ValidatorByNumber(num int32) (*validator.Validator, error) IterateValidators(consumer func(*validator.Validator) (stop bool)) IterateAccounts(consumer func(crypto.Address, *account.Account) (stop bool)) TotalValidators() int32 ActiveValidators() int32 LastCertificate() *certificate.Certificate IsBanned(addr crypto.Address) bool IsPruned() bool PruningHeight() types.Height } type Store interface { Reader UpdateAccount(addr crypto.Address, acc *account.Account) UpdateValidator(val *validator.Validator) UpdateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) SaveBlock(blk *block.Block, cert *certificate.Certificate) Prune(callback func(pruned bool, pruningHeight types.Height) bool) error WriteBatch() error Close() } ================================================ FILE: store/mock.go ================================================ package store import ( "errors" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" ) var _ Store = &MockStore{} // MockStore is a mock implementation of the Store interface for testing. type MockStore struct { ts *testsuite.TestSuite Blocks map[types.Height]*block.Block Accounts map[crypto.Address]*account.Account Validators map[crypto.Address]*validator.Validator LastCert *certificate.Certificate LastHeight types.Height } func MockingStore(ts *testsuite.TestSuite) *MockStore { return &MockStore{ ts: ts, Blocks: make(map[types.Height]*block.Block), Accounts: make(map[crypto.Address]*account.Account), Validators: make(map[crypto.Address]*validator.Validator), } } func (m *MockStore) Block(height types.Height) (*CommittedBlock, error) { blk, ok := m.Blocks[height] if ok { data, _ := blk.Bytes() return &CommittedBlock{ store: m, BlockHash: blk.Hash(), Height: height, Data: data, }, nil } return nil, errors.New("not found") } func (m *MockStore) BlockHash(height types.Height) hash.Hash { b, ok := m.Blocks[height] if ok { return b.Hash() } return hash.UndefHash } func (m *MockStore) BlockHeight(h hash.Hash) types.Height { for height, b := range m.Blocks { if b.Hash() == h { return height } } return 0 } func (m *MockStore) SortitionSeed(blockHeight types.Height) *sortition.VerifiableSeed { if blk, ok := m.Blocks[blockHeight]; ok { sortitionSeed := blk.Header().SortitionSeed() return &sortitionSeed } return nil } func (m *MockStore) PublicKey(addr crypto.Address) (crypto.PublicKey, error) { for _, blk := range m.Blocks { for _, trx := range blk.Transactions() { if trx.Payload().Signer() == addr { return trx.PublicKey(), nil } } } for _, val := range m.Validators { if val.Address() == addr { return val.PublicKey(), nil } } return nil, ErrNotFound } func (m *MockStore) HasPublicKey(addr crypto.Address) bool { pub, _ := m.PublicKey(addr) return pub != nil } func (m *MockStore) Transaction(txID tx.ID) (*CommittedTx, error) { for height, blk := range m.Blocks { for _, trx := range blk.Transactions() { if trx.ID() == txID { data, _ := trx.Bytes() return &CommittedTx{ TxID: txID, Height: height, BlockTime: blk.Header().UnixTime(), Data: data, }, nil } } } return nil, errors.New("not found") } func (m *MockStore) RecentTransaction(txID tx.ID) bool { for _, blk := range m.Blocks { for _, trx := range blk.Transactions() { if trx.ID() == txID { return true } } } return false } func (m *MockStore) HasAccount(addr crypto.Address) bool { _, ok := m.Accounts[addr] return ok } func (m *MockStore) Account(addr crypto.Address) (*account.Account, error) { a, ok := m.Accounts[addr] if ok { return a.Clone(), nil } return nil, errors.New("not found") } func (m *MockStore) AccountByNumber(number int32) (*account.Account, error) { for _, v := range m.Accounts { if v.Number() == number { return v.Clone(), nil } } return nil, errors.New("not found") } func (m *MockStore) UpdateAccount(addr crypto.Address, acc *account.Account) { m.Accounts[addr] = acc } func (m *MockStore) TotalAccounts() int32 { return int32(len(m.Accounts)) } func (m *MockStore) HasValidator(addr crypto.Address) bool { _, ok := m.Validators[addr] return ok } func (m *MockStore) ValidatorAddresses() []crypto.Address { addrs := make([]crypto.Address, 0, len(m.Validators)) for addr := range m.Validators { addrs = append(addrs, addr) } return addrs } func (m *MockStore) Validator(addr crypto.Address) (*validator.Validator, error) { v, ok := m.Validators[addr] if ok { return v.Clone(), nil } return nil, ErrNotFound } func (m *MockStore) ValidatorByNumber(num int32) (*validator.Validator, error) { for _, v := range m.Validators { if v.Number() == num { return v.Clone(), nil } } return nil, errors.New("not found") } func (m *MockStore) UpdateValidator(val *validator.Validator) { m.Validators[val.Address()] = val } func (m *MockStore) TotalValidators() int32 { return int32(len(m.Validators)) } func (m *MockStore) ActiveValidators() int32 { return int32(len(m.Validators)) } func (*MockStore) Close() {} func (m *MockStore) HasAnyBlock() bool { return len(m.Blocks) > 0 } func (m *MockStore) IterateAccounts(consumer func(crypto.Address, *account.Account) (stop bool)) { for addr, acc := range m.Accounts { stopped := consumer(addr, acc.Clone()) if stopped { return } } } func (m *MockStore) IterateValidators(consumer func(*validator.Validator) (stop bool)) { for _, val := range m.Validators { stopped := consumer(val.Clone()) if stopped { return } } } func (m *MockStore) SaveBlock(blk *block.Block, cert *certificate.Certificate) { m.Blocks[cert.Height()] = blk m.LastHeight = cert.Height() m.LastCert = cert } func (m *MockStore) LastCertificate() *certificate.Certificate { if m.LastHeight == 0 { return nil } return m.LastCert } func (*MockStore) WriteBatch() error { return nil } func (m *MockStore) AddTestValidator(options ...testsuite.ValidatorMakerOption) *validator.Validator { val := m.ts.GenerateTestValidator(options...) m.UpdateValidator(val) return val } func (m *MockStore) AddTestAccount(options ...testsuite.AccountMakerOption) (crypto.Address, *account.Account) { acc, addr := m.ts.GenerateTestAccount(options...) m.UpdateAccount(addr, acc) return addr, acc } func (m *MockStore) AddTestBlock(height types.Height) *block.Block { blk, cert := m.ts.GenerateTestBlock(height) m.SaveBlock(blk, cert) return blk } func (m *MockStore) RandomTestAcc() (crypto.Address, *account.Account) { for addr, acc := range m.Accounts { // Do not return the Treasury address for tests, // as it may cause some tests to randomly fail. if addr == crypto.TreasuryAddress { continue } return addr, acc } panic("no account in sandbox") } func (m *MockStore) RandomTestVal() *validator.Validator { for _, val := range m.Validators { return val } panic("no validator in sandbox") } func (*MockStore) IsBanned(_ crypto.Address) bool { return false } func (*MockStore) Prune(_ func(_ bool, _ types.Height) bool) error { return nil } func (*MockStore) IsPruned() bool { return false } func (*MockStore) PruningHeight() types.Height { return 0 } func (m *MockStore) UpdateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) { val, ok := m.Validators[addr] if ok { val.UpdateProtocolVersion(ver) } } ================================================ FILE: store/store.go ================================================ package store import ( "bytes" "errors" "sync" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/encoding" "github.com/pactus-project/pactus/util/logger" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" ) var ( ErrNotFound = errors.New("not found") ErrBadOffset = errors.New("offset is out of range") ) const ( lastStoreVersion = int32(1) ) var ( lastInfoKey = []byte{0x00} blockPrefix = []byte{0x01} txPrefix = []byte{0x03} accountPrefix = []byte{0x05} validatorPrefix = []byte{0x07} blockHeightPrefix = []byte{0x09} publicKeyPrefix = []byte{0x0b} ) func tryGet(db *leveldb.DB, key []byte) ([]byte, error) { data, err := db.Get(key, nil) if err != nil { // Probably key doesn't exist in database logger.Trace("database `get` error", "error", err, "key", key) return nil, err } return data, nil } func tryHas(db *leveldb.DB, key []byte) bool { has, err := db.Has(key, nil) if err != nil { logger.Error("database `has` error", "error", err, "key", key) return false } return has } type store struct { lk sync.RWMutex config *Config db *leveldb.DB batch *leveldb.Batch blockStore *blockStore txStore *txStore accountStore *accountStore validatorStore *validatorStore isPruned bool } func NewStore(conf *Config) (Store, error) { options := &opt.Options{ Strict: opt.DefaultStrict, Compression: opt.NoCompression, } db, err := leveldb.OpenFile(conf.StorePath(), options) if err != nil { return nil, err } store := &store{ config: conf, db: db, batch: new(leveldb.Batch), blockStore: newBlockStore(db, conf.SeedCacheWindow, conf.PublicKeyCacheSize), txStore: newTxStore(db, conf.TxCacheWindow), accountStore: newAccountStore(db, conf.AccountCacheSize), validatorStore: newValidatorStore(db), isPruned: false, } lastCert := store.lastCertificate() if lastCert == nil { return store, nil } // Check if the node is pruned by checking genesis block. cBlkOne, _ := store.block(1) if cBlkOne == nil { store.isPruned = true } currentHeight := lastCert.Height() startHeight := types.Height(1) if currentHeight > types.Height(conf.TxCacheWindow) { startHeight = currentHeight.SafeDecrease(conf.TxCacheWindow) } for height := startHeight; height < currentHeight+1; height++ { cBlk, err := store.block(height) if err != nil { return nil, err } blk, err := cBlk.ToBlock() if err != nil { return nil, err } txs := blk.Transactions() for _, transaction := range txs { store.txStore.addToCache(transaction.ID(), height) } sortitionSeed := blk.Header().SortitionSeed() store.blockStore.addToCache(height, sortitionSeed) } return store, nil } func (s *store) Close() { s.lk.Lock() defer s.lk.Unlock() err := s.db.Close() if err != nil && !errors.Is(err, leveldb.ErrClosed) { logger.Error("error on closing store", "error", err) } } func (s *store) SaveBlock(blk *block.Block, cert *certificate.Certificate) { s.lk.Lock() defer s.lk.Unlock() height := cert.Height() regs := s.blockStore.saveBlock(s.batch, height, blk) s.txStore.saveTxs(s.batch, blk.Transactions(), regs) s.txStore.pruneCache(height) // Removing old block from prune node store. if s.isPruned && uint32(height) > s.config.RetentionBlocks() { pruneHeight := height.SafeDecrease(s.config.RetentionBlocks()) deleted, err := s.pruneBlock(pruneHeight) if err != nil { panic(err) } if deleted { // TODO: Let's use state logger in store[?]. logger.Debug("old block is pruned", "height", pruneHeight) } else { logger.Warn("unable to prune the old block", "height", pruneHeight, "error", err) } } // Save last certificate: [version: 4 bytes]+[certificate: variant] buf := bytes.NewBuffer(make([]byte, 0, 4+cert.SerializeSize())) err := encoding.WriteElements(buf, lastStoreVersion) if err != nil { panic(err) } err = cert.Encode(buf) if err != nil { panic(err) } s.batch.Put(lastInfoKey, buf.Bytes()) } func (s *store) Block(height types.Height) (*CommittedBlock, error) { s.lk.Lock() defer s.lk.Unlock() return s.block(height) } func (s *store) block(height types.Height) (*CommittedBlock, error) { data, err := s.blockStore.block(height) if err != nil { return nil, err } blockHash, err := hash.FromBytes(data[0:hash.HashSize]) if err != nil { return nil, err } return &CommittedBlock{ store: s, BlockHash: blockHash, Height: height, Data: data[hash.HashSize:], }, nil } func (s *store) BlockHeight(h hash.Hash) types.Height { s.lk.Lock() defer s.lk.Unlock() return s.blockStore.blockHeight(h) } func (s *store) BlockHash(height types.Height) hash.Hash { s.lk.Lock() defer s.lk.Unlock() data, err := s.blockStore.block(height) if err == nil { blockHash, _ := hash.FromBytes(data[0:hash.HashSize]) return blockHash } return hash.UndefHash } func (s *store) SortitionSeed(blockHeight types.Height) *sortition.VerifiableSeed { s.lk.Lock() defer s.lk.Unlock() return s.blockStore.sortitionSeed(blockHeight) } func (s *store) PublicKey(addr crypto.Address) (crypto.PublicKey, error) { s.lk.RLock() defer s.lk.RUnlock() return s.blockStore.publicKey(addr) } func (s *store) HasPublicKey(addr crypto.Address) bool { s.lk.RLock() defer s.lk.RUnlock() return tryHas(s.db, publicKeyKey(addr)) } func (s *store) Transaction(txID tx.ID) (*CommittedTx, error) { s.lk.Lock() defer s.lk.Unlock() pos, err := s.txStore.tx(txID) if err != nil { return nil, err } data, err := s.blockStore.block(pos.height) if err != nil { return nil, err } start := pos.offset end := pos.offset + pos.length if end > uint32(len(data)) { return nil, ErrBadOffset } blockTime := util.BytesToUint32LE(data[hash.HashSize+1 : hash.HashSize+5]) return &CommittedTx{ store: s, TxID: txID, Height: pos.height, BlockTime: blockTime, Data: data[start:end], }, nil } // RecentTransaction checks if there is a transaction with the given ID // within the last 8640 blocks. // The time window for recent transactions is determined by the // TransactionToLive interval, which is part of the consensus parameters. func (s *store) RecentTransaction(txID tx.ID) bool { s.lk.RLock() defer s.lk.RUnlock() return s.txStore.recentTransaction(txID) } func (s *store) HasAccount(addr crypto.Address) bool { s.lk.RLock() defer s.lk.RUnlock() return s.accountStore.hasAccount(addr) } func (s *store) Account(addr crypto.Address) (*account.Account, error) { s.lk.RLock() defer s.lk.RUnlock() return s.accountStore.account(addr) } // TotalAccounts returns the total number of accounts. func (s *store) TotalAccounts() int32 { s.lk.Lock() defer s.lk.Unlock() return s.accountStore.total } func (s *store) IterateAccounts(consumer func(crypto.Address, *account.Account) (stop bool)) { s.lk.RLock() defer s.lk.RUnlock() s.accountStore.iterateAccounts(consumer) } func (s *store) UpdateAccount(addr crypto.Address, acc *account.Account) { s.lk.Lock() defer s.lk.Unlock() s.accountStore.updateAccount(s.batch, addr, acc) } func (s *store) HasValidator(addr crypto.Address) bool { s.lk.RLock() defer s.lk.RUnlock() return s.validatorStore.hasValidator(addr) } func (s *store) ValidatorAddresses() []crypto.Address { s.lk.RLock() defer s.lk.RUnlock() return s.validatorStore.ValidatorAddresses() } func (s *store) Validator(addr crypto.Address) (*validator.Validator, error) { s.lk.RLock() defer s.lk.RUnlock() return s.validatorStore.validator(addr) } func (s *store) ValidatorByNumber(num int32) (*validator.Validator, error) { s.lk.RLock() defer s.lk.RUnlock() return s.validatorStore.validatorByNumber(num) } // TotalValidators returns the total number of validators. func (s *store) TotalValidators() int32 { s.lk.RLock() defer s.lk.RUnlock() return s.validatorStore.total } // ActiveValidators returns the number of active (not unbonded) validators. func (s *store) ActiveValidators() int32 { s.lk.RLock() defer s.lk.RUnlock() return s.validatorStore.active } func (s *store) IterateValidators(consumer func(*validator.Validator) (stop bool)) { s.lk.RLock() defer s.lk.RUnlock() s.validatorStore.iterateValidators(consumer) } func (s *store) UpdateValidator(acc *validator.Validator) { s.lk.Lock() defer s.lk.Unlock() s.validatorStore.updateValidator(s.batch, acc) } func (s *store) UpdateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) { s.lk.Lock() defer s.lk.Unlock() s.validatorStore.updateValidatorProtocolVersion(addr, ver) } func (s *store) LastCertificate() *certificate.Certificate { s.lk.RLock() defer s.lk.RUnlock() return s.lastCertificate() } func (s *store) lastCertificate() *certificate.Certificate { data, _ := tryGet(s.db, lastInfoKey) if data == nil { // Genesis block return nil } reader := bytes.NewReader(data) version := int32(0) cert := new(certificate.Certificate) err := encoding.ReadElements(reader, &version) if err != nil { return nil } err = cert.Decode(reader) if err != nil { return nil } return cert } func (s *store) WriteBatch() error { s.lk.Lock() defer s.lk.Unlock() return s.writeBatch() } func (s *store) writeBatch() error { if err := s.db.Write(s.batch, nil); err != nil { // TODO: Should we panic here? // The store is unreliable if the stored data does not match the cached data. return err } s.batch.Reset() return nil } func (s *store) IsBanned(addr crypto.Address) bool { return s.config.BannedAddrs[addr] } // IsPruned returns true if the store is in prune mode, otherwise false. func (s *store) IsPruned() bool { return s.isPruned } // PruningHeight returns the height at which blocks will be pruned if the store is in prune mode. // If the store is not in prune mode, it returns 0. func (s *store) PruningHeight() types.Height { s.lk.RLock() defer s.lk.RUnlock() if !s.isPruned { return 0 } // TODO: it can be optimized (and safer?) by keeping the last block height in memory. cert := s.lastCertificate() return cert.Height().SafeDecrease(s.config.RetentionBlocks()) } // Prune iterates over all blocks from the pruning height to the genesis block and prunes them. // The pruning height is `LastBlockHeight - RetentionBlocks`. // The callback function is called after each block is pruned and can cancel the process. func (s *store) Prune(callback func(pruned bool, pruningHeight types.Height) bool) error { s.lk.Lock() defer s.lk.Unlock() cert := s.lastCertificate() // Store is at the genesis height if cert == nil { return nil } retentionBlocks := s.config.RetentionBlocks() pruningHeight := cert.Height().SafeDecrease(retentionBlocks) for height := pruningHeight; height >= 1; height-- { deleted, err := s.pruneBlock(height) if err != nil { return err } if err := s.writeBatch(); err != nil { return err } if callback(deleted, height) { // canceled break } } return nil } // pruneBlock removes a block and all transactions inside the block from the store. // It accepts a block height to prune, and returns a boolean that // indicate whether the block at the specified height existed and pruned, // or did not exist, along with any encountered errors. func (s *store) pruneBlock(blockHeight types.Height) (bool, error) { if !s.blockStore.hasBlock(blockHeight) { return false, nil } cBlock, err := s.block(blockHeight) if err != nil { return false, err } blk, err := block.FromBytes(cBlock.Data) if err != nil { return false, err } s.batch.Delete(blockHashKey(blk.Hash())) s.batch.Delete(blockKey(blockHeight)) for _, t := range blk.Transactions() { s.batch.Delete(t.ID().Bytes()) } return true, nil } ================================================ FILE: store/store_test.go ================================================ package store import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite store *store } func testConfig() *Config { return &Config{ Path: util.TempDirPath(), TxCacheWindow: 1024, SeedCacheWindow: 1024, AccountCacheSize: 1024, PublicKeyCacheSize: 1024, BannedAddrs: make(map[crypto.Address]bool), } } func setup(t *testing.T, config *Config) *testData { t.Helper() ts := testsuite.NewTestSuite(t) if config == nil { config = testConfig() } storeInt, err := NewStore(config) require.NoError(t, err) assert.False(t, storeInt.IsPruned(), "empty store should not be in prune mode") assert.Zero(t, storeInt.PruningHeight(), "pruning height should be zero for an empty store") td := &testData{ TestSuite: ts, store: storeInt.(*store), } // Save 10 blocks for height := types.Height(0); height < 10; height++ { blk, cert := td.GenerateTestBlock(height + 1) td.store.SaveBlock(blk, cert) require.NoError(t, td.store.WriteBatch()) } return td } func TestReopenStore(t *testing.T) { td := setup(t, nil) td.store.Close() store, _ := NewStore(td.store.config) assert.False(t, store.IsPruned()) assert.Zero(t, store.PruningHeight()) assert.Equal(t, types.Height(10), store.LastCertificate().Height()) } func TestBlockHash(t *testing.T) { td := setup(t, nil) sb, _ := td.store.Block(1) assert.Equal(t, hash.UndefHash, td.store.BlockHash(0)) assert.Equal(t, hash.UndefHash, td.store.BlockHash(types.Height(util.MaxUint32))) assert.Equal(t, sb.BlockHash, td.store.BlockHash(1)) } func TestBlockHeight(t *testing.T) { td := setup(t, nil) sb, _ := td.store.Block(1) assert.Equal(t, types.Height(0), td.store.BlockHeight(hash.UndefHash)) assert.Equal(t, types.Height(0), td.store.BlockHeight(td.RandHash())) assert.Equal(t, types.Height(1), td.store.BlockHeight(sb.BlockHash)) } func TestUnknownTransactionID(t *testing.T) { td := setup(t, nil) trx, err := td.store.Transaction(td.RandHash()) require.Error(t, err) assert.Nil(t, trx) } func TestWriteAndClosePeacefully(t *testing.T) { td := setup(t, nil) // After closing the database, writing will result in an error td.store.Close() require.Error(t, td.store.WriteBatch()) } func TestRetrieveBlockAndTransactions(t *testing.T) { td := setup(t, nil) lastCert := td.store.LastCertificate() lastHeight := lastCert.Height() cBlk, err := td.store.Block(lastHeight) require.NoError(t, err) assert.Equal(t, lastHeight, cBlk.Height) blk, _ := cBlk.ToBlock() assert.Equal(t, lastHeight-1, blk.PrevCertificate().Height()) for _, trx := range blk.Transactions() { committedTx, err := td.store.Transaction(trx.ID()) require.NoError(t, err) assert.Equal(t, committedTx.BlockTime, blk.Header().UnixTime()) assert.Equal(t, committedTx.TxID, trx.ID()) assert.Equal(t, committedTx.Height, lastHeight) trx2, _ := committedTx.ToTx() assert.Equal(t, trx.ID(), trx2.ID()) } } func TestIndexingPublicKeys(t *testing.T) { td := setup(t, nil) t.Run("Query existing public key", func(t *testing.T) { cBlk, _ := td.store.Block(1) blk, _ := cBlk.ToBlock() for _, trx := range blk.Transactions()[1:] { addr := trx.Payload().Signer() pub, err := td.store.PublicKey(addr) require.NoError(t, err) ok := td.store.HasPublicKey(addr) assert.True(t, ok) assert.True(t, trx.PublicKey().EqualsTo(pub)) } }) t.Run("Query non existing public key", func(t *testing.T) { randValAddress := td.RandValAddress() pubKey, err := td.store.PublicKey(randValAddress) ok := td.store.HasPublicKey(randValAddress) assert.False(t, ok) require.Error(t, err) assert.Nil(t, pubKey) }) } func TestStrippedPublicKey(t *testing.T) { td := setup(t, nil) lastHeight := td.store.LastCertificate().Height() _, blsPrv := td.RandBLSKeyPair() committedTrx1 := td.GenerateTestTransferTx( testsuite.TransactionWithSigner(blsPrv), ) _, ed25519Prv := td.RandEd25519KeyPair() committedTrx2 := td.GenerateTestTransferTx( testsuite.TransactionWithSigner(ed25519Prv), ) blk0, cert0 := td.GenerateTestBlock(lastHeight+1, testsuite.BlockWithTransactions([]*tx.Tx{committedTrx1, committedTrx2})) td.store.SaveBlock(blk0, cert0) err := td.store.writeBatch() require.NoError(t, err) // We have some known and index public key, run tests... trx1 := td.GenerateTestTransferTx( testsuite.TransactionWithSigner(blsPrv), ) trx2 := td.GenerateTestTransferTx( testsuite.TransactionWithSigner(ed25519Prv), ) trx3 := td.GenerateTestTransferTx( testsuite.TransactionWithSigner(blsPrv), ) trx4 := td.GenerateTestTransferTx( testsuite.TransactionWithSigner(ed25519Prv), ) trx5 := td.GenerateTestTransferTx() trx3.StripPublicKey() trx4.StripPublicKey() trx5.StripPublicKey() tests := []struct { trx *tx.Tx failed bool }{ {trx1, false}, // indexed public key and not stripped {trx2, false}, // indexed public key and not stripped {trx3, false}, // indexed public key and stripped {trx4, false}, // indexed public key and stripped {trx5, true}, // unknown public key and stripped } for no, tt := range tests { trxs := block.Txs{tt.trx} blockHeight := td.store.LastCertificate().Height() blk, cert := td.GenerateTestBlock(blockHeight+1, testsuite.BlockWithTransactions(trxs)) td.store.SaveBlock(blk, cert) err := td.store.writeBatch() require.NoError(t, err) cBlk, err := td.store.Block(blockHeight + 1) require.NoError(t, err) cTrx, err := td.store.Transaction(tt.trx.ID()) require.NoError(t, err) // if tt.failed { _, err := cBlk.ToBlock() require.ErrorIs(t, err, PublicKeyNotFoundError{ Address: tt.trx.Payload().Signer(), }, "test %d failed, expected error", no+1) _, err = cTrx.ToTx() require.ErrorIs(t, err, PublicKeyNotFoundError{ Address: tt.trx.Payload().Signer(), }, "test %d failed, expected error", no+1) } else { _, err := cBlk.ToBlock() require.NoError(t, err, "test %d failed, not expected error", no+1) _, err = cTrx.ToTx() require.NoError(t, err, "test %d failed, not expected error", no+1) } } } func TestIsBanned(t *testing.T) { conf := testConfig() td := setup(t, conf) bannedAddr := td.RandValAddress() conf.BannedAddrs[bannedAddr] = true assert.False(t, td.store.IsBanned(td.RandAccAddress())) assert.True(t, td.store.IsBanned(bannedAddr)) } func TestPruneBlock(t *testing.T) { conf := testConfig() td := setup(t, conf) t.Run("Prune existing block", func(t *testing.T) { height := types.Height(1) cBlkOne, _ := td.store.Block(height) blkOne, _ := cBlkOne.ToBlock() pruned, err := td.store.pruneBlock(height) assert.True(t, pruned) require.NoError(t, err) err = td.store.WriteBatch() require.NoError(t, err) cBlk, _ := td.store.Block(height) assert.Nil(t, cBlk) h := td.store.BlockHash(height) assert.Equal(t, hash.UndefHash, h) for _, trx := range blkOne.Transactions() { cTrx, _ := td.store.Transaction(trx.ID()) assert.Nil(t, cTrx) } }) t.Run("Prune non existing block", func(t *testing.T) { height := types.Height(11) pruned, err := td.store.pruneBlock(height) assert.False(t, pruned) require.NoError(t, err) err = td.store.WriteBatch() require.NoError(t, err) }) } func TestPrune(t *testing.T) { conf := testConfig() conf.RetentionDays = 1 td := setup(t, conf) totalPruned := uint32(0) lastPruningHeight := types.Height(0) callback := func(pruned bool, pruningHeight types.Height) bool { if pruned { totalPruned++ } lastPruningHeight = pruningHeight return false } t.Run("Not enough block to prune", func(t *testing.T) { totalPruned = uint32(0) lastPruningHeight = types.Height(0) // Store doesn't have blocks for one day err := td.store.Prune(callback) require.NoError(t, err) assert.Zero(t, totalPruned) assert.Zero(t, lastPruningHeight) }) t.Run("Prune database", func(t *testing.T) { totalPruned = uint32(0) lastPruningHeight = types.Height(0) blk, cert := td.GenerateTestBlock(blockPerDay + 7) td.store.SaveBlock(blk, cert) err := td.store.WriteBatch() require.NoError(t, err) blk, cert = td.GenerateTestBlock(blockPerDay + 8) td.store.SaveBlock(blk, cert) err = td.store.WriteBatch() require.NoError(t, err) // It should remove blocks [1..8] err = td.store.Prune(callback) require.NoError(t, err) assert.Equal(t, uint32(8), totalPruned) assert.Equal(t, types.Height(1), lastPruningHeight) }) t.Run("Reopen the store", func(t *testing.T) { td.store.Close() td.store.config.TxCacheWindow = 1 s, err := NewStore(td.store.config) require.NoError(t, err) td.store = s.(*store) assert.True(t, td.store.IsPruned(), "store should be in prune mode") assert.Equal(t, types.Height(8), td.store.PruningHeight()) }) t.Run("Commit new block", func(t *testing.T) { blk, cert := td.GenerateTestBlock(blockPerDay + 9) td.store.SaveBlock(blk, cert) err := td.store.WriteBatch() require.NoError(t, err) cBlk, err := td.store.Block(9) require.Error(t, err) assert.Nil(t, cBlk) assert.Equal(t, types.Height(9), td.store.PruningHeight()) }) } func TestCancelPrune(t *testing.T) { conf := testConfig() conf.RetentionDays = 1 td := setup(t, conf) hits := uint32(0) callback := func(_ bool, _ types.Height) bool { hits++ return true // Cancel pruning } t.Run("Cancel Pruning database", func(t *testing.T) { blk, cert := td.GenerateTestBlock(blockPerDay + 7) td.store.SaveBlock(blk, cert) err := td.store.WriteBatch() require.NoError(t, err) err = td.store.Prune(callback) require.NoError(t, err) assert.Equal(t, uint32(1), hits) }) } func TestRecentTransaction(t *testing.T) { td := setup(t, nil) lastHeight := td.store.LastCertificate().Height() oldTrx := td.GenerateTestTransferTx() blkOld, certOld := td.GenerateTestBlock(lastHeight+1, testsuite.BlockWithTransactions([]*tx.Tx{oldTrx})) td.store.SaveBlock(blkOld, certOld) err := td.store.writeBatch() require.NoError(t, err) assert.True(t, td.store.RecentTransaction(oldTrx.ID())) blk, cert := td.GenerateTestBlock(lastHeight.SafeIncrease(td.store.txStore.txCacheWindow + 2)) td.store.SaveBlock(blk, cert) err = td.store.writeBatch() require.NoError(t, err) assert.False(t, td.store.RecentTransaction(oldTrx.ID())) assert.False(t, td.store.RecentTransaction(td.RandHash())) } ================================================ FILE: store/tx.go ================================================ package store import ( "bytes" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/encoding" "github.com/pactus-project/pactus/util/linkedmap" "github.com/syndtr/goleveldb/leveldb" ) type blockRegion struct { height types.Height offset uint32 length uint32 } func txKey(txID tx.ID) []byte { return append(txPrefix, txID.Bytes()...) } type txStore struct { db *leveldb.DB txCache *linkedmap.LinkedMap[tx.ID, types.Height] txCacheWindow uint32 } func newTxStore(db *leveldb.DB, txCacheWindow uint32) *txStore { return &txStore{ db: db, txCache: linkedmap.New[tx.ID, types.Height](0), txCacheWindow: txCacheWindow, } } func (ts *txStore) saveTxs(batch *leveldb.Batch, txs block.Txs, regs []blockRegion) { for i, trx := range txs { buf := bytes.NewBuffer(make([]byte, 0, 32+4)) reg := regs[i] err := encoding.WriteElements(buf, ®.height, ®.offset, ®.length) if err != nil { panic(err) } txID := trx.ID() key := txKey(txID) batch.Put(key, buf.Bytes()) ts.addToCache(txID, reg.height) } } func (ts *txStore) pruneCache(currentHeight types.Height) { for { head := ts.txCache.HeadNode() txHeight := head.Data.Value if currentHeight.SafeSub(txHeight) <= ts.txCacheWindow { break } ts.txCache.RemoveHead() } } func (ts *txStore) recentTransaction(txID tx.ID) bool { return ts.txCache.Has(txID) } func (ts *txStore) tx(txID tx.ID) (*blockRegion, error) { data, err := tryGet(ts.db, txKey(txID)) if err != nil { return nil, err } r := bytes.NewReader(data) reg := new(blockRegion) if err := encoding.ReadElements(r, ®.height, ®.offset, ®.length); err != nil { return nil, err } return reg, nil } func (ts *txStore) addToCache(txID tx.ID, height types.Height) { ts.txCache.PushBack(txID, height) } ================================================ FILE: store/validator.go ================================================ package store import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/logger" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/util" ) type validatorStore struct { db *leveldb.DB numberMap map[int32]*validator.Validator addressMap map[crypto.Address]*validator.Validator total int32 active int32 } func valKey(addr crypto.Address) []byte { return append(validatorPrefix, addr.Bytes()...) } func newValidatorStore(db *leveldb.DB) *validatorStore { total := int32(0) active := int32(0) numberMap := make(map[int32]*validator.Validator) addressMap := make(map[crypto.Address]*validator.Validator) r := util.BytesPrefix(validatorPrefix) iter := db.NewIterator(r, nil) for iter.Next() { value := iter.Value() val, err := validator.FromBytes(value) if err != nil { logger.Panic("unable to decode validator", "error", err) } numberMap[val.Number()] = val addressMap[val.Address()] = val total++ if !val.IsUnbonded() { active++ } } iter.Release() return &validatorStore{ db: db, total: total, active: active, numberMap: numberMap, addressMap: addressMap, } } func (vs *validatorStore) hasValidator(addr crypto.Address) bool { _, ok := vs.addressMap[addr] return ok } func (vs *validatorStore) ValidatorAddresses() []crypto.Address { addrs := make([]crypto.Address, 0, len(vs.addressMap)) for addr := range vs.addressMap { addrs = append(addrs, addr) } return addrs } func (vs *validatorStore) validator(addr crypto.Address) (*validator.Validator, error) { val, ok := vs.addressMap[addr] if ok { return val.Clone(), nil } return nil, ErrNotFound } func (vs *validatorStore) validatorByNumber(num int32) (*validator.Validator, error) { val, ok := vs.numberMap[num] if ok { return val.Clone(), nil } return nil, ErrNotFound } func (vs *validatorStore) iterateValidators(consumer func(*validator.Validator) (stop bool)) { for _, val := range vs.addressMap { stopped := consumer(val.Clone()) if stopped { return } } } // This function takes ownership of the validator pointer. // It is important that the caller should not modify the validator data and // keep it immutable. func (vs *validatorStore) updateValidator(batch *leveldb.Batch, val *validator.Validator) { data, err := val.Bytes() if err != nil { logger.Panic("unable to encode validator", "error", err) } oldVal, ok := vs.addressMap[val.Address()] if !ok { vs.total++ vs.active++ } else if !oldVal.IsUnbonded() && val.IsUnbonded() { vs.active-- } vs.numberMap[val.Number()] = val vs.addressMap[val.Address()] = val batch.Put(valKey(val.Address()), data) } func (vs *validatorStore) updateValidatorProtocolVersion(addr crypto.Address, ver protocol.Version) { val, ok := vs.addressMap[addr] if ok { val.UpdateProtocolVersion(ver) } } ================================================ FILE: store/validator_test.go ================================================ package store import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestValidatorCounter(t *testing.T) { td := setup(t, nil) val := td.GenerateTestValidator() t.Run("Add new validator, should increase the total validators number", func(t *testing.T) { newVal := val.Clone() td.store.UpdateValidator(newVal) assert.Equal(t, int32(1), td.store.TotalValidators()) assert.Equal(t, int32(1), td.store.ActiveValidators()) }) t.Run("Update validator, should not change the total and active validators number", func(t *testing.T) { newVal := val.Clone() newVal.AddToStake(1) td.store.UpdateValidator(newVal) assert.Equal(t, int32(1), td.store.TotalValidators()) assert.Equal(t, int32(1), td.store.ActiveValidators()) }) t.Run("Unbond validator, should decrease the active validators number", func(t *testing.T) { newVal := val.Clone() newVal.UpdateUnbondingHeight(td.RandHeight()) td.store.UpdateValidator(newVal) assert.Equal(t, int32(1), td.store.TotalValidators()) assert.Equal(t, int32(0), td.store.ActiveValidators()) }) t.Run("Update unbonded validator, should not change the active validators number", func(t *testing.T) { newVal := val.Clone() newVal.UpdateUnbondingHeight(td.RandHeight()) td.store.UpdateValidator(newVal) assert.Equal(t, int32(1), td.store.TotalValidators()) assert.Equal(t, int32(0), td.store.ActiveValidators()) }) } func TestValidatorBatchSaving(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) t.Run("Add some validators", func(t *testing.T) { for i := int32(0); i < total; i++ { val := td.GenerateTestValidator(testsuite.ValidatorWithNumber(i)) td.store.UpdateValidator(val) } require.NoError(t, td.store.WriteBatch()) assert.Equal(t, total, td.store.TotalValidators()) }) t.Run("Close and load db", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) assert.Equal(t, total, store.TotalValidators()) }) } func TestValidatorAddresses(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) addrs1 := make([]crypto.Address, 0, total) for i := int32(0); i < total; i++ { val := td.GenerateTestValidator(testsuite.ValidatorWithNumber(i)) td.store.UpdateValidator(val) addrs1 = append(addrs1, val.Address()) } addrs2 := td.store.ValidatorAddresses() assert.ElementsMatch(t, addrs1, addrs2) } func TestValidatorByNumber(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) t.Run("Add some validators", func(t *testing.T) { for i := int32(0); i < total; i++ { val := td.GenerateTestValidator(testsuite.ValidatorWithNumber(i)) td.store.UpdateValidator(val) } require.NoError(t, td.store.WriteBatch()) assert.Equal(t, total, td.store.TotalValidators()) }) t.Run("Get a random Validator", func(t *testing.T) { num := td.RandInt32Max(total) val, err := td.store.ValidatorByNumber(num) require.NoError(t, err) require.NotNil(t, val) assert.Equal(t, num, val.Number()) }) t.Run("Negative number", func(t *testing.T) { val, err := td.store.ValidatorByNumber(-1) require.Error(t, err) assert.Nil(t, val) }) t.Run("Non existing validator", func(t *testing.T) { addr := td.RandValAddress() val, err := td.store.Validator(addr) has := td.store.HasValidator(addr) assert.False(t, has) require.Error(t, err) assert.Nil(t, val) }) t.Run("Reopen the store", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) num := td.RandInt32Max(total) val, err := store.ValidatorByNumber(num) require.NoError(t, err) require.NotNil(t, val) assert.Equal(t, num, val.Number()) val, err = td.store.ValidatorByNumber(total + 1) require.Error(t, err) assert.Nil(t, val) }) } func TestValidatorByAddress(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) t.Run("Add some validators", func(t *testing.T) { for i := int32(0); i < total; i++ { val := td.GenerateTestValidator(testsuite.ValidatorWithNumber(i)) td.store.UpdateValidator(val) } require.NoError(t, td.store.WriteBatch()) assert.Equal(t, total, td.store.TotalValidators()) }) t.Run("Get random validator", func(t *testing.T) { num := td.RandInt32Max(total) val0, _ := td.store.ValidatorByNumber(num) val, err := td.store.Validator(val0.Address()) require.NoError(t, err) require.NotNil(t, val) assert.Equal(t, num, val.Number()) }) t.Run("Unknown address", func(t *testing.T) { val, err := td.store.Validator(td.RandAccAddress()) require.Error(t, err) assert.Nil(t, val) }) t.Run("Reopen the store", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) num := td.RandInt32Max(total) val0, _ := store.ValidatorByNumber(num) val, err := store.Validator(val0.Address()) require.NoError(t, err) require.NotNil(t, val) assert.Equal(t, num, val.Number()) }) } func TestIterateValidators(t *testing.T) { td := setup(t, nil) total := td.RandInt32NonZero(100) hashes1 := []hash.Hash{} for i := int32(0); i < total; i++ { val := td.GenerateTestValidator(testsuite.ValidatorWithNumber(i)) td.store.UpdateValidator(val) hashes1 = append(hashes1, val.Hash()) } require.NoError(t, td.store.WriteBatch()) hashes2 := []hash.Hash{} td.store.IterateValidators(func(val *validator.Validator) bool { hashes2 = append(hashes2, val.Hash()) return false }) assert.ElementsMatch(t, hashes1, hashes2) stopped := false td.store.IterateValidators(func(val *validator.Validator) bool { if val.Hash() == hashes1[0] { stopped = true } return stopped }) assert.True(t, stopped) } func TestValidatorDeepCopy(t *testing.T) { td := setup(t, nil) num := td.RandInt32NonZero(1000) val1 := td.GenerateTestValidator(testsuite.ValidatorWithNumber(num)) td.store.UpdateValidator(val1) val2, _ := td.store.ValidatorByNumber(num) val2.AddToStake(1) assert.NotEqual(t, td.store.validatorStore.numberMap[num].Hash(), val2.Hash()) val3, _ := td.store.Validator(val1.Address()) val3.AddToStake(1) assert.NotEqual(t, td.store.validatorStore.numberMap[num].Hash(), val3.Hash()) } func TestUpdateValidatorProtocolVersion(t *testing.T) { td := setup(t, nil) val1 := td.GenerateTestValidator() td.store.UpdateValidator(val1) td.store.UpdateValidatorProtocolVersion(val1.Address(), protocol.ProtocolVersion2) val2, _ := td.store.Validator(val1.Address()) assert.Equal(t, protocol.ProtocolVersion2, val2.ProtocolVersion()) } ================================================ FILE: sync/bundle/bundle.go ================================================ package bundle import ( "encoding/binary" "fmt" "io" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util" ) const ( BundleFlagNetworkMainnet = 0x0001 BundleFlagNetworkTestnet = 0x0002 BundleFlagCarrierLibP2P = 0x0010 BundleFlagCompressed = 0x0100 BundleFlagBroadcasted = 0x0200 BundleFlagHandshaking = 0x0400 ) // Custom type to enforce uint32 encoding as 4 bytes, ignoring zeros. type fixedUint32 uint32 func (u fixedUint32) MarshalCBOR() ([]byte, error) { buf := make([]byte, 0, 5) // The header for a 4-byte integer is 0x1A followed by the 4 bytes of the uint32. buf = append(buf, 0x1A) // Append the uint32 in big-endian format buf = binary.BigEndian.AppendUint32(buf, uint32(u)) return buf, nil } type Bundle struct { Flags int Message message.Message ConsensusHeight types.Height } func NewBundle(msg message.Message) *Bundle { return &Bundle{ Flags: 0, Message: msg, ConsensusHeight: msg.ConsensusHeight(), } } // BasicCheck performs basic validation checks on the bundle and its message. func (b *Bundle) BasicCheck() error { return b.Message.BasicCheck() } // LogString returns a concise string representation intended for use in logs. func (b *Bundle) LogString() string { return fmt.Sprintf("%s%s", b.Message.Type(), b.Message.LogString()) } func (b *Bundle) CompressIt() { b.Flags = util.SetFlag(b.Flags, BundleFlagCompressed) } type _Bundle struct { Flags int `cbor:"1,keyasint"` MessageType message.Type `cbor:"2,keyasint"` MessageData []byte `cbor:"3,keyasint"` ConsensusHeight fixedUint32 `cbor:"4,keyasint,omitempty"` } func (b *Bundle) Encode() ([]byte, error) { data, err := cbor.Marshal(b.Message) if err != nil { return nil, err } if util.IsFlagSet(b.Flags, BundleFlagCompressed) { c, err := util.CompressBuffer(data) if err != nil { return nil, err } data = c } msg := &_Bundle{ Flags: b.Flags, MessageType: b.Message.Type(), MessageData: data, ConsensusHeight: fixedUint32(b.ConsensusHeight), } return cbor.Marshal(msg) } func (b *Bundle) Decode(r io.Reader) (int, error) { var bdl _Bundle decOpts := cbor.DecOptions{} decOpts.MaxArrayElements = 65_536 // default in 131072 decOpts.MaxMapPairs = 65_536 // default in 131072 decMode, _ := decOpts.DecMode() d := decMode.NewDecoder(r) err := d.Decode(&bdl) bytesRead := d.NumBytesRead() if err != nil { return bytesRead, err } data := bdl.MessageData msg, err := message.MakeMessage(bdl.MessageType) if err != nil { return bytesRead, err } if util.IsFlagSet(bdl.Flags, BundleFlagCompressed) { c, err := util.DecompressBuffer(bdl.MessageData) if err != nil { return bytesRead, err } data = c } b.Flags = bdl.Flags b.Message = msg b.ConsensusHeight = types.Height(bdl.ConsensusHeight) return bytesRead, cbor.Unmarshal(data, msg) } ================================================ FILE: sync/bundle/bundle_test.go ================================================ package bundle import ( "bytes" "encoding/hex" "fmt" "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestInvalidCBOR(t *testing.T) { data1, _ := hex.DecodeString("00") data2, _ := hex.DecodeString("A3") data3, _ := hex.DecodeString("A3010002000340") bdl := new(Bundle) _, err := bdl.Decode(bytes.NewReader(data1)) require.Error(t, err) _, err = bdl.Decode(bytes.NewReader(data2)) require.Error(t, err) _, err = bdl.Decode(bytes.NewReader(data3)) require.Error(t, err) } func TestMessageCompress(t *testing.T) { ts := testsuite.NewTestSuite(t) blocksData := [][]byte{} for i := 0; i < ts.RandIntMax(40); i++ { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) data, _ := blk.Bytes() blocksData = append(blocksData, data) } msg1 := message.NewBlocksResponseMessage(message.ResponseCodeOK, message.ResponseCodeOK.String(), 1234, 888, blocksData, nil) bdl := NewBundle(msg1) bs0, err := bdl.Encode() require.NoError(t, err) assert.False(t, util.IsFlagSet(bdl.Flags, BundleFlagCompressed)) bdl.CompressIt() bs1, err := bdl.Encode() require.NoError(t, err) assert.True(t, util.IsFlagSet(bdl.Flags, BundleFlagCompressed)) fmt.Printf("Compressed :%v%%\n", 100-len(bs1)*100/(len(bs0))) fmt.Printf("Uncompressed len :%v\n", len(bs0)) fmt.Printf("Compressed len :%v\n", len(bs1)) msg2 := new(Bundle) bytesRead1, err := msg2.Decode(bytes.NewReader(bs0)) require.NoError(t, err) assert.Equal(t, len(bs0), bytesRead1) require.NoError(t, msg2.BasicCheck()) msg3 := new(Bundle) bytesRead2, err := msg3.Decode(bytes.NewReader(bs1)) require.NoError(t, err) assert.Equal(t, len(bs1), bytesRead2) require.NoError(t, msg3.BasicCheck()) } func TestDecodeVoteMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) v, _ := ts.GenerateTestPrecommitVote(88, 0) msg := message.NewVoteMessage(v) bdl := NewBundle(msg) bs0, err := bdl.Encode() require.NoError(t, err) bdl.CompressIt() bs1, err := bdl.Encode() require.NoError(t, err) fmt.Printf("Compressed :%v%%\n", 100-len(bs1)*100/(len(bs0))) fmt.Printf("Uncompressed len :%v\n", len(bs0)) fmt.Printf("Compressed len :%v\n", len(bs1)) } func TestDecodeVoteCBOR(t *testing.T) { dat1, _ := hex.DecodeString( "a4" + // Map(4) "0100" + // Flags = 0 "0207" + // Message Type = 7 (TypeVote) "035879" + // Message + Len "" + "a101a7010102186403010458200264572d4d6bfcd2140d4f885fd5a32fe42fdb" + // Vote Message Uncompressed "" + "f40551e4ff89f3d235e32b4b92055501c0067d277f2dff99943016d6a0f379cf" + "" + "09846c6f06f60758308ab7aecbe03c4ed5b688bcb7e848baffa62bcbf1a40215" + "" + "22c56693f0a7bbcc1fe865277556ee59c1f63ba592acfe1b43" + "041a00001234") // Consensus Height (0x00001234) data2, _ := hex.DecodeString( "a4" + // Map(4) "01190100" + // Flags = 0x0100 (compressed) "0207" + // Message Type = 7 (TypeVote) "035895" + // Message + Len "" + "1f8b08000000000000ff00790086ffa101a7010102186403010458200264572d" + // Vote Uncompressed "" + "4d6bfcd2140d4f885fd5a32fe42fdbf40551e4ff89f3d235e32b4b92055501c0" + "" + "067d277f2dff99943016d6a0f379cf09846c6f06f60758308ab7aecbe03c4ed5" + "" + "b688bcb7e848baffa62bcbf1a4021522c56693f0a7bbcc1fe865277556ee59c1" + "" + "f63ba592acfe1b43010000ffff798ce7ec79000000" + "041a00001234") // Consensus Height (0x00001234) bdl1 := new(Bundle) bdl2 := new(Bundle) bytesRead1, err := bdl1.Decode(bytes.NewReader(dat1)) require.NoError(t, err) assert.Equal(t, len(dat1), bytesRead1) require.NoError(t, bdl1.BasicCheck()) bytesRead2, err := bdl2.Decode(bytes.NewReader(data2)) require.NoError(t, err) assert.Equal(t, len(data2), bytesRead2) require.NoError(t, bdl2.BasicCheck()) assert.Equal(t, bdl1.Message, bdl2.Message) assert.Equal(t, 0x0000, bdl1.Flags) assert.Equal(t, 0x0100, bdl2.Flags) assert.Contains(t, bdl1.LogString(), "vote") assert.Equal(t, types.Height(0x1234), bdl1.ConsensusHeight) assert.Equal(t, types.Height(0x1234), bdl2.ConsensusHeight) } func TestEncodingData(t *testing.T) { t.Run("Encoding non-consensus message", func(t *testing.T) { msg := message.NewBlocksRequestMessage(0x00, 0x12, 0x13) bdl := NewBundle(msg) data, _ := bdl.Encode() expectedData := "a4" + // Map(3) "0100" + // Flags = 0 "0209" + // Message Type = 9 (TypeBlocksRequest) "0347" + // Message + Len "" + "a3" + "" + "0100" + "" + "0212" + "" + "0313" + "041a00000000" // Consensus height (0x00000000) assert.Equal(t, expectedData, hex.EncodeToString(data)) assert.Equal(t, types.Height(0x00), bdl.ConsensusHeight) }) t.Run("Encoding consensus message", func(t *testing.T) { ts := testsuite.NewTestSuite(t) rndAddr := ts.RandValAddress() msg := message.NewQueryVoteMessage(0x12, 0x01, rndAddr) bdl := NewBundle(msg) data, _ := bdl.Encode() expectedData := "a4" + // Map(3) "0100" + // Flags = 0 "0206" + // Message Type = 6 (TypeQueryVote) "03581c" + // Message + Len "" + "a3" + "" + "0112" + "" + "0201" + "" + "0355" + hex.EncodeToString(rndAddr.Bytes()) + "041a00000012" // Consensus height (0x00000012) assert.Equal(t, expectedData, hex.EncodeToString(data)) assert.Equal(t, types.Height(0x12), bdl.ConsensusHeight) }) } func TestCBORLengthAttack(t *testing.T) { tests := []struct { data string msg string }{ {"9A00010001", "exceeded max number of elements 65536"}, // Major type 4 (100x xxxx): Array {"BA00010001", "exceeded max number of key-value pairs 65536"}, // Major type 5 (101x xxxx): Map } for _, tt := range tests { data, _ := hex.DecodeString(tt.data) bdl := new(Bundle) _, err := bdl.Decode(bytes.NewReader(data)) assert.ErrorContains(t, err, tt.msg) } } ================================================ FILE: sync/bundle/message/block_announce.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" ) type BlockAnnounceMessage struct { Block *block.Block `cbor:"1,keyasint"` Certificate *certificate.Certificate `cbor:"2,keyasint"` Proof *certificate.Certificate `cbor:"3,keyasint"` } func NewBlockAnnounceMessage(blk *block.Block, cert *certificate.Certificate, proof *certificate.Certificate, ) *BlockAnnounceMessage { return &BlockAnnounceMessage{ Block: blk, Certificate: cert, Proof: proof, } } func (m *BlockAnnounceMessage) BasicCheck() error { if err := m.Block.BasicCheck(); err != nil { return err } if m.Proof != nil { if err := m.Proof.BasicCheck(); err != nil { return err } } return m.Certificate.BasicCheck() } func (m *BlockAnnounceMessage) Height() types.Height { return m.Certificate.Height() } func (*BlockAnnounceMessage) Type() Type { return TypeBlockAnnounce } func (*BlockAnnounceMessage) TopicID() network.TopicID { return network.TopicIDBlock } func (*BlockAnnounceMessage) ShouldBroadcast() bool { return true } func (m *BlockAnnounceMessage) ConsensusHeight() types.Height { return m.Certificate.Height() } // LogString returns a concise string representation intended for use in logs. func (m *BlockAnnounceMessage) LogString() string { return fmt.Sprintf("{⌘ %d %v}", m.Certificate.Height(), m.Block.Hash().LogString()) } ================================================ FILE: sync/bundle/message/block_announce_test.go ================================================ package message import ( "fmt" "testing" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBlockAnnounceType(t *testing.T) { smg := &BlockAnnounceMessage{} assert.Equal(t, TypeBlockAnnounce, smg.Type()) } func TestBlockAnnounceMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid block certificate", func(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) cert := certificate.NewCertificate(0, 0) msg := NewBlockAnnounceMessage(blk, cert, nil) err := msg.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "height is not positive: 0", }) }) t.Run("Invalid proof", func(t *testing.T) { height := ts.RandHeight() blk, cert := ts.GenerateTestBlock(height) proof := ts.GenerateTestCertificate(0) msg := NewBlockAnnounceMessage(blk, cert, proof) err := msg.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "height is not positive: 0", }) }) t.Run("OK", func(t *testing.T) { height := ts.RandHeight() blk, cert := ts.GenerateTestBlock(height) msg := NewBlockAnnounceMessage(blk, cert, nil) require.NoError(t, msg.BasicCheck()) assert.Equal(t, height, msg.ConsensusHeight()) assert.Contains(t, msg.LogString(), fmt.Sprintf("%d", height)) }) } ================================================ FILE: sync/bundle/message/blocks_request.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" ) type BlocksRequestMessage struct { SessionID int `cbor:"1,keyasint"` From types.Height `cbor:"2,keyasint"` Count uint32 `cbor:"3,keyasint"` } func NewBlocksRequestMessage(sid int, from types.Height, count uint32) *BlocksRequestMessage { return &BlocksRequestMessage{ SessionID: sid, From: from, Count: count, } } func (m *BlocksRequestMessage) To() types.Height { return m.From.SafeIncrease(m.Count) - 1 } func (m *BlocksRequestMessage) BasicCheck() error { if m.From == 0 { return BasicCheckError{Reason: "invalid height"} } if m.Count == 0 { return BasicCheckError{Reason: "count is zero"} } return nil } func (*BlocksRequestMessage) Type() Type { return TypeBlocksRequest } func (*BlocksRequestMessage) TopicID() network.TopicID { return network.TopicIDUnspecified } func (*BlocksRequestMessage) ShouldBroadcast() bool { return false } func (*BlocksRequestMessage) ConsensusHeight() types.Height { return 0 } // LogString returns a concise string representation intended for use in logs. func (m *BlocksRequestMessage) LogString() string { return fmt.Sprintf("{⚓ %d %v:%v}", m.SessionID, m.From, m.To()) } ================================================ FILE: sync/bundle/message/blocks_request_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestLatestBlocksRequestType(t *testing.T) { msg := &BlocksRequestMessage{} assert.Equal(t, TypeBlocksRequest, msg.Type()) } func TestBlocksRequestMessage(t *testing.T) { t.Run("Invalid height", func(t *testing.T) { msg := NewBlocksRequestMessage(1, 0, 0) err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{Reason: "invalid height"}) }) t.Run("Invalid count", func(t *testing.T) { msg := NewBlocksRequestMessage(1, 200, 0) err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{Reason: "count is zero"}) }) t.Run("OK", func(t *testing.T) { msg := NewBlocksRequestMessage(1, 100, 7) require.NoError(t, msg.BasicCheck()) assert.Equal(t, types.Height(106), msg.To()) assert.Contains(t, msg.LogString(), "100") }) } ================================================ FILE: sync/bundle/message/blocks_response.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" ) type BlocksResponseMessage struct { ResponseCode ResponseCode `cbor:"1,keyasint"` SessionID int `cbor:"2,keyasint"` From types.Height `cbor:"3,keyasint"` BlocksData [][]byte `cbor:"4,keyasint"` LastCertificate *certificate.Certificate `cbor:"5,keyasint"` Reason string `cbor:"6,keyasint"` } func NewBlocksResponseMessage(code ResponseCode, reason string, sid int, from types.Height, blocksData [][]byte, lastCert *certificate.Certificate, ) *BlocksResponseMessage { return &BlocksResponseMessage{ ResponseCode: code, SessionID: sid, From: from, BlocksData: blocksData, LastCertificate: lastCert, Reason: reason, } } func (m *BlocksResponseMessage) BasicCheck() error { if m.LastCertificate != nil { if err := m.LastCertificate.BasicCheck(); err != nil { return err } } return nil } func (*BlocksResponseMessage) Type() Type { return TypeBlocksResponse } func (*BlocksResponseMessage) TopicID() network.TopicID { return network.TopicIDUnspecified } func (*BlocksResponseMessage) ShouldBroadcast() bool { return false } func (*BlocksResponseMessage) ConsensusHeight() types.Height { return 0 } func (m *BlocksResponseMessage) Count() uint32 { return uint32(len(m.BlocksData)) } func (m *BlocksResponseMessage) To() types.Height { // response message without any block if len(m.BlocksData) == 0 { return 0 } return m.From.SafeIncrease(m.Count()) - 1 } // LogString returns a concise string representation intended for use in logs. func (m *BlocksResponseMessage) LogString() string { return fmt.Sprintf("{⚓ %d %s %v-%v}", m.SessionID, m.ResponseCode, m.From, m.To()) } func (m *BlocksResponseMessage) IsRequestRejected() bool { return m.ResponseCode == ResponseCodeRejected } ================================================ FILE: sync/bundle/message/blocks_response_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestLatestBlocksResponseType(t *testing.T) { msg := &BlocksResponseMessage{} assert.Equal(t, TypeBlocksResponse, msg.Type()) } func TestBlocksResponseMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) sid := 123 t.Run("Invalid certificate", func(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) cert := certificate.NewCertificate(0, 0) d, _ := blk.Bytes() msg := NewBlocksResponseMessage(ResponseCodeMoreBlocks, ResponseCodeMoreBlocks.String(), sid, ts.RandHeight(), [][]byte{d}, cert) err := msg.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "height is not positive: 0", }) }) t.Run("OK", func(t *testing.T) { height := ts.RandHeight() blk1, _ := ts.GenerateTestBlock(height) blk2, cert2 := ts.GenerateTestBlock(height + 1) d1, _ := blk1.Bytes() d2, _ := blk2.Bytes() msg := NewBlocksResponseMessage(ResponseCodeMoreBlocks, ResponseCodeMoreBlocks.String(), sid, 100, [][]byte{d1, d2}, cert2) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), "100") assert.Equal(t, ResponseCodeMoreBlocks.String(), msg.Reason) }) } func TestLatestBlocksResponseCode(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("rejected", func(t *testing.T) { reason := ts.RandString(16) msg := NewBlocksResponseMessage(ResponseCodeRejected, reason, 1, 0, nil, nil) require.NoError(t, msg.BasicCheck()) assert.Zero(t, msg.From) assert.Zero(t, msg.To()) assert.Zero(t, msg.Count()) assert.True(t, msg.IsRequestRejected()) assert.Equal(t, reason, msg.Reason) }) t.Run("OK - MoreBlocks", func(t *testing.T) { height := ts.RandHeight() blk1, _ := ts.GenerateTestBlock(height) blk2, _ := ts.GenerateTestBlock(height + 1) d1, _ := blk1.Bytes() d2, _ := blk2.Bytes() reason := ts.RandString(16) msg := NewBlocksResponseMessage(ResponseCodeMoreBlocks, reason, 1, 100, [][]byte{d1, d2}, nil) require.NoError(t, msg.BasicCheck()) assert.Equal(t, types.Height(100), msg.From) assert.Equal(t, types.Height(101), msg.To()) assert.Equal(t, uint32(2), msg.Count()) assert.False(t, msg.IsRequestRejected()) assert.Equal(t, reason, msg.Reason) }) t.Run("OK - Synced", func(t *testing.T) { height := ts.RandHeight() _, cert := ts.GenerateTestBlock(height) reason := ts.RandString(16) msg := NewBlocksResponseMessage(ResponseCodeSynced, reason, 1, 100, nil, cert) require.NoError(t, msg.BasicCheck()) assert.Equal(t, types.Height(100), msg.From) assert.Zero(t, msg.To()) assert.Zero(t, msg.Count()) assert.False(t, msg.IsRequestRejected()) assert.Equal(t, reason, msg.Reason) }) } ================================================ FILE: sync/bundle/message/errors.go ================================================ package message import "fmt" // BasicCheckError is returned when the basic check on the message fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } // InvalidMessageTypeError is returned when the message type is not valid. type InvalidMessageTypeError struct { Type int } func (e InvalidMessageTypeError) Error() string { return fmt.Sprintf("invalid message type: %d", e.Type) } ================================================ FILE: sync/bundle/message/hello.go ================================================ package message import ( "fmt" "time" "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/version" ) type HelloMessage struct { PeerID peer.ID `cbor:"1,keyasint"` Agent string `cbor:"2,keyasint"` Moniker string `cbor:"3,keyasint"` PublicKeys []*bls.PublicKey `cbor:"4,keyasint"` Signature *bls.Signature `cbor:"5,keyasint"` Height types.Height `cbor:"6,keyasint"` Services service.Services `cbor:"7,keyasint"` GenesisHash hash.Hash `cbor:"8,keyasint"` BlockHash hash.Hash `cbor:"9,keyasint"` MyTimeUnixMilli int64 `cbor:"10,keyasint"` } func NewHelloMessage(pid peer.ID, moniker string, services service.Services, height types.Height, blockHash, genesisHash hash.Hash, ) *HelloMessage { return &HelloMessage{ PeerID: pid, Agent: version.NodeAgent.String(), Moniker: moniker, GenesisHash: genesisHash, BlockHash: blockHash, Height: height, Services: services, MyTimeUnixMilli: time.Now().UnixMilli(), } } func (m *HelloMessage) BasicCheck() error { if m.Signature == nil { return BasicCheckError{"no signature"} } if len(m.PublicKeys) == 0 { return BasicCheckError{"no public key"} } aggPub, err := bls.PublicKeyAggregate(m.PublicKeys...) if err != nil { return BasicCheckError{err.Error()} } return aggPub.Verify(m.SignBytes(), m.Signature) } func (m *HelloMessage) MyTime() time.Time { return time.UnixMilli(m.MyTimeUnixMilli) } func (m *HelloMessage) SignBytes() []byte { return []byte(fmt.Sprintf("%s:%s:%s:%s", m.Type(), m.Agent, m.PeerID, m.GenesisHash.String())) } func (*HelloMessage) Type() Type { return TypeHello } func (*HelloMessage) TopicID() network.TopicID { return network.TopicIDUnspecified } func (*HelloMessage) ShouldBroadcast() bool { return false } func (*HelloMessage) ConsensusHeight() types.Height { return 0 } // LogString returns a concise string representation intended for use in logs. func (m *HelloMessage) LogString() string { return fmt.Sprintf("{%s %d %s}", m.Moniker, m.Height, m.Services) } func (m *HelloMessage) Sign(valKeys []*bls.ValidatorKey) { signatures := make([]*bls.Signature, len(valKeys)) publicKeys := make([]*bls.PublicKey, len(valKeys)) signBytes := m.SignBytes() for i, key := range valKeys { signatures[i] = key.Sign(signBytes) publicKeys[i] = key.PublicKey() } aggSig, _ := bls.SignatureAggregate(signatures...) m.Signature = aggSig m.PublicKeys = publicKeys } ================================================ FILE: sync/bundle/message/hello_ack.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" ) type HelloAckMessage struct { ResponseCode ResponseCode `cbor:"1,keyasint"` Reason string `cbor:"2,keyasint"` Height types.Height `cbor:"3,keyasint"` } func NewHelloAckMessage(code ResponseCode, reason string, height types.Height) *HelloAckMessage { return &HelloAckMessage{ ResponseCode: code, Reason: reason, Height: height, } } func (*HelloAckMessage) BasicCheck() error { return nil } func (*HelloAckMessage) Type() Type { return TypeHelloAck } func (*HelloAckMessage) TopicID() network.TopicID { return network.TopicIDUnspecified } func (*HelloAckMessage) ShouldBroadcast() bool { return false } func (*HelloAckMessage) ConsensusHeight() types.Height { return 0 } // LogString returns a concise string representation intended for use in logs. func (m *HelloAckMessage) LogString() string { return fmt.Sprintf("{%s: %s %v}", m.ResponseCode, m.Reason, m.Height) } ================================================ FILE: sync/bundle/message/hello_ack_test.go ================================================ package message import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHelloAckType(t *testing.T) { smg := &HelloAckMessage{} assert.Equal(t, TypeHelloAck, smg.Type()) } func TestHelloAckMessage(t *testing.T) { msg := NewHelloAckMessage(ResponseCodeRejected, "rejected", 0) require.NoError(t, msg.BasicCheck()) } ================================================ FILE: sync/bundle/message/hello_test.go ================================================ package message import ( "testing" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHelloType(t *testing.T) { msg := &HelloMessage{} assert.Equal(t, TypeHello, msg.Type()) } func TestHelloMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid signature", func(t *testing.T) { valKey := ts.RandValKey() msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) msg.Sign([]*bls.ValidatorKey{valKey}) msg.Signature = ts.RandBLSSignature() err := msg.BasicCheck() require.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Signature is nil", func(t *testing.T) { valKey := ts.RandValKey() msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) msg.Sign([]*bls.ValidatorKey{valKey}) msg.Signature = nil err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{"no signature"}) }) t.Run("PublicKeys are empty", func(t *testing.T) { valKey := ts.RandValKey() msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) msg.Sign([]*bls.ValidatorKey{valKey}) msg.PublicKeys = make([]*bls.PublicKey, 0) err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{"no public key"}) }) t.Run("Invalid PublicKey", func(t *testing.T) { valKey := ts.RandValKey() msg := NewHelloMessage(ts.RandPeerID(), "Oscar", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) msg.Sign([]*bls.ValidatorKey{valKey}) msg.PublicKeys = []*bls.PublicKey{{}} err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{"short buffer"}) }) t.Run("Check hello message time", func(t *testing.T) { time1 := time.Now() msg := NewHelloMessage(ts.RandPeerID(), "Alice", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) time2 := time.Now() assert.GreaterOrEqual(t, msg.MyTime().UnixMilli(), time1.UnixMilli()) assert.LessOrEqual(t, msg.MyTime().UnixMilli(), time2.UnixMilli()) }) t.Run("Ok", func(t *testing.T) { valKey := ts.RandValKey() msg := NewHelloMessage(ts.RandPeerID(), "Alice", service.New(service.FullNode), ts.RandHeight(), ts.RandHash(), ts.RandHash()) msg.Sign([]*bls.ValidatorKey{valKey}) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), "Alice") assert.Contains(t, msg.LogString(), "FULL") }) } ================================================ FILE: sync/bundle/message/message.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" ) type ResponseCode int const ( ResponseCodeOK = ResponseCode(0) ResponseCodeRejected = ResponseCode(1) ResponseCodeMoreBlocks = ResponseCode(2) ResponseCodeNoMoreBlocks = ResponseCode(3) ResponseCodeSynced = ResponseCode(4) ) func (c ResponseCode) String() string { switch c { case ResponseCodeOK: return "ok" case ResponseCodeRejected: return "rejected" case ResponseCodeMoreBlocks: return "more-blocks" case ResponseCodeNoMoreBlocks: return "no-more-blocks" case ResponseCodeSynced: return "synced" } return fmt.Sprintf("%d", c) } type Type int32 const ( TypeHello = Type(1) TypeHelloAck = Type(2) TypeTransaction = Type(3) TypeQueryProposal = Type(4) TypeProposal = Type(5) TypeQueryVote = Type(6) TypeVote = Type(7) TypeBlockAnnounce = Type(8) TypeBlocksRequest = Type(9) TypeBlocksResponse = Type(10) ) func (t Type) String() string { switch t { case TypeHello: return "hello" case TypeHelloAck: return "hello-ack" case TypeTransaction: return "transaction" case TypeQueryProposal: return "query-proposal" case TypeProposal: return "proposal" case TypeQueryVote: return "query-vote" case TypeVote: return "vote" case TypeBlockAnnounce: return "block-announce" case TypeBlocksRequest: return "blocks-request" case TypeBlocksResponse: return "blocks-response" default: return fmt.Sprintf("%d", t) } } func MakeMessage(msgType Type) (Message, error) { var msg Message switch msgType { case TypeHello: msg = &HelloMessage{} case TypeHelloAck: msg = &HelloAckMessage{} case TypeTransaction: msg = &TransactionsMessage{} case TypeQueryProposal: msg = &QueryProposalMessage{} case TypeProposal: msg = &ProposalMessage{} case TypeQueryVote: msg = &QueryVoteMessage{} case TypeVote: msg = &VoteMessage{} case TypeBlockAnnounce: msg = &BlockAnnounceMessage{} case TypeBlocksRequest: msg = &BlocksRequestMessage{} case TypeBlocksResponse: msg = &BlocksResponseMessage{} default: return nil, InvalidMessageTypeError{Type: int(msgType)} } // return msg, nil } type Message interface { // BasicCheck performs basic validation checks on the message. BasicCheck() error // Type returns the message type. Type() Type // TopicID returns the topic ID for the message. TopicID() network.TopicID // ShouldBroadcast indicates whether the message should be broadcasted // or send directly as stream. ShouldBroadcast() bool // ConsensusHeight indicates the consensus height at which the message is broadcast. // This is applicable for consensus messages, including BlockAnnounce. // For non-consensus messages, this height is set to zero. ConsensusHeight() types.Height // LogString returns a concise string representation intended for use in logs. LogString() string } ================================================ FILE: sync/bundle/message/message_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/network" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMessage(t *testing.T) { tests := []struct { msgType Type typeName string topicID network.TopicID shouldBroadcast bool }{ {TypeHello, "hello", network.TopicIDUnspecified, false}, {TypeHelloAck, "hello-ack", network.TopicIDUnspecified, false}, {TypeTransaction, "transaction", network.TopicIDTransaction, true}, {TypeQueryProposal, "query-proposal", network.TopicIDConsensus, true}, {TypeProposal, "proposal", network.TopicIDConsensus, true}, {TypeQueryVote, "query-vote", network.TopicIDConsensus, true}, {TypeVote, "vote", network.TopicIDConsensus, true}, {TypeBlockAnnounce, "block-announce", network.TopicIDBlock, true}, {TypeBlocksRequest, "blocks-request", network.TopicIDUnspecified, false}, {TypeBlocksResponse, "blocks-response", network.TopicIDUnspecified, false}, } for _, tt := range tests { msg, err := MakeMessage(tt.msgType) require.NoError(t, err) assert.Equal(t, tt.typeName, msg.Type().String()) assert.Equal(t, tt.topicID, msg.TopicID()) assert.Equal(t, tt.shouldBroadcast, msg.ShouldBroadcast()) } } func TestInvalidMessageType(t *testing.T) { _, err := MakeMessage(66) require.ErrorIs(t, err, InvalidMessageTypeError{Type: 66}) } ================================================ FILE: sync/bundle/message/proposal.go ================================================ package message import ( "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/protocol" ) type ProposalMessage struct { Proposal *proposal.Proposal `cbor:"1,keyasint"` ProtocolVersion protocol.Version `cbor:"2,keyasint"` } func NewProposalMessage(p *proposal.Proposal) *ProposalMessage { return &ProposalMessage{ Proposal: p, ProtocolVersion: protocol.ProtocolVersionLatest, } } func (*ProposalMessage) BasicCheck() error { // Basic checks for the proposal are deferred to the consensus phase // to avoid unnecessary validation for validators outside the committee. return nil } func (*ProposalMessage) Type() Type { return TypeProposal } func (*ProposalMessage) TopicID() network.TopicID { return network.TopicIDConsensus } func (*ProposalMessage) ShouldBroadcast() bool { return true } func (m *ProposalMessage) ConsensusHeight() types.Height { return m.Height() } func (m *ProposalMessage) Height() types.Height { return m.Proposal.Height() } // LogString returns a concise string representation intended for use in logs. func (m *ProposalMessage) LogString() string { return m.Proposal.LogString() } ================================================ FILE: sync/bundle/message/proposal_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestProposalType(t *testing.T) { msg := &ProposalMessage{} assert.Equal(t, TypeProposal, msg.Type()) } func TestProposalMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("OK", func(t *testing.T) { prop := ts.GenerateTestProposal(100, 0) msg := NewProposalMessage(prop) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), "100") }) } ================================================ FILE: sync/bundle/message/query_proposal.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" ) type QueryProposalMessage struct { Height types.Height `cbor:"1,keyasint"` Round types.Round `cbor:"3,keyasint"` Querier crypto.Address `cbor:"2,keyasint"` } func NewQueryProposalMessage(height types.Height, round types.Round, querier crypto.Address) *QueryProposalMessage { return &QueryProposalMessage{ Height: height, Round: round, Querier: querier, } } func (m *QueryProposalMessage) BasicCheck() error { if m.Round < 0 { return BasicCheckError{Reason: "invalid round"} } return nil } func (*QueryProposalMessage) Type() Type { return TypeQueryProposal } func (*QueryProposalMessage) TopicID() network.TopicID { return network.TopicIDConsensus } func (*QueryProposalMessage) ShouldBroadcast() bool { return true } func (m *QueryProposalMessage) ConsensusHeight() types.Height { return m.Height } // LogString returns a concise string representation intended for use in logs. func (m *QueryProposalMessage) LogString() string { return fmt.Sprintf("{%v %s}", m.Height, m.Querier.LogString()) } ================================================ FILE: sync/bundle/message/query_proposal_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestQueryProposalType(t *testing.T) { msg := &QueryProposalMessage{} assert.Equal(t, TypeQueryProposal, msg.Type()) } func TestQueryProposalMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid round", func(t *testing.T) { msg := NewQueryProposalMessage(0, -1, ts.RandValAddress()) err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{"invalid round"}) }) t.Run("OK", func(t *testing.T) { msg := NewQueryProposalMessage(100, 0, ts.RandValAddress()) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), "100") }) } ================================================ FILE: sync/bundle/message/query_votes.go ================================================ package message import ( "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" ) type QueryVoteMessage struct { Height types.Height `cbor:"1,keyasint"` Round types.Round `cbor:"2,keyasint"` Querier crypto.Address `cbor:"3,keyasint"` } func NewQueryVoteMessage(height types.Height, round types.Round, querier crypto.Address) *QueryVoteMessage { return &QueryVoteMessage{ Height: height, Round: round, Querier: querier, } } func (m *QueryVoteMessage) BasicCheck() error { if m.Round < 0 { return BasicCheckError{Reason: "invalid round"} } return nil } func (*QueryVoteMessage) Type() Type { return TypeQueryVote } func (*QueryVoteMessage) TopicID() network.TopicID { return network.TopicIDConsensus } func (*QueryVoteMessage) ShouldBroadcast() bool { return true } func (m *QueryVoteMessage) ConsensusHeight() types.Height { return m.Height } // LogString returns a concise string representation intended for use in logs. func (m *QueryVoteMessage) LogString() string { return fmt.Sprintf("{%d/%d %s}", m.Height, m.Round, m.Querier.LogString()) } ================================================ FILE: sync/bundle/message/query_votes_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestQueryVotesType(t *testing.T) { msg := &QueryVoteMessage{} assert.Equal(t, TypeQueryVote, msg.Type()) } func TestQueryVoteMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid round", func(t *testing.T) { msg := NewQueryVoteMessage(0, -1, ts.RandValAddress()) err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{Reason: "invalid round"}) }) t.Run("OK", func(t *testing.T) { msg := NewQueryVoteMessage(100, 0, ts.RandValAddress()) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), "100") }) } ================================================ FILE: sync/bundle/message/transactions.go ================================================ package message import ( "fmt" "strings" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/tx" ) type TransactionsMessage struct { Transactions []*tx.Tx `cbor:"1,keyasint"` } func NewTransactionsMessage(trxs []*tx.Tx) *TransactionsMessage { return &TransactionsMessage{ Transactions: trxs, } } func (m *TransactionsMessage) BasicCheck() error { if len(m.Transactions) == 0 { return BasicCheckError{Reason: "no transaction"} } for _, trx := range m.Transactions { if err := trx.BasicCheck(); err != nil { return err } } return nil } func (*TransactionsMessage) Type() Type { return TypeTransaction } func (*TransactionsMessage) TopicID() network.TopicID { return network.TopicIDTransaction } func (*TransactionsMessage) ShouldBroadcast() bool { return true } func (*TransactionsMessage) ConsensusHeight() types.Height { return 0 } // LogString returns a concise string representation intended for use in logs. func (m *TransactionsMessage) LogString() string { var builder strings.Builder for _, trx := range m.Transactions { fmt.Fprintf(&builder, "%v ", trx.ID().LogString()) } fmt.Fprintf(&builder, "{%v: ⌘ [%v]}", len(m.Transactions), builder.String()) return builder.String() } ================================================ FILE: sync/bundle/message/transactions_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTransactionsType(t *testing.T) { msg := &TransactionsMessage{} assert.Equal(t, TypeTransaction, msg.Type()) } func TestTransactionsMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("No transactions", func(t *testing.T) { msg := NewTransactionsMessage(nil) err := msg.BasicCheck() require.ErrorIs(t, err, BasicCheckError{Reason: "no transaction"}) }) t.Run("OK", func(t *testing.T) { trx := ts.GenerateTestTransferTx() msg := NewTransactionsMessage([]*tx.Tx{trx}) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), trx.ID().LogString()) }) } ================================================ FILE: sync/bundle/message/vote.go ================================================ package message import ( "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" ) type VoteMessage struct { Vote *vote.Vote `cbor:"1,keyasint"` } func NewVoteMessage(v *vote.Vote) *VoteMessage { return &VoteMessage{ Vote: v, } } func (m *VoteMessage) BasicCheck() error { return m.Vote.BasicCheck() } func (*VoteMessage) Type() Type { return TypeVote } func (*VoteMessage) TopicID() network.TopicID { return network.TopicIDConsensus } func (*VoteMessage) ShouldBroadcast() bool { return true } func (m *VoteMessage) ConsensusHeight() types.Height { return m.Vote.Height() } // LogString returns a concise string representation intended for use in logs. func (m *VoteMessage) LogString() string { return m.Vote.LogString() } ================================================ FILE: sync/bundle/message/vote_test.go ================================================ package message import ( "testing" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestVoteType(t *testing.T) { msg := &VoteMessage{} assert.Equal(t, TypeVote, msg.Type()) } func TestVoteMessage(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid vote", func(t *testing.T) { vte := vote.NewPrepareVote(ts.RandHash(), ts.RandHeight(), -1, ts.RandValAddress()) msg := NewVoteMessage(vte) require.ErrorIs(t, msg.BasicCheck(), vote.BasicCheckError{Reason: "invalid round"}) }) t.Run("OK", func(t *testing.T) { vte, _ := ts.GenerateTestPrepareVote(100, 0) msg := NewVoteMessage(vte) require.NoError(t, msg.BasicCheck()) assert.Contains(t, msg.LogString(), vte.LogString()) }) } ================================================ FILE: sync/cache/cache.go ================================================ package cache import ( lru "github.com/hashicorp/golang-lru/v2" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/util" ) type Cache struct { blocks *lru.Cache[types.Height, *block.Block] // it's thread safe certs *lru.Cache[types.Height, *certificate.Certificate] } func NewCache(size int) (*Cache, error) { blockCache, err := lru.New[types.Height, *block.Block](size) if err != nil { return nil, err } certCache, err := lru.New[types.Height, *certificate.Certificate](size) if err != nil { return nil, err } return &Cache{ blocks: blockCache, certs: certCache, }, nil } func (c *Cache) HasBlockInCache(height types.Height) bool { return c.blocks.Contains(height) } func (c *Cache) GetBlock(height types.Height) *block.Block { blk, ok := c.blocks.Get(height) if ok { return blk } return nil } func (c *Cache) AddBlock(blk *block.Block) { prvCert := blk.PrevCertificate() if prvCert == nil { c.blocks.Add(1, blk) } else { c.blocks.Add(prvCert.Height()+1, blk) c.certs.Add(prvCert.Height(), prvCert) } } func (c *Cache) GetCertificate(height types.Height) *certificate.Certificate { cert, ok := c.certs.Get(height) if ok { return cert } return nil } func (c *Cache) AddCertificate(cert *certificate.Certificate) { if cert != nil { c.certs.Add(cert.Height(), cert) } } // RemoveBlock removes the block and certificates at the specified height from the cache. func (c *Cache) RemoveBlock(height types.Height) { c.blocks.Remove(height) c.certs.Remove(height) } // Len returns the maximum number of items in the blocks and certificates cache. func (c *Cache) Len() int { return util.Max(c.blocks.Len(), c.certs.Len()) } func (c *Cache) Clear() { c.blocks.Purge() c.certs.Purge() } ================================================ FILE: sync/cache/cache_test.go ================================================ package cache import ( "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestAddBlockOne(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) blk1, _ := ts.GenerateTestBlock(1) cache.AddBlock(blk1) assert.True(t, cache.HasBlockInCache(1)) assert.Equal(t, blk1, cache.GetBlock(1)) assert.Nil(t, cache.GetCertificate(0)) } func TestAddBlocks(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) testHeight := ts.RandHeight() blk1, _ := ts.GenerateTestBlock(testHeight) cache.AddBlock(blk1) assert.True(t, cache.HasBlockInCache(testHeight)) assert.Equal(t, blk1, cache.GetBlock(testHeight)) assert.Equal(t, blk1.PrevCertificate(), cache.GetCertificate(testHeight-1)) } func TestAddCertificate(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) testHeight := ts.RandHeight() _, cert1 := ts.GenerateTestBlock(testHeight) cache.AddCertificate(cert1) assert.Equal(t, cert1, cache.GetCertificate(testHeight)) } func TestClearCache(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) blk, _ := ts.GenerateTestBlock(ts.RandHeight()) cache.AddBlock(blk) assert.Equal(t, 1, cache.Len()) cache.Clear() assert.Equal(t, 0, cache.Len()) assert.Nil(t, cache.GetBlock(2)) } func TestCacheIsFull(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) height := types.Height(0) for ; height < 10; height++ { blk, _ := ts.GenerateTestBlock(height + 1) cache.AddBlock(blk) } newBlock, _ := ts.GenerateTestBlock(height + 1) cache.AddBlock(newBlock) assert.NotNil(t, cache.GetBlock(height+1)) assert.Nil(t, cache.GetBlock(1)) } func TestAddAgain(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) height := ts.RandHeight() firstBlk, _ := ts.GenerateTestBlock(height) secondBlk, _ := ts.GenerateTestBlock(height) cache.AddBlock(firstBlk) assert.Equal(t, firstBlk, cache.GetBlock(height)) cache.AddBlock(secondBlk) assert.Equal(t, secondBlk, cache.GetBlock(height)) } func TestRemoveBlock(t *testing.T) { ts := testsuite.NewTestSuite(t) cache, _ := NewCache(10) height := ts.RandHeight() blk1, _ := ts.GenerateTestBlock(height) blk2, _ := ts.GenerateTestBlock(height + 1) cache.AddBlock(blk1) cache.AddBlock(blk2) cache.RemoveBlock(height) assert.Nil(t, cache.GetBlock(height)) assert.Nil(t, cache.GetCertificate(height)) } ================================================ FILE: sync/config.go ================================================ package sync import ( "time" "github.com/pactus-project/pactus/sync/firewall" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/version" ) // Config defines parameters for the sync module. type Config struct { Moniker string `toml:"moniker"` SessionTimeoutStr string `toml:"session_timeout"` Firewall *firewall.Config `toml:"firewall"` // Private configs MaxSessions int `toml:"-"` BlockPerSession uint32 `toml:"-"` BlockPerMessage uint32 `toml:"-"` PruneWindow uint32 `toml:"-"` LatestSupportingVer version.Version `toml:"-"` Services service.Services `toml:"-"` } func DefaultConfig() *Config { return &Config{ SessionTimeoutStr: "10s", Services: service.New(service.PrunedNode), MaxSessions: 8, BlockPerSession: 720, BlockPerMessage: 60, PruneWindow: 86_400, // Default retention blocks in prune mode Firewall: firewall.DefaultConfig(), // v1.9.0 is the hard-fork for Split-Reward support. LatestSupportingVer: version.Version{ Major: 1, Minor: 9, Patch: 0, }, } } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { _, err := time.ParseDuration(conf.SessionTimeoutStr) if err != nil { return err } return conf.Firewall.BasicCheck() } func (conf *Config) CacheSize() int { return util.LogScale( int(conf.BlockPerMessage * conf.BlockPerSession)) } func (conf *Config) SessionTimeout() time.Duration { timeout, _ := time.ParseDuration(conf.SessionTimeoutStr) return timeout } ================================================ FILE: sync/config_test.go ================================================ package sync import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConfigBasicCheck(t *testing.T) { tests := []struct { name string expectedErr string updateFn func(c *Config) }{ { name: "Invalid Session Timeout", expectedErr: "time: invalid duration", updateFn: func(c *Config) { c.SessionTimeoutStr = "INVALID-DURATION" }, }, { name: "DefaultConfig", updateFn: func(*Config) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() tt.updateFn(conf) if tt.expectedErr != "" { err := conf.BasicCheck() assert.ErrorContains(t, err, tt.expectedErr, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } func TestDefaultConfigCheck(t *testing.T) { c := DefaultConfig() require.NoError(t, c.BasicCheck()) assert.Equal(t, 10*time.Second, c.SessionTimeout()) } ================================================ FILE: sync/firewall/config.go ================================================ package firewall import ( "net" ) type RateLimit struct { BlockTopic int `toml:"block_topic"` TransactionTopic int `toml:"transaction_topic"` ConsensusTopic int `toml:"consensus_topic"` } // Config defines parameters for the firewall module. type Config struct { BannedNets []string `toml:"banned_nets"` RateLimit RateLimit `toml:"rate_limit"` } func DefaultConfig() *Config { return &Config{ BannedNets: make([]string, 0), RateLimit: RateLimit{ BlockTopic: 1, TransactionTopic: 5, ConsensusTopic: 0, }, } } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { for _, address := range conf.BannedNets { _, _, err := net.ParseCIDR(address) if err != nil { return err } } return nil } ================================================ FILE: sync/firewall/errors.go ================================================ package firewall import ( "errors" "fmt" lp2pcore "github.com/libp2p/go-libp2p/core" ) // ErrGossipMessage is returned when a stream message sends as gossip message. var ErrGossipMessage = errors.New("receive stream message as gossip message") // ErrStreamMessage is returned when a gossip message sends as stream message. var ErrStreamMessage = errors.New("receive gossip message as stream message") // ErrNetworkMismatch is returned when the bundle doesn't belong to this network. var ErrNetworkMismatch = errors.New("bundle is not for this network") // ErrMisMatchConsensusHeight is returned when the bundle height mismatches with the message consensus height. var ErrMisMatchConsensusHeight = errors.New("bundle and message consensus height mismatch") // PeerBannedError is returned when a message received from a banned peer-id or banned address. type PeerBannedError struct { PeerID lp2pcore.PeerID Address string } func (e PeerBannedError) Error() string { return fmt.Sprintf("peer is banned, peer-id: %s, remote-address: %s", e.PeerID, e.Address) } ================================================ FILE: sync/firewall/firewall.go ================================================ package firewall import ( "bytes" "encoding/binary" "io" "time" "github.com/multiformats/go-multiaddr" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/peerset" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/util/ipblocker" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/ratelimit" ) // Firewall check packets before passing them to sync module. type Firewall struct { config *Config network network.Network peerSet *peerset.PeerSet state state.Facade ipBlocker *ipblocker.IPBlocker blockRateLimit *ratelimit.RateLimit transactionRateLimit *ratelimit.RateLimit consensusRateLimit *ratelimit.RateLimit logger *logger.SubLogger } func NewFirewall(conf *Config, network network.Network, peerSet *peerset.PeerSet, state state.Facade, ) (*Firewall, error) { blocker, err := ipblocker.New(conf.BannedNets) if err != nil { return nil, err } blockRateLimit := ratelimit.NewRateLimit(conf.RateLimit.BlockTopic, time.Second) transactionRateLimit := ratelimit.NewRateLimit(conf.RateLimit.TransactionTopic, time.Second) consensusRateLimit := ratelimit.NewRateLimit(conf.RateLimit.ConsensusTopic, time.Second) return &Firewall{ config: conf, network: network, peerSet: peerSet, state: state, ipBlocker: blocker, blockRateLimit: blockRateLimit, transactionRateLimit: transactionRateLimit, consensusRateLimit: consensusRateLimit, logger: logger.NewSubLogger("_firewall", nil), }, nil } func (f *Firewall) OpenGossipBundle(data []byte, from peer.ID) (*bundle.Bundle, error) { bdl, err := f.openBundle(bytes.NewReader(data), from) if err != nil { return bdl, err } if !bdl.Message.ShouldBroadcast() { f.logger.Warn("firewall: receive stream message as gossip message", "error", err, "bundle", bdl, "from", from) f.closeConnection(from) return nil, ErrGossipMessage } if bdl.ConsensusHeight != bdl.Message.ConsensusHeight() { f.logger.Debug("firewall: consensus height mismatch", "peer", from, "bundle_height", bdl.ConsensusHeight, "message_height", bdl.Message.ConsensusHeight(), ) // Drop the message. In next releases we may ban these peers. return nil, ErrMisMatchConsensusHeight } return bdl, nil } // IsBannedAddress checks if the remote IP address is banned. func (f *Firewall) IsBannedAddress(remoteAddr string) bool { ip, err := f.getIPFromMultiAddress(remoteAddr) if err != nil { // Connect event not yet received from this peer. // Refer to: https://github.com/libp2p/go-libp2p/issues/3074 f.logger.Debug("firewall: unable to parse remote address", "error", err, "addr", remoteAddr) return false } return f.ipBlocker.IsBanned(ip) } func (f *Firewall) OpenStreamBundle(r io.Reader, from peer.ID) (*bundle.Bundle, error) { bdl, err := f.openBundle(r, from) if err != nil { f.logger.Debug("firewall: unable to open a stream bundle", "error", err, "bundle", bdl, "from", from) return nil, err } if bdl.Message.ShouldBroadcast() { f.logger.Warn("firewall: receive gossip message as stream message", "error", err, "bundle", bdl, "from", from) f.closeConnection(from) return nil, ErrStreamMessage } return bdl, nil } func (f *Firewall) openBundle(r io.Reader, from peer.ID) (*bundle.Bundle, error) { f.peerSet.UpdateLastReceived(from) peer := f.peerSet.GetPeer(from) if peer.Status.IsBanned() { f.closeConnection(from) return nil, PeerBannedError{ PeerID: peer.PeerID, Address: peer.Address, } } if f.IsBannedAddress(peer.Address) { f.closeConnection(from) f.peerSet.UpdateStatus(from, status.StatusBanned) return nil, PeerBannedError{ PeerID: peer.PeerID, Address: peer.Address, } } bdl, bytesRead, err := f.decodeBundle(r) if err != nil { f.peerSet.UpdateInvalidMetric(from, int64(bytesRead)) return nil, err } if err := f.checkBundle(bdl); err != nil { f.peerSet.UpdateInvalidMetric(from, int64(bytesRead)) return bdl, err } f.peerSet.UpdateReceivedMetric(from, bdl.Message.Type(), int64(bytesRead)) return bdl, nil } func (*Firewall) decodeBundle(r io.Reader) (*bundle.Bundle, int, error) { bdl := new(bundle.Bundle) bytesRead, err := bdl.Decode(r) if err != nil { return nil, bytesRead, err } return bdl, bytesRead, nil } func (f *Firewall) checkBundle(bdl *bundle.Bundle) error { if err := bdl.BasicCheck(); err != nil { return err } switch f.state.Genesis().ChainType() { case genesis.Mainnet: if bdl.Flags&0x3 != bundle.BundleFlagNetworkMainnet { return ErrNetworkMismatch } case genesis.Testnet: if bdl.Flags&0x3 != bundle.BundleFlagNetworkTestnet { return ErrNetworkMismatch } case genesis.Localnet: if bdl.Flags&0x3 != 0 { return ErrNetworkMismatch } } return nil } func (f *Firewall) closeConnection(pid peer.ID) { f.network.CloseConnection(pid) } func (*Firewall) getIPFromMultiAddress(address string) (string, error) { addr, err := multiaddr.NewMultiaddr(address) if err != nil { return "", err } components := addr.Protocols() var ip string for _, comp := range components { switch comp.Name { // TODO: can parse dns address and find ip?? case "ip4", "ip6": ipComponent, err := addr.ValueForProtocol(comp.Code) if err != nil { return "", err } ip = ipComponent } } return ip, nil } func (f *Firewall) isExpiredMessage(msgData []byte) bool { msgLen := len(msgData) if msgLen < 6 { return true } // Consensus height is the last 4 bytes of the bundle. // Refer to the bundle encoding for more details. consensusHeight := binary.BigEndian.Uint32(msgData[msgLen-4:]) // The message is expired, or the consensus height is behind the network's current height. if f.state.LastBlockHeight() > 0 && consensusHeight < uint32(f.state.LastBlockHeight()-1) { f.logger.Debug("firewall: expired message", "message height", consensusHeight, "our height", f.state.LastBlockHeight()) return true } return false } func (f *Firewall) AllowBlockRequest(gossipMsg *network.GossipMessage) network.PropagationPolicy { if f.isExpiredMessage(gossipMsg.Data) { return network.Drop } if !f.blockRateLimit.AllowRequest() { return network.DropButConsume } return network.Propagate } func (f *Firewall) AllowTransactionRequest(_ *network.GossipMessage) network.PropagationPolicy { if !f.transactionRateLimit.AllowRequest() { return network.DropButConsume } return network.Propagate } func (f *Firewall) AllowConsensusRequest(gossipMsg *network.GossipMessage) network.PropagationPolicy { if f.isExpiredMessage(gossipMsg.Data) { return network.Drop } if !f.consensusRateLimit.AllowRequest() { return network.DropButConsume } return network.Propagate } ================================================ FILE: sync/firewall/firewall_test.go ================================================ package firewall import ( "bytes" "encoding/binary" "testing" "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite firewall *Firewall bannedPeerID peer.ID goodPeerID peer.ID unknownPeerID peer.ID network *network.MockNetwork state *state.MockState } func setup(t *testing.T, conf *Config) *testData { t.Helper() ts := testsuite.NewTestSuite(t) peerSet := peerset.NewPeerSet(1 * time.Minute) state := state.MockingState(ts) net := network.MockingNetwork(ts, ts.RandPeerID()) if conf == nil { conf = DefaultConfig() } require.NoError(t, conf.BasicCheck()) firewall, err := NewFirewall(conf, net, peerSet, state) if err != nil { return nil } assert.NotNil(t, firewall) bannedPeerID := ts.RandPeerID() goodPeerID := ts.RandPeerID() unknownPeerID := ts.RandPeerID() net.AddAnotherNetwork(network.MockingNetwork(ts, goodPeerID), lp2pnetwork.DirOutbound) net.AddAnotherNetwork(network.MockingNetwork(ts, unknownPeerID), lp2pnetwork.DirOutbound) net.AddAnotherNetwork(network.MockingNetwork(ts, bannedPeerID), lp2pnetwork.DirOutbound) firewall.peerSet.UpdateStatus(goodPeerID, status.StatusKnown) firewall.peerSet.UpdateStatus(bannedPeerID, status.StatusBanned) return &testData{ TestSuite: ts, firewall: firewall, network: net, state: state, bannedPeerID: bannedPeerID, goodPeerID: goodPeerID, unknownPeerID: unknownPeerID, } } func (td *testData) testGossipBundle() []byte { bdl := bundle.NewBundle(message.NewQueryVoteMessage(td.RandHeight(), td.RandRound(), td.RandValAddress())) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) d, _ := bdl.Encode() return d } func (td *testData) testStreamBundle() []byte { bdl := bundle.NewBundle(message.NewBlocksRequestMessage(td.RandIntMax(100), 1, 100)) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) d, _ := bdl.Encode() return d } func TestDecodeBundles(t *testing.T) { td := setup(t, nil) tests := []struct { name string data string peerID string wantErr bool }{ { name: "invalid data", data: "bad0", wantErr: true, }, { name: "nil data", data: "", wantErr: true, }, { name: "invalid bundle (round is -1)", data: "a4" + // Map with 4 key-value pairs "01" + "01" + // Key 1 (Flags), Value: 1 (Mainnet) "02" + "06" + // Key 2 (Message Type), Value: 6 (QueryVote) "03" + "581d" + // Key 3 (Message), Value: 30 Bytes "" + "a3" + // Map with 3 key-value pairs "" + "01" + "1864" + // Key 1 (Height), Value: 100 "" + "02" + "20" + // Key 2 (Round), Value: -1 "" + "03" + "5501aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // Key 3 (Querier), Value: 21 Bytes "04" + "1a00000064", // Key 4 (Consensus Height), Value: 100 wantErr: true, }, { name: "valid bundle (invalid network, Testnet)", data: "a4" + // Map with 4 key-value pairs "01" + "02" + // Key 1 (Flags), Value: 1 (Testnet) "02" + "06" + // Key 2 (Message Type), Value: 6 (QueryVote) "03" + "581d" + // Key 3 (Message), Value: 30 Bytes "" + "a3" + // Map with 3 key-value pairs "" + "01" + "1864" + // Key 1 (Height), Value: 100 "" + "02" + "00" + // Key 2 (Round), Value: 0 "" + "03" + "5501aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // Key 3 (Querier), Value: 21 Bytes "04" + "1a00000064", // Key 4 (Consensus Height), Value: 100 wantErr: true, }, { name: "valid bundle", data: "a4" + // Map with 4 key-value pairs "01" + "01" + // Key 1 (Flags), Value: 1 (Mainnet) "02" + "06" + // Key 2 (Message Type), Value: 6 (QueryVote) "03" + "581d" + // Key 3 (Message), Value: 29 Bytes "" + "a3" + // Map with 3 key-value pairs "" + "01" + "1864" + // Key 1 (Height), Value: 100 "" + "02" + "00" + // Key 2 (Round), Value: 0 "" + "03" + "5501aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // Key 3 (Querier), Value: 21 Bytes "04" + "1a00000064", // Key 4 (Consensus Height), Value: 100 wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { bs := td.DecodingHex(tt.data) _, err := td.firewall.OpenGossipBundle(bs, td.unknownPeerID) if tt.wantErr { require.Error(t, err) } else { require.NoError(t, err) } }) } p := td.firewall.peerSet.GetPeer(td.unknownPeerID) assert.Equal(t, int64(1), p.Metric.TotalReceived.Bundles) assert.Equal(t, int64(4), p.Metric.TotalInvalid.Bundles) } func TestGossipMismatchBundleHeight(t *testing.T) { td := setup(t, nil) corruptedData := "a4" + // Map with 4 key-value pairs "01" + "01" + // Key 1 (Flags), Value: 1 (Mainnet) "02" + "06" + // Key 2 (Message Type), Value: 6 (QueryVote) "03" + "581d" + // Key 3 (Message), Value: 29 Bytes "" + "a3" + // Map with 3 key-value pairs "" + "01" + "1864" + // Key 1 (Height), Value: 100 "" + "02" + "00" + // Key 2 (Round), Value: 0 "" + "03" + "5501aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // Key 3 (Querier), Value: 21 Bytes "04" + "1a0000029a" // Bundle Consensus Height = 666 rawMsg := td.DecodingHex(corruptedData) bdl, err := td.firewall.OpenGossipBundle(rawMsg, td.unknownPeerID) assert.Nil(t, bdl) require.Error(t, err) assert.Equal(t, err, ErrMisMatchConsensusHeight) assert.Equal(t, status.StatusUnknown, td.firewall.peerSet.GetPeerStatus(td.unknownPeerID)) } func TestGossipMessage(t *testing.T) { t.Run("Message is nil", func(t *testing.T) { td := setup(t, nil) _, err := td.firewall.OpenGossipBundle(nil, td.unknownPeerID) require.Error(t, err) assert.False(t, td.network.IsClosed(td.unknownPeerID)) }) t.Run("Message from banned peer", func(t *testing.T) { td := setup(t, nil) data := td.testGossipBundle() assert.False(t, td.network.IsClosed(td.bannedPeerID)) _, err := td.firewall.OpenGossipBundle(data, td.bannedPeerID) require.ErrorIs(t, err, PeerBannedError{ PeerID: td.bannedPeerID, Address: "", }) assert.True(t, td.network.IsClosed(td.bannedPeerID)) }) t.Run("Stream message as gossip message", func(t *testing.T) { td := setup(t, nil) data := td.testStreamBundle() assert.False(t, td.network.IsClosed(td.unknownPeerID)) _, err := td.firewall.OpenGossipBundle(data, td.unknownPeerID) require.ErrorIs(t, err, ErrGossipMessage) assert.True(t, td.network.IsClosed(td.unknownPeerID)) }) t.Run("Ok", func(t *testing.T) { td := setup(t, nil) data := td.testGossipBundle() assert.False(t, td.network.IsClosed(td.goodPeerID)) _, err := td.firewall.OpenGossipBundle(data, td.goodPeerID) require.NoError(t, err) assert.False(t, td.network.IsClosed(td.goodPeerID)) }) } func TestStreamMessage(t *testing.T) { t.Run("Message is nil", func(t *testing.T) { td := setup(t, nil) assert.False(t, td.network.IsClosed(td.unknownPeerID)) _, err := td.firewall.OpenStreamBundle(bytes.NewReader(nil), td.unknownPeerID) require.Error(t, err) }) t.Run("Message from banned peer", func(t *testing.T) { td := setup(t, nil) data := td.testStreamBundle() assert.False(t, td.network.IsClosed(td.bannedPeerID)) _, err := td.firewall.OpenStreamBundle(bytes.NewReader(data), td.bannedPeerID) require.ErrorIs(t, err, PeerBannedError{ PeerID: td.bannedPeerID, Address: "", }) assert.True(t, td.network.IsClosed(td.bannedPeerID)) }) t.Run("Gossip message as direct message", func(t *testing.T) { td := setup(t, nil) data := td.testGossipBundle() assert.False(t, td.network.IsClosed(td.unknownPeerID)) _, err := td.firewall.OpenStreamBundle(bytes.NewReader(data), td.unknownPeerID) require.ErrorIs(t, err, ErrStreamMessage) assert.True(t, td.network.IsClosed(td.unknownPeerID)) }) t.Run("Ok", func(t *testing.T) { td := setup(t, nil) data := td.testStreamBundle() assert.False(t, td.network.IsClosed(td.goodPeerID)) _, err := td.firewall.OpenStreamBundle(bytes.NewReader(data), td.goodPeerID) require.NoError(t, err) assert.False(t, td.network.IsClosed(td.goodPeerID)) }) } func TestUpdateLastReceived(t *testing.T) { td := setup(t, nil) data := td.testGossipBundle() nowNano := time.Now().UnixNano() _, err := td.firewall.OpenGossipBundle(data, td.goodPeerID) require.NoError(t, err) peerGood := td.firewall.peerSet.GetPeer(td.goodPeerID) assert.GreaterOrEqual(t, peerGood.LastReceived.UnixNano(), nowNano) } func TestBannedAddress(t *testing.T) { conf := &Config{ BannedNets: []string{ "115.193.0.0/16", "240e:390:8a1:ae80:0000:0000:0000:0000/64", }, } td := setup(t, conf) tests := []struct { addr string banned bool }{ { addr: "/ip4/115.193.157.138/tcp/21888", banned: true, }, { addr: "/ip4/10.10.10.10", banned: false, }, { addr: "/ip6/240e:390:8a1:ae80:7dbc:64b6:e84c:d2bf/udp/21888", banned: true, }, { addr: "/ip6/2a01:4f9:4a:1d85::2", banned: false, }, } for no, tt := range tests { peerID := td.RandPeerID() td.firewall.peerSet.UpdateAddress(peerID, tt.addr, lp2pnetwork.DirInbound) data := td.testGossipBundle() _, err := td.firewall.OpenGossipBundle(data, peerID) if tt.banned { expectedErr := PeerBannedError{ PeerID: peerID, Address: tt.addr, } require.ErrorIs(t, err, expectedErr, "test %v failed, addr %v should be banned", no, tt.addr) } else { require.NoError(t, err, "test %v failed, addr %v should not be banned", no, tt.addr) } } } func TestNetworkFlagsMainnet(t *testing.T) { td := setup(t, nil) bdl := bundle.NewBundle(message.NewQueryVoteMessage(td.RandHeight(), td.RandRound(), td.RandValAddress())) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) err := td.firewall.checkBundle(bdl) require.NoError(t, err) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) err = td.firewall.checkBundle(bdl) require.ErrorIs(t, err, ErrNetworkMismatch) bdl.Flags = 0 err = td.firewall.checkBundle(bdl) require.ErrorIs(t, err, ErrNetworkMismatch) } func TestNetworkFlagsTestnet(t *testing.T) { td := setup(t, nil) td.state.TestGenesis = genesis.TestnetGenesis() bdl := bundle.NewBundle(message.NewQueryVoteMessage(td.RandHeight(), td.RandRound(), td.RandValAddress())) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) err := td.firewall.checkBundle(bdl) require.NoError(t, err) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) err = td.firewall.checkBundle(bdl) require.ErrorIs(t, err, ErrNetworkMismatch) bdl.Flags = 0 err = td.firewall.checkBundle(bdl) require.ErrorIs(t, err, ErrNetworkMismatch) } func TestNetworkFlagsLocalnet(t *testing.T) { td := setup(t, nil) td.state.Genesis().Params().BlockVersion = 0x3f // changing genesis hash bdl := bundle.NewBundle(message.NewQueryVoteMessage(td.RandHeight(), td.RandRound(), td.RandValAddress())) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) err := td.firewall.checkBundle(bdl) require.ErrorIs(t, err, ErrNetworkMismatch) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) err = td.firewall.checkBundle(bdl) require.ErrorIs(t, err, ErrNetworkMismatch) bdl.Flags = 0 err = td.firewall.checkBundle(bdl) require.NoError(t, err) } func TestParseP2PAddr(t *testing.T) { td := setup(t, nil) tests := []struct { name string address string expectedIP string expectError bool }{ { name: "Valid IPv4 with p2p", address: "/ip4/84.247.165.249/tcp/21888/p2p/12D3KooWQmv2FcNQfh1EhA98twt8ePdkQaxEPeYfinEYyVS16juY", expectedIP: "84.247.165.249", }, { name: "Valid IPv4 without p2p", address: "/ip4/115.193.157.138/tcp/21888", expectedIP: "115.193.157.138", }, { name: "Valid IPv6 with p2p", address: "/ip6/240e:390:8a1:ae80:7dbc:64b6:e84c:d2bf/tcp/21888/p2p/" + "12D3KooWQmv2FcNQfh1EhA98twt8ePdkQaxEPeYfinEYyVS16juY", expectedIP: "240e:390:8a1:ae80:7dbc:64b6:e84c:d2bf", }, { name: "Invalid address", address: "/invalid/address", expectError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ip, err := td.firewall.getIPFromMultiAddress(tt.address) if tt.expectError { require.Error(t, err) } else { require.NoError(t, err) assert.Equal(t, tt.expectedIP, ip) } }) } } func makeTestGossipMessage(consensusHeight uint32) *network.GossipMessage { data := make([]byte, 0, 6) data = append(data, 0x04, 0x1a) data = binary.BigEndian.AppendUint32(data, consensusHeight) return &network.GossipMessage{ Data: data, } } func TestAllowBlockRequest(t *testing.T) { conf := DefaultConfig() conf.RateLimit.BlockTopic = 1 td := setup(t, conf) testBlk, testCert := td.GenerateTestBlock(2_900_001) require.NoError(t, td.state.CommitBlock(testBlk, testCert)) t.Run("expired message", func(t *testing.T) { msg := makeTestGossipMessage(uint32(td.state.LastBlockHeight() - 2)) assert.Equal(t, network.Drop, td.firewall.AllowBlockRequest(msg)) }) t.Run("rate limit exceeded", func(t *testing.T) { msg := makeTestGossipMessage(uint32(td.state.LastBlockHeight())) assert.Equal(t, network.Propagate, td.firewall.AllowBlockRequest(msg)) assert.Equal(t, network.DropButConsume, td.firewall.AllowBlockRequest(msg)) }) } func TestAllowTransactionRequest(t *testing.T) { conf := DefaultConfig() conf.RateLimit.TransactionTopic = 1 td := setup(t, conf) t.Run("rate limit exceeded", func(t *testing.T) { msg := makeTestGossipMessage(uint32(td.state.LastBlockHeight())) assert.Equal(t, network.Propagate, td.firewall.AllowTransactionRequest(msg)) assert.Equal(t, network.DropButConsume, td.firewall.AllowTransactionRequest(msg)) }) } func TestAllowConsensusRequest(t *testing.T) { conf := DefaultConfig() conf.RateLimit.ConsensusTopic = 1 td := setup(t, conf) testBlk, testCert := td.GenerateTestBlock(2_900_001) require.NoError(t, td.state.CommitBlock(testBlk, testCert)) t.Run("expired message", func(t *testing.T) { msg := makeTestGossipMessage(uint32(td.state.LastBlockHeight() - 2)) assert.Equal(t, network.Drop, td.firewall.AllowConsensusRequest(msg)) }) t.Run("rate limit exceeded", func(t *testing.T) { msg := makeTestGossipMessage(uint32(td.state.LastBlockHeight())) assert.Equal(t, network.Propagate, td.firewall.AllowConsensusRequest(msg)) assert.Equal(t, network.DropButConsume, td.firewall.AllowConsensusRequest(msg)) }) } ================================================ FILE: sync/handler.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" ) type messageHandler interface { ParseMessage(message.Message, peer.ID) PrepareBundle(message.Message) *bundle.Bundle } ================================================ FILE: sync/handler_block_announce.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" ) type blockAnnounceHandler struct { *synchronizer } func newBlockAnnounceHandler(sync *synchronizer) messageHandler { return &blockAnnounceHandler{ sync, } } func (handler *blockAnnounceHandler) ParseMessage(m message.Message, pid peer.ID) { msg := m.(*message.BlockAnnounceMessage) handler.logger.Trace("parsing BlockAnnounce message", "msg", msg) if handler.cache.HasBlockInCache(msg.Height()) { // We have processed this block before. return } handler.peerSet.UpdateHeight(pid, msg.Height(), msg.Block.Hash()) handler.cache.AddCertificate(msg.Certificate) handler.cache.AddBlock(msg.Block) handler.tryCommitBlocks() handler.moveConsensusToNewHeight() handler.updateBlockchain() } func (*blockAnnounceHandler) PrepareBundle(m message.Message) *bundle.Bundle { bdl := bundle.NewBundle(m) return bdl } ================================================ FILE: sync/handler_block_announce_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/stretchr/testify/assert" ) func TestHandlerBlockAnnounceParsingMessages(t *testing.T) { td := setup(t, nil) td.state.CommitTestBlocks(10) pid := td.RandPeerID() lastHeight := td.state.LastBlockHeight() blk1, cert1 := td.GenerateTestBlock(lastHeight + 1) msg1 := message.NewBlockAnnounceMessage(blk1, cert1, nil) blk2, cert2 := td.GenerateTestBlock(lastHeight + 2) msg2 := message.NewBlockAnnounceMessage(blk2, cert2, nil) t.Run("Receiving new block announce message, without committing previous block", func(t *testing.T) { td.receivingNewMessage(td.sync, msg2, pid) stateHeight := td.sync.state.LastBlockHeight() consHeight, _ := td.sync.getConsMgr().HeightRound() assert.Equal(t, lastHeight, stateHeight) assert.Equal(t, lastHeight+1, consHeight) }) t.Run("Receiving missed block, should commit both blocks", func(t *testing.T) { td.receivingNewMessage(td.sync, msg1, pid) assert.Equal(t, lastHeight+2, td.sync.state.LastBlockHeight()) }) } func TestHandlerBlockAnnounceBroadcastingMessages(t *testing.T) { td := setup(t, nil) blk, cert := td.GenerateTestBlock(td.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert, nil) td.sync.broadcast(msg) msg1 := td.shouldPublishMessageWithThisType(t, message.TypeBlockAnnounce) assert.Equal(t, msg.Certificate.Height(), msg1.Message.(*message.BlockAnnounceMessage).Certificate.Height()) } func TestHandlerBlockAnnounceCacheBlock(t *testing.T) { td := setup(t, nil) height := td.RandHeight() blk1, cert1 := td.GenerateTestBlock(height) blk2, cert2 := td.GenerateTestBlock(height) msg1 := message.NewBlockAnnounceMessage(blk1, cert1, nil) msg2 := message.NewBlockAnnounceMessage(blk2, cert2, nil) td.receivingNewMessage(td.sync, msg1, td.RandPeerID()) td.receivingNewMessage(td.sync, msg2, td.RandPeerID()) cachedBlock := td.sync.cache.GetBlock(height) cachedCert := td.sync.cache.GetCertificate(height) assert.Equal(t, blk1, cachedBlock) assert.Equal(t, cert1, cachedCert) } ================================================ FILE: sync/handler_blocks_request.go ================================================ package sync import ( "fmt" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util" ) type blocksRequestHandler struct { *synchronizer } func newBlocksRequestHandler(sync *synchronizer) messageHandler { return &blocksRequestHandler{ sync, } } func (handler *blocksRequestHandler) ParseMessage(m message.Message, pid peer.ID) { msg := m.(*message.BlocksRequestMessage) handler.logger.Trace("parsing BlocksRequest message", "msg", msg) peer := handler.peerSet.GetPeer(pid) if peer == nil { response := message.NewBlocksResponseMessage(message.ResponseCodeRejected, fmt.Sprintf("unknown peer (%s)", pid.String()), msg.SessionID, 0, nil, nil) handler.respond(response, pid) return } if !peer.Status.IsKnown() { response := message.NewBlocksResponseMessage(message.ResponseCodeRejected, fmt.Sprintf("not handshaked (%s)", peer.Status.String()), msg.SessionID, 0, nil, nil) handler.respond(response, pid) return } ourHeight := handler.state.LastBlockHeight() if msg.From > ourHeight { response := message.NewBlocksResponseMessage(message.ResponseCodeRejected, fmt.Sprintf("requested blocks from %v exceed current height %v", msg.From, ourHeight), msg.SessionID, 0, nil, nil) handler.respond(response, pid) return } if msg.Count > handler.config.BlockPerSession { response := message.NewBlocksResponseMessage(message.ResponseCodeRejected, fmt.Sprintf("requested block range %v-%v exceeds the allowed %v blocks per session", msg.From, msg.To(), handler.config.BlockPerSession), msg.SessionID, 0, nil, nil) handler.respond(response, pid) return } // Help this peer to sync up height := msg.From count := msg.Count for { blockCount := util.Min(handler.config.BlockPerMessage, count) blocksData := handler.prepareBlocks(height, blockCount) if len(blocksData) == 0 { break } response := message.NewBlocksResponseMessage(message.ResponseCodeMoreBlocks, message.ResponseCodeMoreBlocks.String(), msg.SessionID, height, blocksData, nil) handler.respond(response, pid) height += types.Height(len(blocksData)) count -= uint32(len(blocksData)) if count <= 0 { break } } if msg.To() >= ourHeight { lastCert := handler.state.LastCertificate() response := message.NewBlocksResponseMessage(message.ResponseCodeSynced, message.ResponseCodeSynced.String(), msg.SessionID, lastCert.Height(), nil, lastCert) handler.respond(response, pid) return } response := message.NewBlocksResponseMessage(message.ResponseCodeNoMoreBlocks, message.ResponseCodeNoMoreBlocks.String(), msg.SessionID, 0, nil, nil) handler.respond(response, pid) } func (*blocksRequestHandler) PrepareBundle(m message.Message) *bundle.Bundle { return bundle.NewBundle(m) } func (handler *blocksRequestHandler) respond(msg *message.BlocksResponseMessage, pid peer.ID) { if msg.ResponseCode == message.ResponseCodeRejected { handler.logger.Debug("rejecting block request message", "msg", msg, "pid", pid, "reason", msg.Reason) handler.sendTo(msg, pid) } else { handler.logger.Info("responding block request message", "msg", msg, "pid", pid) handler.sendTo(msg, pid) } } ================================================ FILE: sync/handler_blocks_request_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/types" "github.com/stretchr/testify/assert" ) func TestHandlerBlocksRequestParsingMessages(t *testing.T) { t.Run("NetworkLimited service is enabled", func(t *testing.T) { config := testConfig() config.Services = service.Services(service.PrunedNode) td := setup(t, config) sid := td.RandIntMax(100) td.state.CommitTestBlocks(31) curHeight := td.state.LastBlockHeight() t.Run("Reject request from unknown peers", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewBlocksRequestMessage(sid, curHeight-1, 1) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res := bdl.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeRejected, res.ResponseCode) assert.Contains(t, res.Reason, "unknown peer") assert.Zero(t, res.From) assert.Equal(t, sid, res.SessionID) }) t.Run("Reject request from peers without handshaking", func(t *testing.T) { pid := td.addPeer(t, status.StatusConnected, service.New(service.None)) msg := message.NewBlocksRequestMessage(sid, curHeight-1, 1) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res := bdl.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeRejected, res.ResponseCode) assert.Contains(t, res.Reason, "not handshaked") }) pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) t.Run("Peer requested blocks that we don't have", func(t *testing.T) { msg := message.NewBlocksRequestMessage(sid, curHeight+1, 1) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res := bdl.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeRejected, res.ResponseCode) assert.Contains(t, res.Reason, "requested blocks from 32 exceed current height 31") }) t.Run("Request blocks more than `BlockPerSession`", func(t *testing.T) { msg := message.NewBlocksRequestMessage(sid, 10, config.BlockPerSession+1) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res := bdl.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeRejected, res.ResponseCode) assert.Contains(t, res.Reason, "requested block range 10-37 exceeds the allowed 27 blocks per session") }) t.Run("Accept request within `BlockPerSession`", func(t *testing.T) { t.Run("Peer needs more block", func(t *testing.T) { msg := message.NewBlocksRequestMessage(sid, curHeight-types.Height(config.BlockPerMessage), config.BlockPerMessage) td.receivingNewMessage(td.sync, msg, pid) bdl1 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res1 := bdl1.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeMoreBlocks, res1.ResponseCode) assert.Equal(t, curHeight-types.Height(config.BlockPerMessage), res1.From) assert.Equal(t, curHeight-1, res1.To()) assert.Equal(t, config.BlockPerMessage, res1.Count()) bdl2 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res2 := bdl2.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeNoMoreBlocks, res2.ResponseCode) assert.Zero(t, res2.From) assert.Zero(t, res2.To()) assert.Zero(t, res2.Count()) }) t.Run("Peer synced", func(t *testing.T) { msg := message.NewBlocksRequestMessage(sid, curHeight-types.Height(config.BlockPerMessage)+1, config.BlockPerMessage) td.receivingNewMessage(td.sync, msg, pid) bdl1 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res1 := bdl1.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeMoreBlocks, res1.ResponseCode) assert.Equal(t, curHeight-types.Height(config.BlockPerMessage)+1, res1.From) assert.Equal(t, curHeight, res1.To()) assert.Equal(t, config.BlockPerMessage, res1.Count()) bdl2 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res2 := bdl2.Message.(*message.BlocksResponseMessage) assert.Equal(t, message.ResponseCodeSynced, res2.ResponseCode) assert.Equal(t, curHeight, res2.From) assert.Zero(t, res2.To()) assert.Zero(t, res2.Count()) }) }) }) t.Run("Network service is enabled", func(t *testing.T) { config := testConfig() config.Services = service.New(service.FullNode) td := setup(t, config) sid := td.RandIntMax(100) td.state.CommitTestBlocks(31) pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) t.Run("Requesting one block", func(t *testing.T) { msg := message.NewBlocksRequestMessage(sid, 1, 2) td.receivingNewMessage(td.sync, msg, pid) msg1 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) assert.Equal(t, message.ResponseCodeMoreBlocks, msg1.Message.(*message.BlocksResponseMessage).ResponseCode) msg2 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) assert.Equal(t, message.ResponseCodeNoMoreBlocks, msg2.Message.(*message.BlocksResponseMessage).ResponseCode) }) }) } ================================================ FILE: sync/handler_blocks_response.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/types/block" ) type blocksResponseHandler struct { *synchronizer } func newBlocksResponseHandler(sync *synchronizer) messageHandler { return &blocksResponseHandler{ sync, } } func (handler *blocksResponseHandler) ParseMessage(m message.Message, pid peer.ID) { msg := m.(*message.BlocksResponseMessage) handler.logger.Trace("parsing BlocksResponse message", "msg", msg) if msg.IsRequestRejected() { handler.logger.Warn("blocks request is rejected", "pid", pid, "reason", msg.Reason, "sid", msg.SessionID) } else { handler.logger.Info("blocks received", "from", msg.From, "count", msg.Count(), "pid", pid, "sid", msg.SessionID) // TODO: // It is good to check the latest height before adding blocks to the cache. // If they have already been committed, this message can be ignored. // Need to test! for _, data := range msg.BlocksData { blk, err := block.FromBytes(data) if err != nil { handler.logger.Warn("unable to decode block data", "from", msg.From, "pid", pid, "error", err) } else { handler.cache.AddBlock(blk) } } handler.cache.AddCertificate(msg.LastCertificate) handler.tryCommitBlocks() } handler.updateSession(msg.SessionID, msg.ResponseCode) } func (*blocksResponseHandler) PrepareBundle(m message.Message) *bundle.Bundle { bdl := bundle.NewBundle(m) bdl.CompressIt() return bdl } func (handler *blocksResponseHandler) updateSession(sid int, code message.ResponseCode) { switch code { case message.ResponseCodeOK: handler.logger.Debug("session accepted. keep session open", "sid", sid) handler.peerSet.UpdateSessionLastActivity(sid) case message.ResponseCodeRejected: handler.logger.Debug("session rejected, uncompleted session", "sid", sid) handler.peerSet.SetSessionUncompleted(sid) case message.ResponseCodeMoreBlocks: handler.logger.Debug("peer responding us. keep session open", "sid", sid) handler.peerSet.UpdateSessionLastActivity(sid) case message.ResponseCodeNoMoreBlocks: handler.logger.Debug("peer sent all blocks. close session", "sid", sid) handler.peerSet.SetSessionCompleted(sid) // TODO: test me handler.updateBlockchain() case message.ResponseCodeSynced: handler.logger.Debug("peer informed us we are synced. close session", "sid", sid) handler.peerSet.SetSessionCompleted(sid) // TODO: test me handler.moveConsensusToNewHeight() } } ================================================ FILE: sync/handler_blocks_response_test.go ================================================ package sync import ( "fmt" "testing" "time" "github.com/ezex-io/gopkg/pipeline" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHandlerBlocksResponseInvalidBlockData(t *testing.T) { td := setup(t, nil) td.state.CommitTestBlocks(10) lastHeight := td.state.LastBlockHeight() blk, cert := td.GenerateTestBlock(lastHeight+1, testsuite.BlockWithPrevCert(nil)) data, _ := blk.Bytes() tests := []struct { data []byte }{ {data: td.RandBytes(16)}, {data: data}, } for _, tt := range tests { pid := td.RandPeerID() sid := td.RandIntMax(1000) msg := message.NewBlocksResponseMessage(message.ResponseCodeMoreBlocks, message.ResponseCodeMoreBlocks.String(), sid, lastHeight+1, [][]byte{tt.data}, cert) td.receivingNewMessage(td.sync, msg, pid) assert.Nil(t, td.sync.cache.GetBlock(msg.From)) } } func TestHandlerBlocksResponseOneBlockShorter(t *testing.T) { td := setup(t, nil) td.state.CommitTestBlocks(10) lastHeight := td.state.LastBlockHeight() blk1, cert1 := td.GenerateTestBlock(lastHeight + 1) d1, _ := blk1.Bytes() pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) sid := td.RandIntMax(1000) msg := message.NewBlocksResponseMessage(message.ResponseCodeSynced, t.Name(), sid, lastHeight+1, [][]byte{d1}, cert1) td.receivingNewMessage(td.sync, msg, pid) assert.Equal(t, lastHeight+1, td.state.LastBlockHeight()) } func TestHandlerBlocksResponseStrippedPublicKey(t *testing.T) { td := setup(t, nil) td.state.CommitTestBlocks(10) lastHeight := td.state.LastBlockHeight() // Add a new block and keep the signer key _, indexedPrv := td.RandBLSKeyPair() trx0 := td.GenerateTestTransferTx(testsuite.TransactionWithSigner(indexedPrv)) trxs0 := []*tx.Tx{trx0} blk0, cert0 := td.GenerateTestBlock(lastHeight+1, testsuite.BlockWithTransactions(trxs0)) err := td.state.CommitBlock(blk0, cert0) require.NoError(t, err) lastHeight++ // ----- _, rndPrv := td.RandBLSKeyPair() trx1 := td.GenerateTestTransferTx(testsuite.TransactionWithSigner(rndPrv)) trx1.StripPublicKey() trxs1 := []*tx.Tx{trx1} blk1, _ := td.GenerateTestBlock(lastHeight+1, testsuite.BlockWithTransactions(trxs1)) trx2 := td.GenerateTestTransferTx(testsuite.TransactionWithSigner(indexedPrv)) trx2.StripPublicKey() trxs2 := []*tx.Tx{trx2} blk2, _ := td.GenerateTestBlock(lastHeight+1, testsuite.BlockWithTransactions(trxs2)) tests := []struct { receivedBlock *block.Block shouldFail bool }{ { receivedBlock: blk1, shouldFail: true, }, { receivedBlock: blk2, shouldFail: false, }, } // Add a peer pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) for _, tt := range tests { blkData, _ := tt.receivedBlock.Bytes() sid := td.RandIntMax(1000) cert := td.GenerateTestCertificate(lastHeight + 1) msg := message.NewBlocksResponseMessage(message.ResponseCodeMoreBlocks, message.ResponseCodeMoreBlocks.String(), sid, lastHeight+1, [][]byte{blkData}, cert) td.receivingNewMessage(td.sync, msg, pid) if tt.shouldFail { assert.Nil(t, td.sync.cache.GetBlock(msg.From)) } else { assert.NotNil(t, td.sync.cache.GetBlock(msg.From)) } } } func shouldPublishBlockRequest(t *testing.T, net *network.MockNetwork, from types.Height) { t.Helper() bdl := shouldPublishMessageWithThisType(t, net, message.TypeBlocksRequest) msg := bdl.Message.(*message.BlocksRequestMessage) require.Equal(t, from, msg.From) } func shouldPublishBlockResponse(t *testing.T, net *network.MockNetwork, from types.Height, count uint32, code message.ResponseCode, ) { t.Helper() bdl := shouldPublishMessageWithThisType(t, net, message.TypeBlocksResponse) msg := bdl.Message.(*message.BlocksResponseMessage) require.Equal(t, from, msg.From) require.Equal(t, count, msg.Count()) require.Equal(t, code, msg.ResponseCode) } type networkAliceBob struct { *testsuite.TestSuite stateAlice *state.MockState stateBob *state.MockState networkAlice *network.MockNetwork networkBob *network.MockNetwork syncAlice *synchronizer syncBob *synchronizer } func makeAliceAndBobNetworks(t *testing.T) *networkAliceBob { t.Helper() ts := testsuite.NewTestSuite(t) configAlice := testConfig() configBob := testConfig() valKeyAlice := []*bls.ValidatorKey{ts.RandValKey()} valKeyBob := []*bls.ValidatorKey{ts.RandValKey()} stateAlice := state.MockingState(ts) stateBob := state.MockingState(ts) consV1MgrAlice, _ := consmgr.MockingManager(ts, stateAlice, valKeyAlice) consV2MgrAlice, _ := consmgr.MockingManager(ts, stateAlice, valKeyAlice) consV1MgrBob, _ := consmgr.MockingManager(ts, stateBob, valKeyBob) consV2MgrBob, _ := consmgr.MockingManager(ts, stateBob, valKeyBob) broadcastPipe := pipeline.New[message.Message](t.Context()) networkAlice := network.MockingNetwork(ts, ts.RandPeerID()) networkBob := network.MockingNetwork(ts, ts.RandPeerID()) sync1, err := NewSynchronizer(t.Context(), configAlice, valKeyAlice, stateAlice, consV1MgrAlice, consV2MgrAlice, networkAlice, broadcastPipe, networkAlice.EventPipe) require.NoError(t, err) syncAlice := sync1.(*synchronizer) sync2, err := NewSynchronizer(t.Context(), configBob, valKeyBob, stateBob, consV1MgrBob, consV2MgrBob, networkBob, broadcastPipe, networkBob.EventPipe) require.NoError(t, err) syncBob := sync2.(*synchronizer) // ------------------------------- // Better logging during testing overrideLogger := func(sync *synchronizer, name string) { sync.logger = logger.NewSubLogger("_sync", testsuite.NewOverrideLogStringer(fmt.Sprintf("%s - %s: ", name, t.Name()), sync)) } overrideLogger(syncAlice, "Alice") overrideLogger(syncBob, "Bob") // ------------------------------- require.NoError(t, syncAlice.Start()) require.NoError(t, syncBob.Start()) // Connect the networks of Alice and Bob to each other (Alice is outbound, Bob is inbound) networkBob.AddAnotherNetwork(networkAlice, lp2pnetwork.DirInbound) networkAlice.AddAnotherNetwork(networkBob, lp2pnetwork.DirOutbound) // Verify that Hello messages are exchanged between Alice and Bob // Alice sends hello to Bob shouldPublishMessageWithThisType(t, networkAlice, message.TypeHello) shouldPublishMessageWithThisType(t, networkBob, message.TypeHello) shouldPublishMessageWithThisType(t, networkBob, message.TypeHelloAck) shouldPublishMessageWithThisType(t, networkAlice, message.TypeHelloAck) // Ensure Alice and Bob are connected and handshaked require.Eventually(t, func() bool { return syncAlice.PeerSet().GetPeerStatus(syncBob.SelfID()).IsKnown() && syncBob.PeerSet().GetPeerStatus(syncAlice.SelfID()).IsKnown() }, 2*time.Second, 100*time.Millisecond) return &networkAliceBob{ TestSuite: ts, syncAlice: syncAlice, stateAlice: stateAlice, networkAlice: networkAlice, syncBob: syncBob, stateBob: stateBob, networkBob: networkBob, } } // TestIdenticalBundles tests if two different peers publish the same message, // whether the bundle data is also the same. func TestHandlerBlocksResponseIdenticalBundles(t *testing.T) { nets := makeAliceAndBobNetworks(t) blk, cert := nets.GenerateTestBlock(nets.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert, nil) bdlAlice := nets.syncAlice.prepareBundle(msg) bdlBob := nets.syncBob.prepareBundle(msg) assert.Equal(t, bdlAlice, bdlBob) } // TestSyncing is an important test to verify the syncing process between two // test nodes, Alice and Bob. In real-world scenarios, multiple nodes are typically // involved, but the procedure remains similar. func TestHandlerBlocksResponseSyncing(t *testing.T) { nets := makeAliceAndBobNetworks(t) // Adding 100 blocks for Bob blockInterval := nets.syncBob.state.Genesis().Params().BlockInterval() blockTime := nets.syncBob.state.Genesis().GenesisTime() for i := types.Height(0); i < 100; i++ { blk, cert := nets.GenerateTestBlock(i+1, testsuite.BlockWithTime(blockTime)) require.NoError(t, nets.syncBob.state.CommitBlock(blk, cert)) blockTime = blockTime.Add(blockInterval) } assert.Equal(t, types.Height(0), nets.syncAlice.state.LastBlockHeight()) assert.Equal(t, types.Height(100), nets.syncBob.state.LastBlockHeight()) // Announcing a block blk, cert := nets.GenerateTestBlock(nets.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert, nil) nets.syncBob.broadcast(msg) shouldPublishMessageWithThisType(t, nets.networkBob, message.TypeBlockAnnounce) // Perform block syncing assert.Equal(t, uint32(11), nets.syncAlice.config.BlockPerMessage) assert.Equal(t, uint32(27), nets.syncAlice.config.BlockPerSession) shouldPublishBlockRequest(t, nets.networkAlice, 1) shouldPublishBlockResponse(t, nets.networkBob, 1, 11, message.ResponseCodeMoreBlocks) // 1-11 shouldPublishBlockResponse(t, nets.networkBob, 12, 11, message.ResponseCodeMoreBlocks) // 12-22 shouldPublishBlockResponse(t, nets.networkBob, 23, 5, message.ResponseCodeMoreBlocks) // 23-27 shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock shouldPublishBlockRequest(t, nets.networkAlice, 28) shouldPublishBlockResponse(t, nets.networkBob, 28, 11, message.ResponseCodeMoreBlocks) // 28-38 shouldPublishBlockResponse(t, nets.networkBob, 39, 11, message.ResponseCodeMoreBlocks) // 39-49 shouldPublishBlockResponse(t, nets.networkBob, 50, 5, message.ResponseCodeMoreBlocks) // 50-54 shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock shouldPublishBlockRequest(t, nets.networkAlice, 55) shouldPublishBlockResponse(t, nets.networkBob, 55, 11, message.ResponseCodeMoreBlocks) // 55-65 shouldPublishBlockResponse(t, nets.networkBob, 66, 11, message.ResponseCodeMoreBlocks) // 66-76 shouldPublishBlockResponse(t, nets.networkBob, 77, 5, message.ResponseCodeMoreBlocks) // 77-81 shouldPublishBlockResponse(t, nets.networkBob, 0, 0, message.ResponseCodeNoMoreBlocks) // NoMoreBlock shouldPublishBlockRequest(t, nets.networkAlice, 82) shouldPublishBlockResponse(t, nets.networkBob, 82, 11, message.ResponseCodeMoreBlocks) // 82-92 shouldPublishBlockResponse(t, nets.networkBob, 93, 8, message.ResponseCodeMoreBlocks) // 93-100 shouldPublishBlockResponse(t, nets.networkBob, 100, 0, message.ResponseCodeSynced) // Synced assert.Eventually(t, func() bool { return nets.syncAlice.state.LastBlockHeight() == types.Height(100) }, 10*time.Second, 1*time.Second) } func TestHandlerBlocksResponseSyncingHasBlockInCache(t *testing.T) { nets := makeAliceAndBobNetworks(t) // Adding 100 blocks for Bob blockInterval := nets.syncBob.state.Genesis().Params().BlockInterval() blockTime := nets.syncBob.state.Genesis().GenesisTime() for i := types.Height(0); i < 23; i++ { blk, cert := nets.GenerateTestBlock(i+1, testsuite.BlockWithTime(blockTime)) require.NoError(t, nets.syncBob.state.CommitBlock(blk, cert)) blockTime = blockTime.Add(blockInterval) } assert.Equal(t, types.Height(0), nets.syncAlice.state.LastBlockHeight()) assert.Equal(t, types.Height(23), nets.syncBob.state.LastBlockHeight()) // Adding some blocks to the cache blk1 := nets.stateBob.TestStore.Blocks[1] blk2 := nets.stateBob.TestStore.Blocks[2] blk3 := nets.stateBob.TestStore.Blocks[3] nets.syncAlice.cache.AddBlock(blk1) nets.syncAlice.cache.AddBlock(blk2) nets.syncAlice.cache.AddBlock(blk3) // Announcing a block blk, cert := nets.GenerateTestBlock(nets.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert, nil) nets.syncBob.broadcast(msg) shouldPublishMessageWithThisType(t, nets.networkBob, message.TypeBlockAnnounce) // blocks 1-2 are inside the cache shouldPublishBlockRequest(t, nets.networkAlice, 4) shouldPublishBlockResponse(t, nets.networkBob, 4, 11, message.ResponseCodeMoreBlocks) // 4-14 shouldPublishBlockResponse(t, nets.networkBob, 15, 9, message.ResponseCodeMoreBlocks) // 15-23 shouldPublishBlockResponse(t, nets.networkBob, 23, 0, message.ResponseCodeSynced) // Synced } ================================================ FILE: sync/handler_hello.go ================================================ package sync import ( "fmt" "math" "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/version" ) // // Handshake protocol in Pactus // // Handshake protocol is used to exchange information between two peers // when they first connect to each other. The handshake process involves // the following steps: // // 1. When two peers connect, the outbound peer first sends a Hello message to the inbound peer. // 2. The inbound peer responds with a HelloAck message. // 3. Then the Inbound peer sends a Hello message to the outbound peer. // 4. Finally, the outbound peer responds with a HelloAck message. // // | | // Outbound Peer | | Inbound Peer // | | // Connected | | Connected // | | // | Hello | // | ---------------------> | // | HelloAck | // | <--------------------- | // | | // | Hello | // Known | <--------------------- | // | HelloAck | // | ---------------------> | Known // | | // // After the handshake process is complete, both peers have exchanged // information about their status, such as their latest block height, // genesis hash, and supported services. This information is used to // determine whether the peers are compatible and can communicate // effectively. // type helloHandler struct { *synchronizer } func newHelloHandler(sync *synchronizer) messageHandler { return &helloHandler{ sync, } } func (handler *helloHandler) ParseMessage(m message.Message, pid peer.ID) { msg := m.(*message.HelloMessage) handler.logger.Trace("parsing Hello message", "msg", msg) handler.logger.Debug("updating peer info", "pid", pid, "moniker", msg.Moniker, "services", msg.Services) handler.peerSet.UpdateInfo(pid, msg.Moniker, msg.Agent, msg.PublicKeys, msg.Services) handler.peerSet.UpdateHeight(pid, msg.Height, msg.BlockHash) if msg.GenesisHash != handler.state.Genesis().Hash() { response := message.NewHelloAckMessage(message.ResponseCodeRejected, fmt.Sprintf("invalid genesis hash, expected: %v, got: %v", handler.state.Genesis().Hash(), msg.GenesisHash), 0) handler.acknowledge(response, pid) return } if math.Abs(time.Since(msg.MyTime()).Seconds()) > 10 { response := message.NewHelloAckMessage(message.ResponseCodeRejected, "time discrepancy exceeds 10 seconds", 0) handler.acknowledge(response, pid) return } agent, _ := version.ParseAgent(msg.Agent) if agent.Version.Compare(handler.config.LatestSupportingVer) == -1 { response := message.NewHelloAckMessage(message.ResponseCodeRejected, "not supporting Pactus version", 0) handler.acknowledge(response, pid) return } for _, pub := range msg.PublicKeys { handler.state.UpdateValidatorProtocolVersion(pub.ValidatorAddress(), agent.ProtocolVersion) } if handler.state.Params().BlockVersion == protocol.ProtocolVersionLatest && agent.ProtocolVersion < protocol.ProtocolVersionLatest { response := message.NewHelloAckMessage(message.ResponseCodeRejected, "not supporting protocol version", 0) handler.acknowledge(response, pid) return } peer := handler.peerSet.GetPeer(pid) switch peer.Direction { case lp2pnetwork.DirUnknown: handler.logger.Warn("received unexpected Hello message", "pid", pid, "direction", peer.Direction) handler.network.CloseConnection(pid) return case lp2pnetwork.DirInbound: if peer.OutboundHelloSent { handler.logger.Warn("received unexpected Hello message", "pid", pid, "direction", peer.Direction) return } // Mark that we've received the hello message from the outbound peer handler.peerSet.UpdateOutboundHelloSent(pid, true) handler.logger.Info("sending Hello message (inbound)", "to", pid) handler.sayHello(pid) case lp2pnetwork.DirOutbound: if !peer.OutboundHelloSent { handler.logger.Warn("received unexpected Hello message", "pid", pid, "direction", peer.Direction) return } handler.peerSet.UpdateStatus(pid, status.StatusKnown) } response := message.NewHelloAckMessage(message.ResponseCodeOK, "Ok", handler.state.LastBlockHeight()) handler.acknowledge(response, pid) } func (*helloHandler) PrepareBundle(m message.Message) *bundle.Bundle { bdl := bundle.NewBundle(m) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagHandshaking) return bdl } func (handler *helloHandler) acknowledge(msg *message.HelloAckMessage, pid peer.ID) { if msg.ResponseCode == message.ResponseCodeRejected { handler.logger.Info("rejecting hello message", "msg", msg, "pid", pid, "reason", msg.Reason) handler.sendTo(msg, pid) handler.peerSet.UpdateStatus(pid, status.StatusBanned) } else { handler.logger.Info("acknowledging hello message", "msg", msg, "pid", pid) handler.sendTo(msg, pid) } } ================================================ FILE: sync/handler_hello_ack.go ================================================ package sync import ( lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/util" ) type helloAckHandler struct { *synchronizer } func newHelloAckHandler(sync *synchronizer) messageHandler { return &helloAckHandler{ sync, } } func (handler *helloAckHandler) ParseMessage(m message.Message, pid peer.ID) { msg := m.(*message.HelloAckMessage) handler.logger.Trace("parsing HelloAck message", "msg", msg) if msg.ResponseCode == message.ResponseCodeRejected { handler.logger.Warn("hello message rejected", "from", pid, "reason", msg.Reason) handler.network.CloseConnection(pid) return } peer := handler.peerSet.GetPeer(pid) if peer == nil { handler.logger.Warn("received HelloAck from unknown peer", "pid", pid) handler.network.CloseConnection(pid) return } switch peer.Direction { case lp2pnetwork.DirUnknown: handler.logger.Warn("received unexpected HelloAc message", "pid", pid, "direction", peer.Direction) handler.network.CloseConnection(pid) return case lp2pnetwork.DirInbound: if !peer.OutboundHelloSent { handler.logger.Warn("received unexpected HelloAc message", "pid", pid, "direction", peer.Direction) return } case lp2pnetwork.DirOutbound: if !peer.OutboundHelloSent { handler.logger.Warn("received unexpected HelloAc message", "pid", pid, "direction", peer.Direction) return } } handler.peerSet.UpdateStatus(pid, status.StatusKnown) handler.logger.Info("hello message acknowledged", "pid", pid, "reason", msg.Reason) if msg.Height > handler.state.LastBlockHeight() { handler.updateBlockchain() } } func (*helloAckHandler) PrepareBundle(m message.Message) *bundle.Bundle { bdl := bundle.NewBundle(m) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagHandshaking) return bdl } ================================================ FILE: sync/handler_hello_ack_test.go ================================================ package sync import ( "testing" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer/status" ) func TestHandlerHelloAckParsingMessages(t *testing.T) { td := setup(t, nil) t.Run("Receiving HelloAck message: Rejected hello", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeRejected, "rejected", td.RandHeight()) td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusUnknown) }) t.Run("Receiving HelloAck message from unknown peer", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeOK, "ok", td.RandHeight()) td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusUnknown) }) } func TestHandlerHelloAckHandshaking(t *testing.T) { td := setup(t, nil) t.Run("Unknown Direction", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeOK, "ok", td.RandHeight()) td.connectPeer(pid, lp2pnetwork.DirUnknown, false) td.receivingNewMessage(td.sync, msg, pid) td.shouldNotPublishAnyMessage(t) }) t.Run("Inbound Direction, Outbound Hello Not Sent", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeOK, "ok", td.RandHeight()) td.connectPeer(pid, lp2pnetwork.DirInbound, false) td.receivingNewMessage(td.sync, msg, pid) td.shouldNotPublishAnyMessage(t) td.checkPeerStatus(t, pid, status.StatusConnected) }) t.Run("Outbound Direction, Outbound Hello Not Sent", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeOK, "ok", td.RandHeight()) td.connectPeer(pid, lp2pnetwork.DirOutbound, false) td.receivingNewMessage(td.sync, msg, pid) td.shouldNotPublishAnyMessage(t) td.checkPeerStatus(t, pid, status.StatusConnected) }) t.Run("Inbound Direction, Outbound Hello Sent", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeOK, "ok", td.RandHeight()) td.connectPeer(pid, lp2pnetwork.DirInbound, true) td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusKnown) }) t.Run("Outbound Direction, Outbound Hello Sent", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewHelloAckMessage(message.ResponseCodeOK, "ok", td.RandHeight()) td.connectPeer(pid, lp2pnetwork.DirOutbound, true) td.receivingNewMessage(td.sync, msg, pid) td.shouldNotPublishAnyMessage(t) td.checkPeerStatus(t, pid, status.StatusKnown) }) } ================================================ FILE: sync/handler_hello_test.go ================================================ package sync import ( "testing" "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/version" "github.com/stretchr/testify/assert" ) func (td *testData) validHelloMessage() *message.HelloMessage { valKey1 := td.RandValKey() valKey2 := td.RandValKey() msg := message.NewHelloMessage(td.RandPeerID(), td.RandString(12), service.New(service.FullNode), td.RandHeight(), td.RandHash(), td.state.Genesis().Hash()) msg.Sign([]*bls.ValidatorKey{valKey1, valKey2}) return msg } func (td *testData) connectPeer(pid peer.ID, direction lp2pnetwork.Direction, outboundHelloSent bool) { td.sync.peerSet.UpdateAddress(pid, "some-address", direction) td.sync.peerSet.UpdateStatus(pid, status.StatusConnected) td.sync.peerSet.UpdateOutboundHelloSent(pid, outboundHelloSent) } func TestHandlerHelloParsingMessages(t *testing.T) { td := setup(t, nil) td.state.CommitTestBlocks(21) t.Run("Receiving Hello message from a peer. Genesis hash is wrong.", func(t *testing.T) { msg := td.validHelloMessage() msg.GenesisHash = td.RandHash() td.receivingNewMessage(td.sync, msg, msg.PeerID) td.checkPeerStatus(t, msg.PeerID, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Receiving a Hello message from a peer. The time difference is greater than or equal to -10", func(t *testing.T) { msg := td.validHelloMessage() msg.MyTimeUnixMilli = msg.MyTime().Add(-10 * time.Second).UnixMilli() td.receivingNewMessage(td.sync, msg, msg.PeerID) td.checkPeerStatus(t, msg.PeerID, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Receiving Hello message from a peer. Difference is less or equal than 20 seconds.", func(t *testing.T) { msg := td.validHelloMessage() msg.MyTimeUnixMilli = msg.MyTime().Add(20 * time.Second).UnixMilli() td.receivingNewMessage(td.sync, msg, msg.PeerID) td.checkPeerStatus(t, msg.PeerID, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Non supporting version", func(t *testing.T) { msg := td.validHelloMessage() nodeAgent := version.NodeAgent nodeAgent.Version = version.Version{ Major: 1, Minor: 8, Patch: 0, } msg.Agent = nodeAgent.String() td.receivingNewMessage(td.sync, msg, msg.PeerID) td.checkPeerStatus(t, msg.PeerID, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Invalid agent", func(t *testing.T) { msg := td.validHelloMessage() msg.Agent = "invalid-agent" td.receivingNewMessage(td.sync, msg, msg.PeerID) td.checkPeerStatus(t, msg.PeerID, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Outdated protocol version", func(t *testing.T) { msg := td.validHelloMessage() nodeAgent := version.NodeAgent nodeAgent.ProtocolVersion = protocol.ProtocolVersionLatest - 1 msg.Agent = nodeAgent.String() td.sync.peerSet.UpdateStatus(msg.PeerID, status.StatusConnected) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.checkPeerStatus(t, msg.PeerID, status.StatusConnected) td.shouldNotPublishAnyMessage(t) }) t.Run("Receiving Hello message from a peer. It should be acknowledged and updates the peer info", func(t *testing.T) { msg := td.validHelloMessage() td.sync.peerSet.UpdateAddress(msg.PeerID, "some-address", lp2pnetwork.DirInbound) td.sync.peerSet.UpdateStatus(msg.PeerID, status.StatusConnected) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.shouldPublishMessageWithThisType(t, message.TypeHello) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) assert.Equal(t, message.ResponseCodeOK, bdl.Message.(*message.HelloAckMessage).ResponseCode) // Check if the peer info is updated peer := td.sync.peerSet.GetPeer(msg.PeerID) assert.Equal(t, status.StatusConnected, peer.Status) assert.Equal(t, version.NodeAgent.String(), peer.Agent) assert.Equal(t, msg.Moniker, peer.Moniker) assert.Equal(t, msg.PublicKeys, peer.ConsensusKeys) assert.Equal(t, msg.PeerID, peer.PeerID) assert.Equal(t, msg.Height, peer.Height) assert.True(t, peer.IsFullNode()) }) } func TestHandlerHelloHandshaking(t *testing.T) { td := setup(t, nil) t.Run("Unknown Direction", func(t *testing.T) { msg := td.validHelloMessage() td.connectPeer(msg.PeerID, lp2pnetwork.DirUnknown, false) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.shouldNotPublishAnyMessage(t) }) t.Run("Inbound Direction, Outbound Hello Not Sent", func(t *testing.T) { msg := td.validHelloMessage() td.connectPeer(msg.PeerID, lp2pnetwork.DirInbound, false) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.shouldPublishMessageWithThisType(t, message.TypeHello) td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) td.checkPeerStatus(t, msg.PeerID, status.StatusConnected) }) t.Run("Outbound Direction, Outbound Hello Not Sent", func(t *testing.T) { msg := td.validHelloMessage() td.connectPeer(msg.PeerID, lp2pnetwork.DirOutbound, false) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.shouldNotPublishAnyMessage(t) td.checkPeerStatus(t, msg.PeerID, status.StatusConnected) }) t.Run("Inbound Direction, Outbound Hello Sent", func(t *testing.T) { msg := td.validHelloMessage() td.connectPeer(msg.PeerID, lp2pnetwork.DirInbound, true) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.shouldNotPublishAnyMessage(t) td.checkPeerStatus(t, msg.PeerID, status.StatusConnected) }) t.Run("Outbound Direction, Outbound Hello Sent", func(t *testing.T) { msg := td.validHelloMessage() td.connectPeer(msg.PeerID, lp2pnetwork.DirOutbound, true) td.receivingNewMessage(td.sync, msg, msg.PeerID) td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) td.checkPeerStatus(t, msg.PeerID, status.StatusKnown) }) } ================================================ FILE: sync/handler_proposal.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/types/protocol" ) type proposalHandler struct { *synchronizer } func newProposalHandler(sync *synchronizer) messageHandler { return &proposalHandler{ sync, } } func (handler *proposalHandler) ParseMessage(m message.Message, _ peer.ID) { msg := m.(*message.ProposalMessage) handler.logger.Trace("parsing Proposal message", "msg", msg) handler.getConsMgr().SetProposal(msg.Proposal) // TODO: This condition can be removed in future releases. // This helps to support old nodes that don't specify their protocol version in proposal. if msg.ProtocolVersion != protocol.ProtocolVersionUnknown { handler.state.UpdateValidatorProtocolVersion( msg.Proposal.Block().Header().ProposerAddress(), msg.ProtocolVersion, ) } } func (*proposalHandler) PrepareBundle(m message.Message) *bundle.Bundle { return bundle.NewBundle(m) } ================================================ FILE: sync/handler_proposal_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestHandlerProposalParsingMessages(t *testing.T) { td := setup(t, nil) t.Run("Set proposal for consensus", func(t *testing.T) { consensusHeight := td.state.LastBlockHeight() + 1 prop := td.GenerateTestProposal(consensusHeight, 0) msg := message.NewProposalMessage(prop) pid := td.RandPeerID() td.receivingNewMessage(td.sync, msg, pid) assert.Equal(t, prop, td.sync.getConsMgr().Proposal()) }) t.Run("Update protocol version of the proposer", func(t *testing.T) { consensusHeight := td.state.LastBlockHeight() + 1 valKey := td.RandValKey() val := td.GenerateTestValidator(testsuite.ValidatorWithPublicKey(valKey.PublicKey())) td.state.TestStore.UpdateValidator(val) prop := td.GenerateTestProposal(consensusHeight, 0, testsuite.ProposalWithKey(valKey)) msg := message.NewProposalMessage(prop) pid := td.RandPeerID() td.receivingNewMessage(td.sync, msg, pid) assert.Equal(t, protocol.ProtocolVersionLatest, val.ProtocolVersion()) }) } ================================================ FILE: sync/handler_query_proposal.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" ) type queryProposalHandler struct { *synchronizer } func newQueryProposalHandler(sync *synchronizer) messageHandler { return &queryProposalHandler{ sync, } } func (handler *queryProposalHandler) ParseMessage(m message.Message, _ peer.ID) { msg := m.(*message.QueryProposalMessage) handler.logger.Trace("parsing QueryProposal message", "msg", msg) prop := handler.getConsMgr().HandleQueryProposal(msg.Height, msg.Round) if prop != nil { response := message.NewProposalMessage(prop) handler.broadcast(response) } } func (*queryProposalHandler) PrepareBundle(m message.Message) *bundle.Bundle { bdl := bundle.NewBundle(m) return bdl } ================================================ FILE: sync/handler_query_proposal_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/stretchr/testify/assert" ) func TestHandlerQueryProposalParsingMessages(t *testing.T) { td := setup(t, nil) consHeight, consRound := td.sync.getConsMgr().HeightRound() t.Run("doesn't have the proposal", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewQueryProposalMessage(consHeight, consRound, td.RandValAddress()) td.receivingNewMessage(td.sync, msg, pid) td.shouldNotPublishAnyMessage(t) }) t.Run("should respond to the query proposal message", func(t *testing.T) { prop := td.GenerateTestProposal(consHeight, 0) pid := td.RandPeerID() td.sync.getConsMgr().SetProposal(prop) msg := message.NewQueryProposalMessage(consHeight, consRound, td.RandValAddress()) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeProposal) assert.Equal(t, prop.Hash(), bdl.Message.(*message.ProposalMessage).Proposal.Hash()) }) } func TestHandlerQueryProposalBroadcastingMessages(t *testing.T) { td := setup(t, nil) consHeight, consRound := td.sync.getConsMgr().HeightRound() msg := message.NewQueryProposalMessage(consHeight, consRound, td.RandValAddress()) td.sync.broadcast(msg) td.shouldPublishMessageWithThisType(t, message.TypeQueryProposal) } ================================================ FILE: sync/handler_query_votes.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" ) type queryVoteHandler struct { *synchronizer } func newQueryVoteHandler(sync *synchronizer) messageHandler { return &queryVoteHandler{ sync, } } func (handler *queryVoteHandler) ParseMessage(m message.Message, _ peer.ID) { msg := m.(*message.QueryVoteMessage) handler.logger.Trace("parsing QueryVote message", "msg", msg) v := handler.getConsMgr().HandleQueryVote(msg.Height, msg.Round) if v != nil { response := message.NewVoteMessage(v) handler.broadcast(response) } } func (*queryVoteHandler) PrepareBundle(m message.Message) *bundle.Bundle { bdl := bundle.NewBundle(m) return bdl } ================================================ FILE: sync/handler_query_votes_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/stretchr/testify/assert" ) func TestHandlerQueryVoteParsingMessages(t *testing.T) { td := setup(t, nil) consHeight, consRound := td.sync.getConsMgr().HeightRound() t.Run("doesn't have any votes", func(t *testing.T) { pid := td.RandPeerID() msg := message.NewQueryVoteMessage(consHeight, consRound, td.RandValAddress()) td.receivingNewMessage(td.sync, msg, pid) td.shouldNotPublishAnyMessage(t) }) t.Run("should respond to the query votes message", func(t *testing.T) { vote, _ := td.GenerateTestPrecommitVote(consHeight, consRound) td.sync.getConsMgr().AddVote(vote) pid := td.RandPeerID() msg := message.NewQueryVoteMessage(consHeight, consRound, td.RandValAddress()) td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeVote) assert.Equal(t, vote.Hash(), bdl.Message.(*message.VoteMessage).Vote.Hash()) }) } func TestHandlerQueryVoteBroadcastingMessages(t *testing.T) { td := setup(t, nil) consensusHeight := td.state.LastBlockHeight() + 1 msg := message.NewQueryVoteMessage(consensusHeight, 1, td.RandValAddress()) td.sync.broadcast(msg) td.shouldPublishMessageWithThisType(t, message.TypeQueryVote) } ================================================ FILE: sync/handler_transactions.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" ) type transactionsHandler struct { *synchronizer } func newTransactionsHandler(sync *synchronizer) messageHandler { return &transactionsHandler{ sync, } } func (handler *transactionsHandler) ParseMessage(m message.Message, _ peer.ID) { msg := m.(*message.TransactionsMessage) handler.logger.Trace("parsing Transactions message", "msg", msg) for _, trx := range msg.Transactions { if err := handler.state.AddPendingTx(trx); err != nil { handler.logger.Debug("cannot append transaction", "tx", trx, "error", err) } } } func (*transactionsHandler) PrepareBundle(m message.Message) *bundle.Bundle { return bundle.NewBundle(m) } ================================================ FILE: sync/handler_transactions_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types/tx" ) func TestHandlerTransactionsParsingMessages(t *testing.T) { td := setup(t, nil) t.Run("Parsing transactions message", func(*testing.T) { trx1 := td.GenerateTestBondTx() msg := message.NewTransactionsMessage([]*tx.Tx{trx1}) pid := td.RandPeerID() td.state.MockTxPool.EXPECT().AppendTx(trx1).Return(nil).Times(1) td.receivingNewMessage(td.sync, msg, pid) }) } func TestHandlerTransactionsBroadcastingMessages(t *testing.T) { td := setup(t, nil) trx1 := td.GenerateTestBondTx() msg := message.NewTransactionsMessage([]*tx.Tx{trx1}) td.sync.broadcast(msg) td.shouldPublishMessageWithThisType(t, message.TypeTransaction) } ================================================ FILE: sync/handler_vote.go ================================================ package sync import ( "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" ) type voteHandler struct { *synchronizer } func newVoteHandler(sync *synchronizer) messageHandler { return &voteHandler{ sync, } } func (handler *voteHandler) ParseMessage(m message.Message, _ peer.ID) { msg := m.(*message.VoteMessage) handler.logger.Trace("parsing Vote message", "msg", msg) handler.getConsMgr().AddVote(msg.Vote) } func (*voteHandler) PrepareBundle(m message.Message) *bundle.Bundle { return bundle.NewBundle(m) } ================================================ FILE: sync/handler_vote_test.go ================================================ package sync import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/stretchr/testify/assert" ) func TestHandlerVoteParsingMessages(t *testing.T) { td := setup(t, nil) t.Run("Parsing vote message", func(t *testing.T) { v, _ := td.GenerateTestPrecommitVote(1, 0) msg := message.NewVoteMessage(v) pid := td.RandPeerID() td.receivingNewMessage(td.sync, msg, pid) assert.Contains(t, td.consMocks[0].AllVotes(), v) }) } ================================================ FILE: sync/interface.go ================================================ package sync import ( "time" "github.com/pactus-project/pactus/sync/peerset" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/service" ) type Synchronizer interface { Start() error Stop() Moniker() string SelfID() peer.ID PeerSet() *peerset.PeerSet Services() service.Services ClockOffset() (time.Duration, error) IsClockOutOfSync() bool } ================================================ FILE: sync/mock.go ================================================ package sync import ( "time" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sync/peerset" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/version" ) var _ Synchronizer = &MockSync{} // MockSync is a mock implementation of the Synchronizer interface for testing. type MockSync struct { TestID peer.ID TestPeerSet *peerset.PeerSet TestServices service.Services } func MockingSync(ts *testsuite.TestSuite) *MockSync { peerSet := peerset.NewPeerSet(1 * time.Second) pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() peerSet.UpdateInfo( pid1, "test-peer-1", version.NodeAgent.String(), []*bls.PublicKey{pub1}, service.New(service.FullNode)) peerSet.UpdateHeight(pid1, ts.RandHeight(), ts.RandHash()) peerSet.UpdateInfo( pid2, "test-peer-2", version.NodeAgent.String(), []*bls.PublicKey{pub2}, service.New(service.None)) peerSet.UpdateHeight(pid1, ts.RandHeight(), ts.RandHash()) services := service.New() return &MockSync{ TestID: ts.RandPeerID(), TestPeerSet: peerSet, TestServices: services, } } func (*MockSync) Start() error { return nil } func (*MockSync) Stop() { } func (m *MockSync) SelfID() peer.ID { return m.TestID } func (*MockSync) Moniker() string { return "test-moniker" } func (m *MockSync) PeerSet() *peerset.PeerSet { return m.TestPeerSet } func (m *MockSync) Services() service.Services { return m.TestServices } func (*MockSync) ClockOffset() (time.Duration, error) { return 1 * time.Second, nil } func (*MockSync) IsClockOutOfSync() bool { return false } ================================================ FILE: sync/peerset/peer/metric/metric.go ================================================ package metric import "github.com/pactus-project/pactus/sync/bundle/message" type Counter struct { Bytes int64 Bundles int64 } type Metric struct { TotalInvalid Counter TotalSent Counter TotalReceived Counter MessageSent map[message.Type]*Counter MessageReceived map[message.Type]*Counter } func NewMetric() Metric { return Metric{ MessageSent: make(map[message.Type]*Counter), MessageReceived: make(map[message.Type]*Counter), } } func (m *Metric) UpdateSentMetric(msgType message.Type, bytes int64) { m.TotalSent.Bundles++ m.TotalSent.Bytes += bytes _, ok := m.MessageSent[msgType] if !ok { m.MessageSent[msgType] = &Counter{} } m.MessageSent[msgType].Bundles++ m.MessageSent[msgType].Bytes += bytes } func (m *Metric) UpdateReceivedMetric(msgType message.Type, bytes int64) { m.TotalReceived.Bundles++ m.TotalReceived.Bytes += bytes _, ok := m.MessageReceived[msgType] if !ok { m.MessageReceived[msgType] = &Counter{} } m.MessageReceived[msgType].Bundles++ m.MessageReceived[msgType].Bytes += bytes } func (m *Metric) UpdateInvalidMetric(bytes int64) { m.TotalInvalid.Bundles++ m.TotalInvalid.Bytes += bytes } ================================================ FILE: sync/peerset/peer/metric/metric_test.go ================================================ package metric import ( "testing" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/stretchr/testify/assert" ) func TestUpdateSentMetric(t *testing.T) { metric := NewMetric() testMsgType := message.Type(1) metric.UpdateSentMetric(testMsgType, 100) assert.Equal(t, int64(1), metric.TotalSent.Bundles) assert.Equal(t, int64(100), metric.TotalSent.Bytes) assert.NotNil(t, metric.MessageSent[testMsgType]) assert.Equal(t, int64(1), metric.MessageSent[testMsgType].Bundles) assert.Equal(t, int64(100), metric.MessageSent[testMsgType].Bytes) } func TestUpdateReceivedMetric(t *testing.T) { metric := NewMetric() testMsgType := message.Type(2) metric.UpdateReceivedMetric(testMsgType, 200) assert.Equal(t, int64(1), metric.TotalReceived.Bundles) assert.Equal(t, int64(200), metric.TotalReceived.Bytes) assert.NotNil(t, metric.MessageReceived[testMsgType]) assert.Equal(t, int64(1), metric.MessageReceived[testMsgType].Bundles) assert.Equal(t, int64(200), metric.MessageReceived[testMsgType].Bytes) } func TestUpdateInvalidMetric(t *testing.T) { metric := NewMetric() metric.UpdateInvalidMetric(123) assert.Equal(t, int64(1), metric.TotalInvalid.Bundles) assert.Equal(t, int64(123), metric.TotalInvalid.Bytes) } ================================================ FILE: sync/peerset/peer/peer.go ================================================ package peer import ( "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sync/peerset/peer/metric" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/types" ) type ID = lp2ppeer.ID type Peer struct { Status status.Status Moniker string Agent string Address string Direction lp2pnetwork.Direction Protocols []string PeerID ID ConsensusKeys []*bls.PublicKey Services service.Services LastSent time.Time LastReceived time.Time LastBlockHash hash.Hash Height types.Height TotalSessions int CompletedSessions int Metric metric.Metric // OutboundHelloSent tracks whether we've sent the initial hello message for outbound connections OutboundHelloSent bool } func NewPeer(peerID ID) *Peer { return &Peer{ ConsensusKeys: make([]*bls.PublicKey, 0), Status: status.StatusUnknown, PeerID: peerID, Metric: metric.NewMetric(), Protocols: make([]string, 0), } } func (p *Peer) IsFullNode() bool { return p.Services.IsFullNode() } func (p *Peer) DownloadScore() int { return (p.CompletedSessions + 1) * 100 / (p.TotalSessions + 1) } ================================================ FILE: sync/peerset/peer/peer_test.go ================================================ package peer import ( "testing" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/stretchr/testify/assert" ) func TestPeerStatus(t *testing.T) { tests := []struct { status status.Status isDisconnected bool isBanned bool isConnected bool isKnown bool isKnownOrConnected bool }{ {status: status.StatusBanned, isBanned: true}, {status: status.StatusDisconnected, isDisconnected: true}, {status: status.StatusConnected, isConnected: true, isKnownOrConnected: true}, {status: status.StatusKnown, isKnown: true, isKnownOrConnected: true}, } for _, tt := range tests { peer := NewPeer("test") peer.Status = tt.status assert.Equal(t, tt.isDisconnected, peer.Status.IsDisconnected()) assert.Equal(t, tt.isBanned, peer.Status.IsBanned()) assert.Equal(t, tt.isConnected, peer.Status.IsConnected()) assert.Equal(t, tt.isKnown, peer.Status.IsKnown()) assert.Equal(t, tt.isKnownOrConnected, peer.Status.IsConnectedOrKnown()) } } func TestIsFullNode(t *testing.T) { p1 := NewPeer("peer-1") p2 := NewPeer("peer-1") p1.Services = service.New(service.PrunedNode) p2.Services = service.New(service.FullNode) assert.False(t, p1.IsFullNode()) assert.True(t, p2.IsFullNode()) } func TestDownloadScore(t *testing.T) { tests := []struct { totalSession int completedSession int expectedScore int }{ {0, 0, 100}, {1, 1, 100}, {1, 0, 50}, {2, 0, 33}, {3, 0, 25}, {5, 4, 83}, {6, 5, 85}, {7, 6, 87}, } for no, tt := range tests { peer := NewPeer("test") peer.TotalSessions = tt.totalSession peer.CompletedSessions = tt.completedSession score := peer.DownloadScore() assert.Equal(t, tt.expectedScore, score, "Test %v failed. expected score %d, got %d", no+1, tt.expectedScore, score) } } ================================================ FILE: sync/peerset/peer/service/services.go ================================================ package service import ( "fmt" "github.com/pactus-project/pactus/util" ) type ( Services int Service int ) const ( None Service = 0x00 // FullNode indicates that the node has a full blockchain history. FullNode Service = 0x01 // PrunedNode indicates that the node has a pruned blockchain history. PrunedNode Service = 0x02 ) func New(flags ...Service) Services { s := None for _, f := range flags { s = util.SetFlag(s, f) } return Services(s) } func (s *Services) Append(flag Service) { *s = util.SetFlag(*s, Services(flag)) } func (s Services) String() string { services := "" flags := s if util.IsFlagSet(flags, Services(FullNode)) { services += "FULL | " flags = util.UnsetFlag(flags, Services(FullNode)) } if util.IsFlagSet(flags, Services(PrunedNode)) { services += "PRUNED | " flags = util.UnsetFlag(flags, Services(PrunedNode)) } if flags != 0 { services += fmt.Sprintf("%d", flags) } else if services != "" { services = services[:len(services)-3] } return services } func (s Services) IsFullNode() bool { return util.IsFlagSet(s, Services(FullNode)) } func (s Services) IsPrunedNode() bool { return util.IsFlagSet(s, Services(PrunedNode)) } ================================================ FILE: sync/peerset/peer/service/services_test.go ================================================ package service import ( "testing" "github.com/stretchr/testify/assert" ) func TestServicesString(t *testing.T) { assert.Empty(t, New(None).String()) assert.Equal(t, "FULL", New(FullNode).String()) assert.Equal(t, "PRUNED", New(PrunedNode).String()) assert.Equal(t, "FULL | PRUNED", New(FullNode, PrunedNode).String()) assert.Equal(t, "FULL | 4", New(5).String()) assert.Equal(t, "PRUNED | 4", New(6).String()) } func TestAppend(t *testing.T) { services := New(FullNode) assert.True(t, services.IsFullNode()) assert.False(t, services.IsPrunedNode()) services.Append(PrunedNode) assert.True(t, services.IsFullNode()) assert.True(t, services.IsPrunedNode()) } ================================================ FILE: sync/peerset/peer/status/status.go ================================================ package status type Status int const ( // The Status here, tells us the status os the connection. StatusBanned = Status(-1) StatusUnknown = Status(0) StatusDisconnected = Status(1) StatusConnected = Status(2) StatusKnown = Status(3) ) func (s Status) String() string { switch s { case StatusBanned: return "banned" case StatusUnknown: return "unknown" case StatusDisconnected: return "disconnected" case StatusConnected: return "connected" case StatusKnown: return "known" } return "invalid" } func (s Status) IsUnknown() bool { return s == StatusUnknown } func (s Status) IsKnown() bool { return s == StatusKnown } func (s Status) IsDisconnected() bool { return s == StatusDisconnected } func (s Status) IsConnected() bool { return s == StatusConnected } func (s Status) IsConnectedOrKnown() bool { return s == StatusConnected || s == StatusKnown } func (s Status) IsBanned() bool { return s == StatusBanned } ================================================ FILE: sync/peerset/peer_set.go ================================================ package peerset import ( "sync" "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/metric" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/sync/peerset/session" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util" ) type PeerSet struct { lk sync.RWMutex peers map[peer.ID]*peer.Peer sessionManager *session.Manager startedAt time.Time metric metric.Metric } // NewPeerSet constructs a new PeerSet for managing peer information. func NewPeerSet(sessionTimeout time.Duration) *PeerSet { return &PeerSet{ peers: make(map[peer.ID]*peer.Peer), sessionManager: session.NewManager(sessionTimeout), metric: metric.NewMetric(), startedAt: time.Now(), } } // OpenSession opens a new session for downloading blocks and returns the session ID. func (ps *PeerSet) OpenSession(pid peer.ID, from types.Height, count uint32) int { ps.lk.Lock() defer ps.lk.Unlock() ssn := ps.sessionManager.OpenSession(pid, from, count) p := ps.findOrCreatePeer(pid) p.TotalSessions++ return ssn.SessionID } // NumberOfSessions returns the total number of sessions. func (ps *PeerSet) NumberOfSessions() int { ps.lk.Lock() defer ps.lk.Unlock() return ps.sessionManager.NumberOfSessions() } // HasOpenSession checks if the specified peer has an open session for downloading blocks. // Note that a peer may have more than one session. func (ps *PeerSet) HasOpenSession(pid peer.ID) bool { ps.lk.RLock() defer ps.lk.RUnlock() return ps.sessionManager.HasOpenSession(pid) } func (ps *PeerSet) SessionStats() session.Stats { ps.lk.RLock() defer ps.lk.RUnlock() return ps.sessionManager.Stats() } func (ps *PeerSet) HasAnyOpenSession() bool { ps.lk.RLock() defer ps.lk.RUnlock() return ps.sessionManager.HasAnyOpenSession() } func (ps *PeerSet) UpdateSessionLastActivity(sid int) { ps.lk.Lock() defer ps.lk.Unlock() ps.sessionManager.UpdateSessionLastActivity(sid) } func (ps *PeerSet) SetExpiredSessionsAsUncompleted() { ps.lk.Lock() defer ps.lk.Unlock() ps.sessionManager.SetExpiredSessionsAsUncompleted() } func (ps *PeerSet) SetSessionUncompleted(sid int) { ps.lk.Lock() defer ps.lk.Unlock() ps.sessionManager.SetSessionUncompleted(sid) } func (ps *PeerSet) SetSessionCompleted(sid int) { ps.lk.Lock() defer ps.lk.Unlock() ssn := ps.sessionManager.SetSessionCompleted(sid) if ssn != nil { p := ps.findOrCreatePeer(ssn.PeerID) p.CompletedSessions++ } } func (ps *PeerSet) RemoveAllSessions() { ps.lk.Lock() defer ps.lk.Unlock() ps.sessionManager.RemoveAllSessions() } func (ps *PeerSet) Len() int { ps.lk.RLock() defer ps.lk.RUnlock() return len(ps.peers) } func (ps *PeerSet) RemovePeer(pid peer.ID) { ps.lk.Lock() defer ps.lk.Unlock() delete(ps.peers, pid) } // GetPeer finds a peer by id and returns a copy of the peer object. func (ps *PeerSet) GetPeer(pid peer.ID) *peer.Peer { ps.lk.RLock() defer ps.lk.RUnlock() return ps.findPeer(pid) } // HasPeer checks if a peer with the given id exists in the set. func (ps *PeerSet) HasPeer(pid peer.ID) bool { ps.lk.RLock() defer ps.lk.RUnlock() _, ok := ps.peers[pid] return ok } func (ps *PeerSet) findPeer(pid peer.ID) *peer.Peer { if p, ok := ps.peers[pid]; ok { return p } return nil } // FindOrCreatePeer tries to find a peer with the given pid. // If not found, it creates a new peer and assigns the pid to it. func (ps *PeerSet) findOrCreatePeer(pid peer.ID) *peer.Peer { per := ps.findPeer(pid) if per == nil { per = peer.NewPeer(pid) ps.peers[pid] = per } return per } // GetPeerStatus finds a peer by id and returns the status of the Peer. func (ps *PeerSet) GetPeerStatus(pid peer.ID) status.Status { ps.lk.RLock() defer ps.lk.RUnlock() p := ps.findPeer(pid) if p != nil { return p.Status } return status.StatusUnknown } func (ps *PeerSet) UpdateInfo( pid peer.ID, moniker string, agent string, consKeys []*bls.PublicKey, services service.Services, ) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.Moniker = moniker p.Agent = agent p.ConsensusKeys = consKeys p.Services = services } func (ps *PeerSet) UpdateHeight(pid peer.ID, height types.Height, lastBlockHash hash.Hash) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.Height = height p.LastBlockHash = lastBlockHash } func (ps *PeerSet) UpdateAddress(pid peer.ID, addr string, direction lp2pnetwork.Direction) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.Address = addr p.Direction = direction } func (ps *PeerSet) UpdateOutboundHelloSent(pid peer.ID, sent bool) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.OutboundHelloSent = sent } func (ps *PeerSet) UpdateStatus(pid peer.ID, status status.Status) { ps.lk.Lock() defer ps.lk.Unlock() peer := ps.findOrCreatePeer(pid) // Don't update the status if peer is banned (unless status is disconnected). // This helps banned peers to recover, like fixing their system time, etc. if peer.Status.IsBanned() && !status.IsDisconnected() { return } // Don't change status to connected if peer is known already if peer.Status.IsKnown() && status.IsConnected() { return } peer.Status = status if status.IsDisconnected() { peer.OutboundHelloSent = false for _, ssn := range ps.sessionManager.Sessions() { if ssn.PeerID == pid { ssn.Status = session.Uncompleted } } } } func (ps *PeerSet) UpdateProtocols(pid peer.ID, protocols []string) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.Protocols = protocols } func (ps *PeerSet) UpdateLastSent(pid peer.ID) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.LastSent = time.Now() } func (ps *PeerSet) UpdateLastReceived(pid peer.ID) { ps.lk.Lock() defer ps.lk.Unlock() p := ps.findOrCreatePeer(pid) p.LastReceived = time.Now() } func (ps *PeerSet) UpdateInvalidMetric(pid peer.ID, bytes int64) { ps.lk.Lock() defer ps.lk.Unlock() ps.metric.UpdateInvalidMetric(bytes) p := ps.findOrCreatePeer(pid) p.Metric.UpdateInvalidMetric(bytes) } func (ps *PeerSet) UpdateReceivedMetric(pid peer.ID, msgType message.Type, bytes int64) { ps.lk.Lock() defer ps.lk.Unlock() ps.metric.UpdateReceivedMetric(msgType, bytes) p := ps.findOrCreatePeer(pid) p.Metric.UpdateReceivedMetric(msgType, bytes) } func (ps *PeerSet) UpdateSentMetric(pid *peer.ID, msgType message.Type, bytes int64) { ps.lk.Lock() defer ps.lk.Unlock() ps.metric.UpdateSentMetric(msgType, bytes) if pid != nil { p := ps.findOrCreatePeer(*pid) p.Metric.UpdateSentMetric(msgType, bytes) } } func (ps *PeerSet) StartedAt() time.Time { ps.lk.RLock() defer ps.lk.RUnlock() return ps.startedAt } func (ps *PeerSet) IteratePeers(consumer func(p *peer.Peer) (stop bool)) { ps.lk.RLock() defer ps.lk.RUnlock() for _, p := range ps.peers { stopped := consumer(p) if stopped { return } } } func (ps *PeerSet) Sessions() []*session.Session { ps.lk.RLock() defer ps.lk.RUnlock() return ps.sessionManager.Sessions() } func (ps *PeerSet) Metric() metric.Metric { ps.lk.RLock() defer ps.lk.RUnlock() return ps.metric } // GetRandomPeer selects a random peer from the peer set based on their download score. // Peers with higher score are more likely to be selected. func (ps *PeerSet) GetRandomPeer() *peer.Peer { ps.lk.RLock() defer ps.lk.RUnlock() type scoredPeer struct { peer *peer.Peer score int } // totalScore := 0 peers := make([]scoredPeer, 0, len(ps.peers)) for _, peer := range ps.peers { if !peer.Status.IsConnectedOrKnown() { continue } score := peer.DownloadScore() totalScore += score peers = append(peers, scoredPeer{ peer: peer, score: score, }) } if len(peers) == 0 { return nil } rnd := int(util.RandUint32(uint32(totalScore))) // Find the index where the random number falls for _, p := range peers { totalScore -= p.score if rnd >= totalScore { return p.peer } } panic("unreachable code") } ================================================ FILE: sync/peerset/peer_set_test.go ================================================ package peerset import ( "fmt" "testing" "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/sync/peerset/session" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func getSessionByID(ps *PeerSet, sid int) *session.Session { ssns := ps.Sessions() for _, ssn := range ssns { if ssn.SessionID == sid { return ssn } } return nil } func TestPeerSet(t *testing.T) { ts := testsuite.NewTestSuite(t) peerSet := NewPeerSet(time.Minute) pk11, _ := ts.RandBLSKeyPair() pk12, _ := ts.RandBLSKeyPair() pk21, _ := ts.RandBLSKeyPair() pk31, _ := ts.RandBLSKeyPair() pk32, _ := ts.RandBLSKeyPair() pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() pid3 := ts.RandPeerID() peerSet.UpdateInfo(pid1, "Moniker1", "Agent1", []*bls.PublicKey{pk11, pk12}, service.New(service.FullNode)) peerSet.UpdateInfo(pid2, "Moniker2", "Agent2", []*bls.PublicKey{pk21}, service.New(service.None)) peerSet.UpdateInfo(pid3, "Moniker3", "Agent3", []*bls.PublicKey{pk31, pk32}, service.New(service.FullNode)) t.Run("Testing Len", func(t *testing.T) { assert.Equal(t, 3, peerSet.Len()) }) t.Run("Testing Iterate peers", func(t *testing.T) { // Verify that the peer list contains the expected peers found := false peerSet.IteratePeers(func(p *peer.Peer) bool { if p.PeerID == pid2 { found = true return true } return false }) assert.True(t, found, "Peer with ID %s not found in the peer list", pid2) }) t.Run("Testing hasPeer", func(t *testing.T) { assert.True(t, peerSet.HasPeer(pid1)) assert.False(t, peerSet.HasPeer(ts.RandPeerID())) }) t.Run("Testing GetPeer", func(t *testing.T) { p := peerSet.GetPeer(pid2) assert.Equal(t, pid2, p.PeerID) assert.True(t, p.Status.IsUnknown()) p = peerSet.GetPeer(ts.RandPeerID()) assert.Nil(t, p) }) t.Run("Testing ConsensusKeys", func(t *testing.T) { p := peerSet.GetPeer(pid3) assert.Contains(t, p.ConsensusKeys, pk31) assert.Contains(t, p.ConsensusKeys, pk32) }) t.Run("Testing counters", func(t *testing.T) { peerSet.UpdateInvalidMetric(pid1, 123) peerSet.UpdateReceivedMetric(pid1, message.TypeBlocksResponse, 100) peerSet.UpdateReceivedMetric(pid1, message.TypeTransaction, 150) peerSet.UpdateSentMetric(nil, message.TypeBlocksRequest, 200) peerSet.UpdateSentMetric(&pid1, message.TypeBlocksRequest, 250) peer1 := peerSet.findPeer(pid1) assert.Equal(t, int64(1), peer1.Metric.TotalInvalid.Bundles) assert.Equal(t, int64(2), peer1.Metric.TotalReceived.Bundles) assert.Equal(t, int64(100), peer1.Metric.MessageReceived[message.TypeBlocksResponse].Bytes) assert.Equal(t, int64(150), peer1.Metric.MessageReceived[message.TypeTransaction].Bytes) assert.Equal(t, int64(250), peer1.Metric.MessageSent[message.TypeBlocksRequest].Bytes) peerSetMetric := peerSet.Metric() assert.Equal(t, int64(250), peerSetMetric.TotalReceived.Bytes) assert.Equal(t, int64(100), peerSetMetric.MessageReceived[message.TypeBlocksResponse].Bytes) assert.Equal(t, int64(150), peerSetMetric.MessageReceived[message.TypeTransaction].Bytes) assert.Equal(t, int64(450), peerSetMetric.TotalSent.Bytes) assert.Equal(t, int64(450), peerSetMetric.MessageSent[message.TypeBlocksRequest].Bytes) }) t.Run("Testing UpdateHeight", func(t *testing.T) { height := ts.RandHeight() h := ts.RandHash() peerSet.UpdateHeight(pid1, height, h) peer1 := peerSet.findPeer(pid1) assert.Equal(t, height, peer1.Height) assert.Equal(t, h, peer1.LastBlockHash) }) t.Run("Testing UpdateLastSent", func(t *testing.T) { now := time.Now() peerSet.UpdateLastSent(pid1) peer1 := peerSet.findPeer(pid1) assert.GreaterOrEqual(t, peer1.LastSent, now) }) t.Run("Testing UpdateLastReceived", func(t *testing.T) { now := time.Now() peerSet.UpdateLastReceived(pid1) peer1 := peerSet.findPeer(pid1) assert.GreaterOrEqual(t, peer1.LastReceived, now) }) t.Run("Testing StartedAt", func(t *testing.T) { assert.LessOrEqual(t, peerSet.StartedAt(), time.Now()) }) t.Run("Testing RemovePeer", func(t *testing.T) { peerSet.RemovePeer(ts.RandPeerID()) assert.Equal(t, 3, peerSet.Len()) peerSet.RemovePeer(pid2) assert.Equal(t, 2, peerSet.Len()) }) } func TestOpenSession(t *testing.T) { ts := testsuite.NewTestSuite(t) peerSet := NewPeerSet(time.Minute) pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() sid1 := peerSet.OpenSession(pid1, 100, 10) sid2 := peerSet.OpenSession(pid2, 110, 10) ssn1 := getSessionByID(peerSet, sid1) ssn2 := getSessionByID(peerSet, sid1) assert.NotNil(t, ssn1) assert.Equal(t, types.Height(100), ssn1.From) assert.Equal(t, types.Height(100), ssn2.From) assert.Equal(t, uint32(10), ssn1.Count) assert.Equal(t, uint32(10), ssn2.Count) assert.Equal(t, pid1, ssn1.PeerID) assert.Equal(t, session.Open, ssn1.Status) assert.LessOrEqual(t, ssn1.LastActivity, time.Now()) assert.Equal(t, 0, sid1) assert.Equal(t, 1, sid2) assert.True(t, peerSet.HasOpenSession(pid1)) assert.True(t, peerSet.HasOpenSession(pid2)) assert.False(t, peerSet.HasOpenSession(ts.RandPeerID())) assert.Equal(t, 2, peerSet.NumberOfSessions()) } func TestNumberOfSessions(t *testing.T) { peerSet := NewPeerSet(time.Minute) // Test when there are no open sessions assert.Equal(t, 0, peerSet.NumberOfSessions()) // Test when there are multiple open sessions peerSet.OpenSession("peer1", 100, 101) peerSet.OpenSession("peer2", 200, 201) peerSet.OpenSession("peer3", 300, 301) assert.Equal(t, 3, peerSet.NumberOfSessions()) } func TestHasAnyOpenSession(t *testing.T) { peerSet := NewPeerSet(time.Minute) // Test when there are no open sessions assert.False(t, peerSet.HasAnyOpenSession()) sid := peerSet.OpenSession("peer1", 100, 101) assert.True(t, peerSet.HasAnyOpenSession()) peerSet.SetSessionCompleted(sid) assert.False(t, peerSet.HasAnyOpenSession()) } func TestRemoveAllSessions(t *testing.T) { peerSet := NewPeerSet(time.Minute) _ = peerSet.OpenSession("peer1", 100, 101) _ = peerSet.OpenSession("peer2", 100, 101) _ = peerSet.OpenSession("peer3", 100, 101) peerSet.RemoveAllSessions() assert.Zero(t, peerSet.NumberOfSessions()) assert.False(t, peerSet.HasAnyOpenSession()) } func TestCompletedSession(t *testing.T) { peerSet := NewPeerSet(time.Minute) sid := peerSet.OpenSession("peer1", 100, 101) ssn := getSessionByID(peerSet, sid) assert.Equal(t, session.Open, ssn.Status) peerSet.SetSessionCompleted(sid) assert.Equal(t, 1, peerSet.NumberOfSessions()) assert.False(t, peerSet.HasAnyOpenSession()) assert.Equal(t, session.Completed, ssn.Status) } func TestUncompletedSession(t *testing.T) { peerSet := NewPeerSet(time.Minute) sid := peerSet.OpenSession("peer1", 100, 101) ssn := getSessionByID(peerSet, sid) assert.Equal(t, session.Open, ssn.Status) peerSet.SetSessionUncompleted(sid) assert.Equal(t, 1, peerSet.NumberOfSessions()) assert.False(t, peerSet.HasAnyOpenSession()) assert.Equal(t, session.Uncompleted, ssn.Status) } func TestExpireSessions(t *testing.T) { timeout := 100 * time.Millisecond peerSet := NewPeerSet(timeout) sid := peerSet.OpenSession("peer1", 100, 101) ssn := getSessionByID(peerSet, sid) time.Sleep(timeout) peerSet.SetExpiredSessionsAsUncompleted() assert.Equal(t, 1, peerSet.NumberOfSessions()) assert.False(t, peerSet.HasAnyOpenSession()) assert.Equal(t, session.Uncompleted, ssn.Status) } func TestGetRandomPeer(t *testing.T) { // We create 6 peers for testing: // // peer_1 has score 100 // peer_2 has score 83 // peer_3 has score 66 // peer_4 has score 50 // peer_5 has score 33 // peer_6 has score 16 peerSet := NewPeerSet(time.Minute) for index := 0; index < 6; index++ { pid := peer.ID(fmt.Sprintf("peer_%v", index+1)) peerSet.UpdateInfo(pid, fmt.Sprintf("Moniker_%v", index+1), "Agent1", nil, service.New()) peerSet.UpdateStatus(pid, status.StatusKnown) for r := 0; r < 5; r++ { sid := peerSet.OpenSession(pid, 0, 0) if r < 5-index { peerSet.SetSessionCompleted(sid) } } } // Now let's run TestGetRandomPeer for 1000 times hits := make(map[peer.ID]int) for i := 0; i < 1000; i++ { randomPeer := peerSet.GetRandomPeer() hits[randomPeer.PeerID]++ } assert.Greater(t, hits[peer.ID("peer_1")], hits[peer.ID("peer_3")]) assert.Greater(t, hits[peer.ID("peer_2")], hits[peer.ID("peer_4")]) assert.Greater(t, hits[peer.ID("peer_3")], hits[peer.ID("peer_5")]) assert.Greater(t, hits[peer.ID("peer_4")], hits[peer.ID("peer_6")]) } func TestGetRandomPeerConnected(t *testing.T) { peerSet := NewPeerSet(time.Minute) pidBanned := peer.ID("known") pidConnected := peer.ID("connected") pidDisconnected := peer.ID("disconnected") peerSet.UpdateInfo(pidBanned, "moniker", "agent", nil, service.New()) peerSet.UpdateInfo(pidConnected, "moniker", "agent", nil, service.New()) peerSet.UpdateInfo(pidDisconnected, "moniker", "agent", nil, service.New()) peerSet.UpdateStatus(pidBanned, status.StatusBanned) peerSet.UpdateStatus(pidConnected, status.StatusConnected) peerSet.UpdateStatus(pidDisconnected, status.StatusDisconnected) peer := peerSet.GetRandomPeer() assert.NotEqual(t, peer.PeerID, pidBanned) assert.NotEqual(t, peer.PeerID, pidDisconnected) assert.Equal(t, peer.PeerID, pidConnected) } func TestGetRandomPeerNoPeer(t *testing.T) { peerSet := NewPeerSet(time.Minute) randomPeer := peerSet.GetRandomPeer() assert.Nil(t, randomPeer) } func TestGetRandomPeerOnePeer(t *testing.T) { peerSet := NewPeerSet(time.Minute) pidAlice := peer.ID("alice") peerSet.UpdateInfo(pidAlice, "alice", "agent", nil, service.New()) peerSet.UpdateStatus(pidAlice, status.StatusKnown) randomPeer := peerSet.GetRandomPeer() assert.Equal(t, randomPeer.PeerID, pidAlice) } func TestUpdateAddress(t *testing.T) { peerSet := NewPeerSet(time.Minute) pid := peer.ID("peer1") addr := "pid-1-address" dir := lp2pnetwork.DirInbound peerSet.UpdateAddress(pid, addr, dir) p := peerSet.GetPeer(pid) assert.Equal(t, addr, p.Address) assert.Equal(t, dir, p.Direction) } func TestUpdateSessionLastActivity(t *testing.T) { peerSet := NewPeerSet(time.Minute) sid := peerSet.OpenSession("peer1", 100, 101) ssn := getSessionByID(peerSet, sid) activity1 := ssn.LastActivity time.Sleep(10 * time.Millisecond) peerSet.UpdateSessionLastActivity(sid) assert.Greater(t, ssn.LastActivity, activity1) } func TestUpdateProtocols(t *testing.T) { peerSet := NewPeerSet(time.Minute) pid := peer.ID("peer-1") protocols := []string{"protocol-1"} peerSet.UpdateProtocols(pid, protocols) p := peerSet.GetPeer(pid) assert.Equal(t, protocols, p.Protocols) } func TestUpdateOutboundHelloSent(t *testing.T) { peerSet := NewPeerSet(time.Minute) pid := peer.ID("peer1") peerSet.UpdateOutboundHelloSent(pid, true) p := peerSet.GetPeer(pid) assert.True(t, p.OutboundHelloSent) } func TestUpdateStatus(t *testing.T) { ts := testsuite.NewTestSuite(t) peerSet := NewPeerSet(time.Minute) t.Run("Status of Unknown peer", func(t *testing.T) { pid := ts.RandPeerID() assert.Equal(t, status.StatusUnknown, peerSet.GetPeerStatus(pid)) }) t.Run("UpdateStatus from Known to Banned", func(t *testing.T) { pid := ts.RandPeerID() peerSet.UpdateStatus(pid, status.StatusKnown) peerSet.UpdateStatus(pid, status.StatusBanned) assert.Equal(t, status.StatusBanned, peerSet.GetPeerStatus(pid)) }) t.Run("UpdateStatus from Known to Disconnected", func(t *testing.T) { pid := ts.RandPeerID() peerSet.UpdateStatus(pid, status.StatusKnown) peerSet.UpdateStatus(pid, status.StatusDisconnected) assert.Equal(t, status.StatusDisconnected, peerSet.GetPeerStatus(pid)) assert.False(t, peerSet.GetPeer(pid).OutboundHelloSent) }) t.Run("UpdateStatus from Known to Connected (should not change)", func(t *testing.T) { pid := ts.RandPeerID() peerSet.UpdateStatus(pid, status.StatusKnown) peerSet.UpdateStatus(pid, status.StatusConnected) assert.Equal(t, status.StatusKnown, peerSet.GetPeerStatus(pid)) }) t.Run("UpdateStatus from Banned to Disconnected (should change)", func(t *testing.T) { pid := ts.RandPeerID() peerSet.UpdateStatus(pid, status.StatusBanned) peerSet.UpdateStatus(pid, status.StatusDisconnected) assert.Equal(t, status.StatusDisconnected, peerSet.GetPeerStatus(pid)) }) t.Run("UpdateStatus from Banned to Connected", func(t *testing.T) { pid := ts.RandPeerID() peerSet.UpdateStatus(pid, status.StatusBanned) peerSet.UpdateStatus(pid, status.StatusConnected) assert.Equal(t, status.StatusBanned, peerSet.GetPeerStatus(pid)) }) t.Run("UpdateStatus from Banned to Known", func(t *testing.T) { pid := ts.RandPeerID() peerSet.UpdateStatus(pid, status.StatusBanned) peerSet.UpdateStatus(pid, status.StatusKnown) assert.Equal(t, status.StatusBanned, peerSet.GetPeerStatus(pid)) }) t.Run("Close Sessions On Disconnect", func(t *testing.T) { pid1 := ts.RandPeerID() pid2 := ts.RandPeerID() peerSet.OpenSession(pid1, 100, 10) peerSet.OpenSession(pid2, 110, 10) peerSet.UpdateStatus(pid1, status.StatusDisconnected) assert.False(t, peerSet.HasOpenSession(pid1)) assert.True(t, peerSet.HasOpenSession(pid2)) }) } ================================================ FILE: sync/peerset/session/manager.go ================================================ package session import ( "time" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/types" ) type Manager struct { sessionTimeout time.Duration sessions map[int]*Session nextSessionID int } func NewManager(sessionTimeout time.Duration) *Manager { return &Manager{ sessionTimeout: sessionTimeout, sessions: make(map[int]*Session), } } func (sm *Manager) Stats() Stats { total := len(sm.sessions) open := 0 completed := 0 unCompleted := 0 for _, ssn := range sm.sessions { switch ssn.Status { case Open: open++ case Completed: completed++ case Uncompleted: unCompleted++ } } return Stats{ Total: total, Open: open, Completed: completed, Uncompleted: unCompleted, } } func (sm *Manager) OpenSession(pid peer.ID, from types.Height, count uint32) *Session { ssn := NewSession(sm.nextSessionID, pid, from, count) sm.sessions[ssn.SessionID] = ssn sm.nextSessionID++ return ssn } func (sm *Manager) NumberOfSessions() int { return len(sm.sessions) } func (sm *Manager) HasOpenSession(pid peer.ID) bool { for _, ssn := range sm.sessions { if ssn.PeerID == pid && ssn.Status == Open { return true } } return false } func (sm *Manager) HasAnyOpenSession() bool { for _, ssn := range sm.sessions { if ssn.Status == Open { return true } } return false } func (sm *Manager) UpdateSessionLastActivity(sid int) { ssn := sm.sessions[sid] if ssn != nil { ssn.LastActivity = time.Now() } } func (sm *Manager) SetExpiredSessionsAsUncompleted() { for _, ssn := range sm.sessions { if sm.sessionTimeout < time.Since(ssn.LastActivity) { ssn.Status = Uncompleted } } } func (sm *Manager) SetSessionUncompleted(sid int) { ssn := sm.sessions[sid] if ssn != nil { ssn.Status = Uncompleted } } func (sm *Manager) SetSessionCompleted(sid int) *Session { ssn := sm.sessions[sid] if ssn != nil { ssn.Status = Completed } return ssn } func (sm *Manager) RemoveAllSessions() { sm.sessions = make(map[int]*Session) } func (sm *Manager) Sessions() []*Session { sessions := make([]*Session, 0, len(sm.sessions)) for _, ssn := range sm.sessions { sessions = append(sessions, ssn) } return sessions } ================================================ FILE: sync/peerset/session/session.go ================================================ package session import ( "time" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/types" ) type Status int const ( Open = Status(0) Completed = Status(2) Uncompleted = Status(1) ) type Session struct { SessionID int Status Status PeerID peer.ID From types.Height Count uint32 LastActivity time.Time } func NewSession(id int, peerID peer.ID, from types.Height, count uint32) *Session { return &Session{ SessionID: id, Status: Open, PeerID: peerID, From: from, Count: count, LastActivity: time.Now(), } } ================================================ FILE: sync/peerset/session/stats.go ================================================ package session import "fmt" type Stats struct { Total int Open int Completed int Uncompleted int } func (ss *Stats) String() string { return fmt.Sprintf("total: %v, open: %v, completed: %v, uncompleted: %v", ss.Total, ss.Open, ss.Completed, ss.Uncompleted) } ================================================ FILE: sync/sync.go ================================================ package sync import ( "context" "fmt" "time" "github.com/ezex-io/gopkg/pipeline" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/cache" "github.com/pactus-project/pactus/sync/firewall" "github.com/pactus-project/pactus/sync/peerset" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/sync/peerset/session" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/ntp" ) // IMPORTANT NOTES: // // 1. The Sync module is based on pulling instead of pushing. This means that the network // does not update a node (push); instead, a node should update itself (pull). // // 2. The Synchronizer should not have any locks to prevent deadlocks. All submodules, // such as state or consensus, should be thread-safe. type synchronizer struct { config *Config valKeys []*bls.ValidatorKey state state.Facade consV1Mgr consmgr.Manager consV2Mgr consmgr.Manager peerSet *peerset.PeerSet firewall *firewall.Firewall cache *cache.Cache handlers map[message.Type]messageHandler broadcastPipe pipeline.Pipeline[message.Message] networkPipe pipeline.Pipeline[network.Event] network network.Network logger *logger.SubLogger ntp *ntp.Checker } //nolint:revive // arguments can't be reduced. func NewSynchronizer( ctx context.Context, conf *Config, valKeys []*bls.ValidatorKey, state state.Facade, consV1Mgr consmgr.Manager, consV2Mgr consmgr.Manager, network network.Network, broadcastPipe pipeline.Pipeline[message.Message], networkPipe pipeline.Pipeline[network.Event], ) (Synchronizer, error) { sync := &synchronizer{ config: conf, valKeys: valKeys, state: state, consV1Mgr: consV1Mgr, consV2Mgr: consV2Mgr, network: network, broadcastPipe: broadcastPipe, networkPipe: networkPipe, ntp: ntp.NewNtpChecker(ctx), } sync.peerSet = peerset.NewPeerSet(conf.SessionTimeout()) sync.logger = logger.NewSubLogger("_sync", sync) fw, err := firewall.NewFirewall(conf.Firewall, network, sync.peerSet, state) if err != nil { return nil, err } sync.firewall = fw cacheSize := conf.CacheSize() ca, err := cache.NewCache(conf.CacheSize()) if err != nil { return nil, err } sync.cache = ca sync.logger.Info("cache setup", "size", cacheSize) handlers := make(map[message.Type]messageHandler) handlers[message.TypeHello] = newHelloHandler(sync) handlers[message.TypeHelloAck] = newHelloAckHandler(sync) handlers[message.TypeTransaction] = newTransactionsHandler(sync) handlers[message.TypeQueryProposal] = newQueryProposalHandler(sync) handlers[message.TypeProposal] = newProposalHandler(sync) handlers[message.TypeQueryVote] = newQueryVoteHandler(sync) handlers[message.TypeVote] = newVoteHandler(sync) handlers[message.TypeBlockAnnounce] = newBlockAnnounceHandler(sync) handlers[message.TypeBlocksRequest] = newBlocksRequestHandler(sync) handlers[message.TypeBlocksResponse] = newBlocksResponseHandler(sync) sync.handlers = handlers sync.networkPipe.RegisterReceiver(sync.processNetworkEvent) sync.broadcastPipe.RegisterReceiver(sync.broadcastMessage) return sync, nil } func (sync *synchronizer) Start() error { if err := sync.network.JoinTopic(network.TopicIDBlock, sync.blockTopicEvaluator); err != nil { return err } if err := sync.network.JoinTopic(network.TopicIDTransaction, sync.transactionTopicEvaluator); err != nil { return err } // TODO: Not joining consensus topic when we are syncing if err := sync.network.JoinTopic(network.TopicIDConsensus, sync.consensusTopicEvaluator); err != nil { return err } sync.ntp.Start() return nil } func (sync *synchronizer) Stop() { sync.ntp.Stop() } func (sync *synchronizer) ClockOffset() (time.Duration, error) { return sync.ntp.ClockOffset() } func (sync *synchronizer) IsClockOutOfSync() bool { return sync.ntp.IsOutOfSync() } func (sync *synchronizer) stateHeight() types.Height { stateHeight := sync.state.LastBlockHeight() return stateHeight } func (sync *synchronizer) moveConsensusToNewHeight() { stateHeight := sync.stateHeight() consHeight, _ := sync.getConsMgr().HeightRound() if stateHeight >= consHeight { sync.getConsMgr().MoveToNewHeight() } } func (sync *synchronizer) prepareBundle(msg message.Message) *bundle.Bundle { h := sync.handlers[msg.Type()] bdl := h.PrepareBundle(msg) // Bundles will be carried through LibP2P. // In future we might support other libraries. bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagCarrierLibP2P) switch sync.state.Genesis().ChainType() { case genesis.Mainnet: bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet) case genesis.Testnet: bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet) case genesis.Localnet: // It's localnet and for testing purpose only } return bdl } func (sync *synchronizer) sendTo(msg message.Message, pid peer.ID) { bdl := sync.prepareBundle(msg) data, _ := bdl.Encode() sync.network.SendTo(data, pid) sync.peerSet.UpdateLastSent(pid) sync.peerSet.UpdateSentMetric(&pid, msg.Type(), int64(len(data))) sync.logger.Debug("bundle sent", "bundle", bdl, "pid", pid) } func (sync *synchronizer) broadcast(msg message.Message) { if msg.Type() == message.TypeBlockAnnounce { m := msg.(*message.BlockAnnounceMessage) if sync.cache.HasBlockInCache(m.Height()) { // We have received the block announcement from other peers before, // so we can simply ignore broadcasting it again. // This helps to reduce the network bandwidth. return } } bdl := sync.prepareBundle(msg) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagBroadcasted) data, _ := bdl.Encode() sync.network.Broadcast(data, msg.TopicID()) sync.peerSet.UpdateSentMetric(nil, msg.Type(), int64(len(data))) sync.logger.Debug("bundle broadcasted", "bundle", bdl) } func (sync *synchronizer) SelfID() peer.ID { return sync.network.SelfID() } func (sync *synchronizer) Moniker() string { return sync.config.Moniker } func (sync *synchronizer) PeerSet() *peerset.PeerSet { return sync.peerSet } func (sync *synchronizer) Services() service.Services { return sync.config.Services } func (sync *synchronizer) sayHello(pid peer.ID) { peer := sync.peerSet.GetPeer(pid) if peer.Status.IsKnown() { return } msg := message.NewHelloMessage( sync.SelfID(), sync.config.Moniker, sync.config.Services, sync.stateHeight(), sync.state.LastBlockHash(), sync.state.Genesis().Hash(), ) msg.Sign(sync.valKeys) sync.sendTo(msg, pid) } func (sync *synchronizer) broadcastMessage(msg message.Message) { sync.broadcast(msg) } func (sync *synchronizer) processNetworkEvent(evt network.Event) { switch evt.Type() { case network.EventTypeGossip: ge := evt.(*network.GossipMessage) sync.processGossipMessage(ge) case network.EventTypeStream: se := evt.(*network.StreamMessage) sync.processStreamMessage(se) case network.EventTypeConnect: ce := evt.(*network.ConnectEvent) sync.processConnectEvent(ce) case network.EventTypeDisconnect: de := evt.(*network.DisconnectEvent) sync.processDisconnectEvent(de) case network.EventTypeProtocols: pe := evt.(*network.ProtocolsEvents) sync.processProtocolsEvent(pe) } } func (sync *synchronizer) processGossipMessage(msg *network.GossipMessage) { sync.logger.Debug("processing gossip message", "pid", msg.From) bdl, err := sync.firewall.OpenGossipBundle(msg.Data, msg.From) if err != nil { sync.logger.Debug("error on parsing a Gossip bundle", "from", msg.From, "bundle", bdl, "error", err) return } sync.processIncomingBundle(bdl, msg.From) } func (sync *synchronizer) processStreamMessage(msg *network.StreamMessage) { sync.logger.Debug("processing stream message", "pid", msg.From) defer func() { _ = msg.Reader.Close() }() bdl, err := sync.firewall.OpenStreamBundle(msg.Reader, msg.From) if err != nil { sync.logger.Debug("error on parsing a Stream bundle", "from", msg.From, "bundle", bdl, "error", err) return } sync.processIncomingBundle(bdl, msg.From) } func (sync *synchronizer) processConnectEvent(eve *network.ConnectEvent) { sync.logger.Debug("processing connect event", "pid", eve.PeerID) sync.peerSet.UpdateAddress(eve.PeerID, eve.RemoteAddress, eve.Direction) sync.peerSet.UpdateStatus(eve.PeerID, status.StatusConnected) } func (sync *synchronizer) processProtocolsEvent(eve *network.ProtocolsEvents) { sync.logger.Debug("processing protocols event", "pid", eve.PeerID, "protocols", eve.Protocols) sync.peerSet.UpdateProtocols(eve.PeerID, eve.Protocols) peer := sync.peerSet.GetPeer(eve.PeerID) if peer.Direction == lp2pnetwork.DirOutbound { sync.logger.Info("sending Hello message (outbound)", "to", eve.PeerID) sync.sayHello(eve.PeerID) // Mark that we've sent the hello message to the inbound peer sync.peerSet.UpdateOutboundHelloSent(eve.PeerID, true) } } func (sync *synchronizer) processDisconnectEvent(de *network.DisconnectEvent) { sync.logger.Debug("processing disconnect event", "pid", de.PeerID) sync.peerSet.UpdateStatus(de.PeerID, status.StatusDisconnected) } func (sync *synchronizer) processIncomingBundle(bdl *bundle.Bundle, from peer.ID) { sync.logger.Debug("received a bundle", "from", from, "bundle", bdl) handler := sync.handlers[bdl.Message.Type()] if handler == nil { sync.logger.Error("invalid message type", "type", bdl.Message.Type()) return } handler.ParseMessage(bdl.Message, from) } // LogString returns a concise string representation intended for use in logs. func (sync *synchronizer) LogString() string { return fmt.Sprintf("{☍ %d ⛃ %d}", sync.peerSet.Len(), sync.cache.Len()) } // updateBlockchain checks whether the node's height is shorter than the network's height or not. // If the node's height is shorter than the network's height by more than two hours (720 blocks), // it should start downloading blocks from the network's nodes. // Otherwise, the node can request the latest blocks from any nodes. func (sync *synchronizer) updateBlockchain() { // Maybe we have some blocks inside the cache? sync.tryCommitBlocks() // Check if we have any expired sessions sync.peerSet.SetExpiredSessionsAsUncompleted() // Try to re-download the blocks for uncompleted sessions sessions := sync.peerSet.Sessions() for _, ssn := range sessions { if ssn.Status == session.Uncompleted { sync.logger.Info("uncompleted block request, re-download", "sid", ssn.SessionID, "pid", ssn.PeerID, "stats", sync.peerSet.SessionStats()) sent := sync.sendBlockRequestToRandomPeer(ssn.From, ssn.Count, false) if !sent { break } } } // Check if there are any open sessions. // If open sessions exist, we should wait for them to close. // Otherwise, we might request to download the same blocks from different peers. // TODO: write test for me if sync.peerSet.HasAnyOpenSession() { sync.logger.Debug("we have open session", "stats", sync.peerSet.SessionStats()) return } sync.peerSet.RemoveAllSessions() blockInterval := sync.state.Params().BlockInterval() curTime := util.RoundNow(int(blockInterval.Seconds())) lastBlockTime := sync.state.LastBlockTime() diff := curTime.Sub(lastBlockTime) numOfBlocks := uint32(diff.Seconds() / blockInterval.Seconds()) if numOfBlocks <= 1 { // We are sync return } downloadHeight := sync.state.LastBlockHeight() downloadHeight++ if sync.cache.HasBlockInCache(downloadHeight) { // The last block exists inside the cache, without the certificate. // Ignore downloading this block again. downloadHeight++ } sync.logger.Info("start syncing with the network", "numOfBlocks", numOfBlocks, "height", downloadHeight) if numOfBlocks > sync.config.PruneWindow { // Don't have blocks for more than 10 days sync.downloadBlocks(downloadHeight, true) } else { sync.downloadBlocks(downloadHeight, false) } } // downloadBlocks starts downloading blocks from the network. func (sync *synchronizer) downloadBlocks(from types.Height, onlyFullNodes bool) { sync.logger.Debug("downloading blocks", "from", from) for i := sync.peerSet.NumberOfSessions(); i < sync.config.MaxSessions; i++ { count := sync.config.BlockPerSession sent := sync.sendBlockRequestToRandomPeer(from, count, onlyFullNodes) if !sent { return } from += types.Height(count) } } func (sync *synchronizer) sendBlockRequestToRandomPeer(from types.Height, count uint32, onlyFullNodes bool) bool { // Prevent downloading blocks that might be cached before for sync.cache.HasBlockInCache(from) { from++ count-- if count == 0 { // we have blocks inside the cache sync.logger.Debug("sending download request ignored", "from", from+1) return true } } for i := sync.peerSet.NumberOfSessions(); i < sync.config.MaxSessions; i++ { peer := sync.peerSet.GetRandomPeer() if peer == nil { break } // Don't open a new session if we already have an open session with the same peer. // This helps us to get blocks from different peers. if sync.peerSet.HasOpenSession(peer.PeerID) { continue } // We haven't completed the handshake with this peer. if !peer.Status.IsKnown() { if onlyFullNodes { sync.network.CloseConnection(peer.PeerID) } continue } if onlyFullNodes && !peer.IsFullNode() { if onlyFullNodes { sync.network.CloseConnection(peer.PeerID) } continue } sid := sync.peerSet.OpenSession(peer.PeerID, from, count) msg := message.NewBlocksRequestMessage(sid, from, count) sync.sendTo(msg, peer.PeerID) sync.logger.Info("blocks request sent", "from", from+1, "count", count, "pid", peer.PeerID, "sid", sid) return true } sync.logger.Warn("unable to open a new session", "stats", sync.peerSet.SessionStats()) return false } func (sync *synchronizer) tryCommitBlocks() { onError := func(height types.Height, err error) { sync.logger.Warn("committing block failed, removing block from the cache", "height", height, "error", err) sync.cache.RemoveBlock(height) } height := sync.stateHeight() + 1 for { blk := sync.cache.GetBlock(height) if blk == nil { break } cert := sync.cache.GetCertificate(height) if cert == nil { break } trxs := blk.Transactions() for i := 0; i < trxs.Len(); i++ { trx := trxs[i] if trx.IsPublicKeyStriped() { pub, err := sync.state.PublicKey(trx.Payload().Signer()) if err != nil { onError(height, err) return } trx.SetPublicKey(pub) } } if err := blk.BasicCheck(); err != nil { onError(height, err) return } if err := cert.BasicCheck(); err != nil { onError(height, err) return } sync.logger.Trace("committing block", "height", height, "block", blk) if err := sync.state.CommitBlock(blk, cert); err != nil { onError(height, err) return } height++ } } func (sync *synchronizer) prepareBlocks(from types.Height, count uint32) [][]byte { ourHeight := sync.stateHeight() if from > ourHeight { sync.logger.Debug("we don't have block at this height", "height", from) return nil } if from+types.Height(count) > ourHeight { count = uint32(ourHeight - from + 1) } blocks := make([][]byte, 0, count) for height := from; height < from+types.Height(count); height++ { cBlk, err := sync.state.CommittedBlock(height) if err != nil { sync.logger.Warn("unable to find a block", "height", height) return nil } blocks = append(blocks, cBlk.Data) } return blocks } func (sync *synchronizer) blockTopicEvaluator(msg *network.GossipMessage) network.PropagationPolicy { return sync.firewall.AllowBlockRequest(msg) } func (sync *synchronizer) transactionTopicEvaluator(msg *network.GossipMessage) network.PropagationPolicy { return sync.firewall.AllowTransactionRequest(msg) } func (sync *synchronizer) consensusTopicEvaluator(msg *network.GossipMessage) network.PropagationPolicy { return sync.firewall.AllowConsensusRequest(msg) } // getConsMgr returns consensus manager based on the upgrade condition. // After the chain is fully upgraded, we can remove this function. func (sync *synchronizer) getConsMgr() consmgr.Manager { if sync.consV1Mgr.IsDeprecated() { return sync.consV2Mgr } return sync.consV1Mgr } ================================================ FILE: sync/sync_test.go ================================================ package sync import ( "bytes" "fmt" "testing" "time" "github.com/ezex-io/gopkg/pipeline" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/consensus" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync/bundle" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/firewall" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/version" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite config *Config state *state.MockState consMocks []*consensus.MockConsensus network *network.MockNetwork sync *synchronizer } func testConfig() *Config { return &Config{ Moniker: "test", SessionTimeoutStr: "1s", BlockPerMessage: 11, MaxSessions: 4, BlockPerSession: 27, PruneWindow: 13, Firewall: firewall.DefaultConfig(), LatestSupportingVer: DefaultConfig().LatestSupportingVer, Services: service.New(service.FullNode, service.PrunedNode), } } func setup(t *testing.T, config *Config) *testData { t.Helper() ts := testsuite.NewTestSuite(t) if config == nil { config = testConfig() config.Moniker = "Alice" } valKeys := []*bls.ValidatorKey{ts.RandValKey(), ts.RandValKey()} mockState := state.MockingState(ts) consV1Mgr, consMocks := consmgr.MockingManager(ts, mockState, []*bls.ValidatorKey{valKeys[0], valKeys[1]}) consV1Mgr.MoveToNewHeight() consV2Mgr, _ := consmgr.MockingManager(ts, mockState, []*bls.ValidatorKey{valKeys[0], valKeys[1]}) consV2Mgr.MoveToNewHeight() mockNetwork := network.MockingNetwork(ts, ts.RandPeerID()) broadcastPipe := pipeline.New[message.Message](t.Context()) syncInst, err := NewSynchronizer(t.Context(), config, valKeys, mockState, consV1Mgr, consV2Mgr, mockNetwork, broadcastPipe, mockNetwork.EventPipe) require.NoError(t, err) sync := syncInst.(*synchronizer) td := &testData{ TestSuite: ts, config: config, state: mockState, consMocks: consMocks, network: mockNetwork, sync: sync, } require.NoError(t, td.sync.Start()) assert.Equal(t, config.Moniker, td.sync.Moniker()) assert.Equal(t, config.Services, td.sync.Services()) logger.Info("setup finished, running the tests", "name", t.Name()) return td } func shouldPublishMessageWithThisType(t *testing.T, net *network.MockNetwork, msgType message.Type) *bundle.Bundle { t.Helper() timer := time.NewTimer(3 * time.Second) for { select { case <-timer.C: require.NoError(t, fmt.Errorf("shouldPublishMessageWithThisType %v: Timeout, test: %v", msgType, t.Name())) return nil case data := <-net.PublishCh: // Decode message again to check the message type bdl := new(bundle.Bundle) _, err := bdl.Decode(bytes.NewReader(data.Data)) require.NoError(t, err) // ----------- // Check flags require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagCarrierLibP2P), "invalid flag: %v", bdl) require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkMainnet), "invalid flag: %v", bdl) if data.Target == nil { require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagBroadcasted), "invalid flag: %v", bdl) } else { require.False(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagBroadcasted), "invalid flag: %v", bdl) } if bdl.Message.Type() == message.TypeHello || bdl.Message.Type() == message.TypeHelloAck { require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagHandshaking), "invalid flag: %v", bdl) } else { require.False(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagHandshaking), "invalid flag: %v", bdl) } // ----------- require.Equal(t, msgType, bdl.Message.Type(), "not expected message: %s", msgType) return bdl } } } func (td *testData) shouldPublishMessageWithThisType(t *testing.T, msgType message.Type, ) *bundle.Bundle { t.Helper() return shouldPublishMessageWithThisType(t, td.network, msgType) } func shouldNotPublishAnyMessage(t *testing.T, net *network.MockNetwork) { t.Helper() timer := time.NewTimer(3 * time.Millisecond) for { select { case <-timer.C: return case data := <-net.PublishCh: // Decode message again to check the message type bdl := new(bundle.Bundle) _, err := bdl.Decode(bytes.NewReader(data.Data)) require.NoError(t, err) require.Fail(t, "published unexpected message: "+bdl.Message.Type().String()) } } } func (td *testData) shouldNotPublishAnyMessage(t *testing.T) { t.Helper() shouldNotPublishAnyMessage(t, td.network) } func (*testData) receivingNewMessage(sync *synchronizer, msg message.Message, from peer.ID) { bdl := bundle.NewBundle(msg) bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagCarrierLibP2P|bundle.BundleFlagNetworkMainnet) sync.processIncomingBundle(bdl, from) } func (td *testData) addPeer(t *testing.T, status status.Status, services service.Services) peer.ID { t.Helper() pid := td.RandPeerID() pub, _ := td.RandBLSKeyPair() td.sync.peerSet.UpdateInfo(pid, t.Name(), version.NodeAgent.String(), []*bls.PublicKey{pub}, services) td.sync.peerSet.UpdateStatus(pid, status) return pid } func (td *testData) addValidatorToCommittee(t *testing.T, pub *bls.PublicKey) { t.Helper() if pub == nil { pub, _ = td.RandBLSKeyPair() } val := td.GenerateTestValidator(testsuite.ValidatorWithPublicKey(pub)) // Note: This may not be completely accurate, but it has no harm for testing purposes. val.UpdateLastSortitionHeight(td.state.TestCommittee.Proposer(0).LastSortitionHeight() + 1) td.state.TestStore.UpdateValidator(val) td.state.TestCommittee.Update(0, []*validator.Validator{val}) require.True(t, td.state.TestCommittee.Contains(pub.ValidatorAddress())) for _, cons := range td.consMocks { cons.SetActive(cons.ValKey.PublicKey().EqualsTo(pub)) } } func (td *testData) checkPeerStatus(t *testing.T, pid peer.ID, code status.Status) { t.Helper() require.Equal(t, code, td.sync.peerSet.GetPeerStatus(pid)) } func TestStop(t *testing.T) { td := setup(t, nil) // Should stop gracefully. td.sync.Stop() } func TestConnectEvent(t *testing.T) { td := setup(t, nil) pid := td.RandPeerID() remoteAddr := "/ip4/2.2.2.2/tcp/21888" ce := &network.ConnectEvent{ PeerID: pid, RemoteAddress: remoteAddr, Direction: lp2pnetwork.DirInbound, } td.network.EventPipe.Send(ce) assert.Eventually(t, func() bool { return td.sync.peerSet.HasPeer(pid) }, time.Second, 100*time.Millisecond) peer := td.sync.peerSet.GetPeer(pid) assert.Equal(t, status.StatusConnected, peer.Status) assert.Equal(t, remoteAddr, peer.Address) assert.Equal(t, lp2pnetwork.DirInbound, peer.Direction) } func TestDisconnectEvent(t *testing.T) { td := setup(t, nil) pid := td.RandPeerID() de := &network.DisconnectEvent{ PeerID: pid, } td.network.EventPipe.Send(de) assert.Eventually(t, func() bool { return td.sync.peerSet.HasPeer(pid) }, time.Second, 100*time.Millisecond) td.checkPeerStatus(t, pid, status.StatusDisconnected) } func TestProtocolsEvent(t *testing.T) { td := setup(t, nil) pid := td.RandPeerID() pe := &network.ProtocolsEvents{ PeerID: pid, Protocols: []string{"protocol-1", "protocol-2"}, } td.network.EventPipe.Send(pe) assert.Eventually(t, func() bool { return td.sync.peerSet.HasPeer(pid) }, time.Second, 100*time.Millisecond) peer := td.sync.peerSet.GetPeer(pid) assert.Equal(t, []string{"protocol-1", "protocol-2"}, peer.Protocols) } func TestSendHello(t *testing.T) { td := setup(t, nil) t.Run("Peer with unknown Direction", func(t *testing.T) { pid := td.RandPeerID() pe := &network.ProtocolsEvents{ PeerID: pid, Protocols: []string{"protocol-1"}, } td.network.EventPipe.Send(pe) td.shouldNotPublishAnyMessage(t) }) t.Run("Peer with inbound Direction", func(t *testing.T) { pid := td.RandPeerID() td.sync.peerSet.UpdateAddress(pid, "test-address", lp2pnetwork.DirInbound) pe := &network.ProtocolsEvents{ PeerID: pid, Protocols: []string{"protocol-1"}, } td.network.EventPipe.Send(pe) td.shouldNotPublishAnyMessage(t) }) t.Run("Peer with outbound Direction", func(t *testing.T) { pid := td.RandPeerID() td.sync.peerSet.UpdateAddress(pid, "test-address", lp2pnetwork.DirOutbound) pe := &network.ProtocolsEvents{ PeerID: pid, Protocols: []string{"protocol-1"}, } td.network.EventPipe.Send(pe) td.shouldPublishMessageWithThisType(t, message.TypeHello) }) } func TestTestNetFlags(t *testing.T) { td := setup(t, nil) td.state.TestGenesis = genesis.TestnetGenesis() td.addValidatorToCommittee(t, td.sync.valKeys[0].PublicKey()) bdl := td.sync.prepareBundle(message.NewQueryProposalMessage(td.RandHeight(), td.RandRound(), td.RandValAddress())) require.False(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkMainnet), "invalid flag: %v", bdl) require.True(t, util.IsFlagSet(bdl.Flags, bundle.BundleFlagNetworkTestnet), "invalid flag: %v", bdl) } func TestDownload(t *testing.T) { conf := testConfig() // Let's not allow `GetRandomPeer` to disappoint us! conf.MaxSessions = 32 t.Run("try to download blocks, but the peer is not known", func(t *testing.T) { td := setup(t, conf) pid := td.addPeer(t, status.StatusConnected, service.New(service.None)) blk, cert := td.GenerateTestBlock(td.RandHeight()) baMsg := message.NewBlockAnnounceMessage(blk, cert, nil) td.receivingNewMessage(td.sync, baMsg, pid) td.shouldNotPublishAnyMessage(t) td.network.IsClosed(pid) }) t.Run("try to download blocks, but the peer is not a network node", func(t *testing.T) { td := setup(t, conf) pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) blk, cert := td.GenerateTestBlock(td.RandHeight()) baMsg := message.NewBlockAnnounceMessage(blk, cert, nil) td.receivingNewMessage(td.sync, baMsg, pid) td.shouldNotPublishAnyMessage(t) td.network.IsClosed(pid) }) t.Run("try to download blocks and the peer is a network node", func(t *testing.T) { td := setup(t, conf) pid := td.addPeer(t, status.StatusKnown, service.New(service.FullNode)) blk, cert := td.GenerateTestBlock(td.RandHeight()) baMsg := message.NewBlockAnnounceMessage(blk, cert, nil) td.receivingNewMessage(td.sync, baMsg, pid) td.shouldPublishMessageWithThisType(t, message.TypeBlocksRequest) }) t.Run("download request is rejected", func(t *testing.T) { td := setup(t, conf) pid := td.addPeer(t, status.StatusKnown, service.New(service.None)) from := td.sync.stateHeight() + 1 count := uint32(123) sid := td.sync.peerSet.OpenSession(pid, from, count) msg := message.NewBlocksResponseMessage(message.ResponseCodeRejected, t.Name(), sid, 1, nil, nil) td.receivingNewMessage(td.sync, msg, pid) assert.False(t, td.sync.peerSet.HasOpenSession(pid)) }) } func TestBroadcastBlockAnnounce(t *testing.T) { td := setup(t, nil) t.Run("Should announce the block", func(t *testing.T) { blk, cert := td.GenerateTestBlock(td.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert, nil) td.sync.broadcast(msg) td.shouldPublishMessageWithThisType(t, message.TypeBlockAnnounce) }) t.Run("Should NOT announce the block", func(t *testing.T) { blk, cert := td.GenerateTestBlock(td.RandHeight()) msg := message.NewBlockAnnounceMessage(blk, cert, nil) td.sync.cache.AddBlock(blk) td.sync.broadcast(msg) td.shouldNotPublishAnyMessage(t) }) } func TestAllBlocksInCache(t *testing.T) { td := setup(t, nil) blk100, _ := td.GenerateTestBlock(100) blk101, _ := td.GenerateTestBlock(101) blk102, _ := td.GenerateTestBlock(102) td.sync.cache.AddBlock(blk100) td.sync.cache.AddBlock(blk101) td.sync.cache.AddBlock(blk102) res := td.sync.sendBlockRequestToRandomPeer(100, 3, true) assert.True(t, res) } ================================================ FILE: tests/account_test.go ================================================ package tests import ( "testing" "github.com/pactus-project/pactus/crypto" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func getAccount(t *testing.T, addr crypto.Address) *pactus.AccountInfo { t.Helper() res, err := tBlockchainClient.GetAccount(tCtx, &pactus.GetAccountRequest{Address: addr.String()}) if err != nil { return nil } return res.Account } func TestGetAccount(t *testing.T) { acc := getAccount(t, crypto.TreasuryAddress) require.NotNil(t, acc) assert.Equal(t, int32(0), acc.Number) } ================================================ FILE: tests/block_test.go ================================================ package tests import ( "fmt" "time" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/util/logger" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) func lastHeight() types.Height { res, err := tBlockchainClient.GetBlockchainInfo(tCtx, &pactus.GetBlockchainInfoRequest{}) if err != nil { panic(err) } return types.Height(res.LastBlockHeight) } func waitForNewBlocks(num uint32) { for i := uint32(0); i < num; i++ { height := lastHeight() if lastHeight() > height { break } time.Sleep(4 * time.Second) } } func lastBlock() *pactus.GetBlockResponse { return getBlockAt(lastHeight()) } func getBlockAt(height types.Height) *pactus.GetBlockResponse { for i := 0; i < 120; i++ { res, err := tBlockchainClient.GetBlock(tCtx, &pactus.GetBlockRequest{ Height: uint32(height), Verbosity: pactus.BlockVerbosity_BLOCK_VERBOSITY_INFO, }, ) if err != nil { fmt.Printf("getBlockAt err: %s\n", err.Error()) time.Sleep(1 * time.Second) continue } return res } logger.Panic("getBlockAt timeout", "height", height) return nil } ================================================ FILE: tests/main_test.go ================================================ package tests import ( "context" "fmt" "path/filepath" "testing" "time" "github.com/pactus-project/pactus/config" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/node" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/txpool" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/wallet" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) var ( tValKeys [][]*bls.ValidatorKey tConfigs []*config.Config tNodes []*node.Node tGRPCAddress = "127.0.0.1:1337" tGenDoc *genesis.Genesis tBlockchainClient pactus.BlockchainClient tTransactionClient pactus.TransactionClient tNetwork pactus.NetworkClient tCtx context.Context ) const ( tNodeIdx1 = 0 tNodeIdx2 = 1 tNodeIdx3 = 2 tNodeIdx4 = 3 tTotalNodes = 4 // each node has 3 validators tCommitteeSize = 7 ) func TestMain(m *testing.M) { // Prevent log from messing the workspace logger.LogFilename = util.TempFilePath() tValKeys = make([][]*bls.ValidatorKey, tTotalNodes) tConfigs = make([]*config.Config, tTotalNodes) tNodes = make([]*node.Node, tTotalNodes) ikm := hash.CalcHash([]byte{}) for i := 0; i < tTotalNodes; i++ { ikm = hash.CalcHash(ikm.Bytes()) key0, _ := bls.KeyGen(ikm.Bytes(), nil) ikm = hash.CalcHash(ikm.Bytes()) key1, _ := bls.KeyGen(ikm.Bytes(), nil) ikm = hash.CalcHash(ikm.Bytes()) key2, _ := bls.KeyGen(ikm.Bytes(), nil) tValKeys[i] = make([]*bls.ValidatorKey, 3) tValKeys[i][0] = bls.NewValidatorKey(key0) tValKeys[i][1] = bls.NewValidatorKey(key1) tValKeys[i][2] = bls.NewValidatorKey(key2) tConfigs[i] = config.DefaultConfigMainnet() tConfigs[i].TxPool.Fee = &txpool.FeeConfig{ FixedFee: 0.000001, DailyLimit: 280, UnitPrice: 0, } tConfigs[i].Store.Path = util.TempDirPath() tConfigs[i].Consensus.ChangeProposerTimeout = 2 * time.Second tConfigs[i].Consensus.ChangeProposerDelta = 2 * time.Second tConfigs[i].Consensus.QueryVoteTimeout = 2 * time.Second tConfigs[i].ConsensusV2.ChangeProposerTimeout = 2 * time.Second tConfigs[i].ConsensusV2.ChangeProposerDelta = 2 * time.Second tConfigs[i].ConsensusV2.QueryVoteTimeout = 2 * time.Second tConfigs[i].Logger.Levels["default"] = "info" tConfigs[i].Logger.Levels["_state"] = "info" tConfigs[i].Logger.Levels["_sync"] = "info" tConfigs[i].Logger.Levels["_consensus"] = "debug" tConfigs[i].Logger.Levels["_network"] = "info" tConfigs[i].Logger.Levels["_pool"] = "info" tConfigs[i].Sync.Firewall.BannedNets = make([]string, 0) tConfigs[i].Sync.BlockPerSession = 10 tConfigs[i].Network.EnableMdns = true tConfigs[i].Network.EnableRelay = false tConfigs[i].Network.DefaultBootstrapAddrStrings = []string{} tConfigs[i].Network.BootstrapAddrStrings = []string{} tConfigs[i].Network.ForcePrivateNetwork = true tConfigs[i].Network.NetworkKey = util.TempFilePath() tConfigs[i].Network.NetworkName = "test" tConfigs[i].Network.ListenAddrStrings = []string{"/ip4/127.0.0.1/tcp/0", "/ip4/127.0.0.1/udp/0/quic-v1"} tConfigs[i].Network.MaxConns = 32 tConfigs[i].Network.PeerStorePath = util.TempFilePath() tConfigs[i].HTML.Enable = false tConfigs[i].GRPC.Enable = false tConfigs[i].WalletManager.WalletsDir = util.TempDirPath() walletPath := filepath.Join(tConfigs[i].WalletManager.WalletsDir, "default_wallet") mnemonic, _ := wallet.GenerateMnemonic(128) wlt, err := wallet.Create(context.Background(), walletPath, mnemonic, "", genesis.Mainnet) if err != nil { panic(fmt.Errorf("failed to create wallet: %w", err)) } wlt.Close() if i == 0 { tConfigs[i].GRPC.Enable = true tConfigs[i].GRPC.Listen = tGRPCAddress } fmt.Printf("Node %d created.\n", i+1) } acc1 := account.NewAccount(0) acc1.AddToBalance(21 * 1e14) key, _ := bls.KeyGen(ikm.Bytes(), nil) acc2 := account.NewAccount(1) acc2.AddToBalance(21 * 1e14) accs := map[crypto.Address]*account.Account{ crypto.TreasuryAddress: acc1, key.PublicKeyNative().AccountAddress(): acc2, } vals := make([]*validator.Validator, 4) vals[0] = validator.NewValidator(tValKeys[tNodeIdx1][0].PublicKey(), 0) vals[1] = validator.NewValidator(tValKeys[tNodeIdx2][0].PublicKey(), 1) vals[2] = validator.NewValidator(tValKeys[tNodeIdx3][0].PublicKey(), 2) vals[3] = validator.NewValidator(tValKeys[tNodeIdx4][0].PublicKey(), 3) genParams := genesis.DefaultGenesisParams() genParams.BlockVersion = protocol.ProtocolVersionLatest genParams.MinimumStake = 1000 genParams.BlockIntervalInSecond = 2 genParams.BondInterval = 8 genParams.CommitteeSize = tCommitteeSize genParams.TransactionToLiveInterval = 8 tGenDoc = genesis.MakeGenesis(time.Now().Add(10*time.Second), accs, vals, genParams) tCtx = context.Background() for i := 0; i < tTotalNodes; i++ { tNodes[i], _ = node.NewNode( tCtx, tGenDoc, tConfigs[i], tValKeys[i], []crypto.Address{ tValKeys[i][0].PublicKey().AccountAddress(), tValKeys[i][1].PublicKey().AccountAddress(), tValKeys[i][2].PublicKey().AccountAddress(), }) if err := tNodes[i].Start(); err != nil { panic(fmt.Sprintf("Error on starting the node: %v", err)) } if i == 0 { // Set bootstrap address for better connectivity bootstrapAddr := fmt.Sprintf("%v/p2p/%v", tNodes[i].Network().HostAddrs()[0], tNodes[i].Network().SelfID()) fmt.Println("Bootstrap address is: " + bootstrapAddr) tConfigs[tNodeIdx2].Network.BootstrapAddrStrings = []string{bootstrapAddr} tConfigs[tNodeIdx3].Network.BootstrapAddrStrings = []string{bootstrapAddr} tConfigs[tNodeIdx4].Network.BootstrapAddrStrings = []string{bootstrapAddr} } } time.Sleep(10 * time.Second) grpcConn, err := grpc.NewClient( tGRPCAddress, grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { panic(fmt.Errorf("failed to dial server: %w", err)) } tBlockchainClient = pactus.NewBlockchainClient(grpcConn) tTransactionClient = pactus.NewTransactionClient(grpcConn) tNetwork = pactus.NewNetworkClient(grpcConn) // Wait for some blocks fmt.Println("Waiting to commit some blocks...") waitForNewBlocks(8) fmt.Println("Running tests...") m.Run() // Commit more blocks, then new nodes can catch up and send sortition transactions fmt.Println("Waiting to commit some blocks...") waitForNewBlocks(20) // Check if sortition worked or not? block := lastBlock() cert := block.PrevCert if block.Height == 1 { panic("block height should be greater than 1") } if len(cert.Committers) == 4 { panic("Sortition didn't work") } // Lets shutdown the nodes tCtx.Done() for i := 0; i < tTotalNodes; i++ { tNodes[i].Stop() } store, _ := store.NewStore(tConfigs[tNodeIdx1].Store) total := amount.Amount(0) store.IterateAccounts(func(_ crypto.Address, acc *account.Account) bool { total += acc.Balance() return false }) store.IterateValidators(func(v *validator.Validator) bool { total += v.Stake() return false }) if total != tGenDoc.TotalSupply() { panic(fmt.Sprintf("Some coins missed: %v", tGenDoc.TotalSupply()-total)) } } ================================================ FILE: tests/transaction_test.go ================================================ package tests import ( "encoding/hex" "fmt" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/testsuite" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func sendRawTx(t *testing.T, raw []byte) error { t.Helper() _, err := tTransactionClient.BroadcastTransaction(tCtx, &pactus.BroadcastTransactionRequest{SignedRawTransaction: hex.EncodeToString(raw)}) return err } func broadcastSendTransaction(t *testing.T, sender *bls.ValidatorKey, receiver crypto.Address, amt, fee amount.Amount, ) error { t.Helper() lockTime := lastHeight() + 1 trx := tx.NewTransferTx(lockTime, sender.PublicKey().AccountAddress(), receiver, amt, fee) sig := sender.Sign(trx.SignBytes()) trx.SetPublicKey(sender.PublicKey()) trx.SetSignature(sig) d, _ := trx.Bytes() return sendRawTx(t, d) } func broadcastBondTransaction(t *testing.T, sender *bls.ValidatorKey, pub *bls.PublicKey, stake, fee amount.Amount, ) error { t.Helper() lockTime := lastHeight() + 1 trx := tx.NewBondTx(lockTime, sender.PublicKey().AccountAddress(), pub.ValidatorAddress(), pub, stake, fee) sig := sender.Sign(trx.SignBytes()) trx.SetPublicKey(sender.PublicKey()) trx.SetSignature(sig) d, _ := trx.Bytes() return sendRawTx(t, d) } func TestTransactions(t *testing.T) { ts := testsuite.NewTestSuite(t) pubAlice, prvAlice := ts.RandBLSKeyPair() pubBob, prvBob := ts.RandBLSKeyPair() pubCarol, _ := ts.RandBLSKeyPair() pubDave, _ := ts.RandBLSKeyPair() valKeyAlice := bls.NewValidatorKey(prvAlice) valKeyBob := bls.NewValidatorKey(prvBob) t.Run("Sending normal transaction", func(t *testing.T) { require.NoError(t, broadcastSendTransaction(t, tValKeys[tNodeIdx2][0], pubAlice.AccountAddress(), 80000000, 8000)) }) t.Run("Alice tries double spending", func(t *testing.T) { require.NoError(t, broadcastSendTransaction(t, valKeyAlice, pubBob.AccountAddress(), 50000000, 5000)) require.Error(t, broadcastSendTransaction(t, valKeyAlice, pubCarol.AccountAddress(), 50000000, 5000)) }) t.Run("Bob sends two transaction at once", func(t *testing.T) { require.NoError(t, broadcastSendTransaction(t, valKeyBob, pubCarol.AccountAddress(), 10, 1000)) require.NoError(t, broadcastSendTransaction(t, valKeyBob, pubDave.AccountAddress(), 1, 1000)) }) t.Run("Bonding transactions", func(t *testing.T) { // These validators are not in the committee now. // Bond transactions are valid and they can enter the committee soon for i := 0; i < tTotalNodes; i++ { amt := amount.Amount(1000000) fee := amount.Amount(1000) valKey := tValKeys[tNodeIdx1][0] require.NoError(t, broadcastBondTransaction(t, valKey, tValKeys[i][1].PublicKey(), amt, fee)) fmt.Printf("Staking %v to %v\n", amt, tValKeys[i][1].Address()) require.NoError(t, broadcastBondTransaction(t, valKey, tValKeys[i][2].PublicKey(), amt, fee)) fmt.Printf("Staking %v to %v\n", amt, tValKeys[i][2].Address()) } }) // Make sure all transactions are confirmed waitForNewBlocks(8) accAlice := getAccount(t, pubAlice.AccountAddress()) accBob := getAccount(t, pubBob.AccountAddress()) accCarol := getAccount(t, pubCarol.AccountAddress()) accDave := getAccount(t, pubDave.AccountAddress()) require.NotNil(t, accAlice) require.NotNil(t, accBob) require.NotNil(t, accCarol) require.NotNil(t, accDave) assert.Equal(t, int64(80000000-50005000), accAlice.Balance) assert.Equal(t, int64(50000000-2011), accBob.Balance) assert.Equal(t, int64(10), accCarol.Balance) assert.Equal(t, int64(1), accDave.Balance) } ================================================ FILE: tests/validator_test.go ================================================ package tests import ( "testing" "github.com/pactus-project/pactus/crypto" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func getValidator(t *testing.T, addr crypto.Address) *pactus.ValidatorInfo { t.Helper() res, err := tBlockchainClient.GetValidator(tCtx, &pactus.GetValidatorRequest{Address: addr.String()}) if err != nil { return nil } return res.Validator } func TestGetValidator(t *testing.T) { val := getValidator(t, tValKeys[tNodeIdx2][0].Address()) require.NotNil(t, val) assert.Equal(t, int32(1), val.Number) } ================================================ FILE: txpool/config.go ================================================ package txpool import "github.com/pactus-project/pactus/types/amount" // Config defines parameters for the transaction pool. type Config struct { MaxSize int `toml:"max_size"` Fee *FeeConfig `toml:"fee"` // Private configuration ConsumptionWindow uint32 `toml:"-"` } // FeeConfig holds fee-related settings used to estimate and validate // transaction fees. type FeeConfig struct { FixedFee float64 `toml:"fixed_fee"` DailyLimit int `toml:"daily_limit"` UnitPrice float64 `toml:"unit_price"` } // DefaultConfig returns the default transaction pool configuration. func DefaultConfig() *Config { return &Config{ MaxSize: 1000, Fee: DefaultFeeConfig(), ConsumptionWindow: 8640, } } // DefaultFeeConfig returns the default fee configuration. func DefaultFeeConfig() *FeeConfig { return &FeeConfig{ FixedFee: 0.01, DailyLimit: 360, UnitPrice: 0, } } // BasicCheck performs basic checks on the configuration. func (conf *Config) BasicCheck() error { if conf.MaxSize < 10 { return ConfigError{ Reason: "maxSize can't be less than 10", } } if conf.Fee.DailyLimit <= 0 { return ConfigError{ Reason: "dailyLimit should be positive", } } return nil } func (conf *Config) calculateConsumption() bool { return conf.Fee.UnitPrice > 0 } func (conf *Config) fixedFee() amount.Amount { amt, _ := amount.NewAmount(conf.Fee.FixedFee) return amt } func (conf *Config) sortitionPoolSize() int { return int(float32(conf.MaxSize) * 0.1) } func (conf *Config) bondPoolSize() int { return int(float32(conf.MaxSize) * 0.1) } func (conf *Config) unbondPoolSize() int { return int(float32(conf.MaxSize) * 0.1) } func (conf *Config) withdrawPoolSize() int { return int(float32(conf.MaxSize) * 0.1) } func (conf *Config) transferPoolSize() int { return int(float32(conf.MaxSize) * 0.5) } func (conf *Config) batchTransferPoolSize() int { return int(float32(conf.MaxSize) * 0.1) } ================================================ FILE: txpool/config_test.go ================================================ package txpool import ( "testing" "github.com/pactus-project/pactus/types/amount" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDefaultConfig(t *testing.T) { conf := DefaultConfig() require.NoError(t, conf.BasicCheck()) assert.Equal(t, 500, conf.transferPoolSize()) assert.Equal(t, 100, conf.bondPoolSize()) assert.Equal(t, 100, conf.unbondPoolSize()) assert.Equal(t, 100, conf.withdrawPoolSize()) assert.Equal(t, 100, conf.sortitionPoolSize()) assert.Equal(t, 100, conf.batchTransferPoolSize()) assert.Equal(t, amount.Amount(0.01e9), conf.fixedFee()) assert.Equal(t, conf.transferPoolSize()+ conf.bondPoolSize()+ conf.unbondPoolSize()+ conf.withdrawPoolSize()+ conf.sortitionPoolSize()+ conf.batchTransferPoolSize(), conf.MaxSize) } func TestConfigBasicCheck(t *testing.T) { tests := []struct { name string expectedErr error updateFn func(c *Config) }{ { name: "Invalid MaxSize", expectedErr: ConfigError{ Reason: "maxSize can't be less than 10", }, updateFn: func(c *Config) { c.MaxSize = 0 }, }, { name: "Invalid MaxSize", expectedErr: ConfigError{ Reason: "maxSize can't be less than 10", }, updateFn: func(c *Config) { c.MaxSize = 9 }, }, { name: "Invalid DailyLimit", expectedErr: ConfigError{ Reason: "dailyLimit should be positive", }, updateFn: func(c *Config) { c.Fee.DailyLimit = 0 }, }, { name: "Negative DailyLimit", expectedErr: ConfigError{ Reason: "dailyLimit should be positive", }, updateFn: func(c *Config) { c.Fee.DailyLimit = -1 }, }, { name: "Valid Config", updateFn: func(c *Config) { c.MaxSize = 100 c.Fee = &FeeConfig{ FixedFee: 0.01, DailyLimit: 280, UnitPrice: 0, } }, }, { name: "DefaultConfig", updateFn: func(*Config) {}, }, } for no, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := DefaultConfig() tt.updateFn(conf) if tt.expectedErr != nil { err := conf.BasicCheck() require.ErrorIs(t, tt.expectedErr, err, "Expected error not matched for test %d-%s, expected: %s, got: %s", no, tt.name, tt.expectedErr, err) } else { err := conf.BasicCheck() require.NoError(t, err, "Expected no error for test %d-%s, get: %s", no, tt.name, err) } }) } } ================================================ FILE: txpool/errors.go ================================================ package txpool import ( "fmt" "github.com/pactus-project/pactus/types/amount" ) // ConfigError is returned when the transaction pool configuration is invalid. type ConfigError struct { Reason string } func (e ConfigError) Error() string { return e.Reason } // InvalidFeeError indicates that a transaction fee is below the required minimum. type InvalidFeeError struct { MinimumFee amount.Amount } func (e InvalidFeeError) Error() string { return fmt.Sprintf("transaction fee is below the minimum of %s", e.MinimumFee) } ================================================ FILE: txpool/interface.go ================================================ package txpool import ( "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" ) // Reader exposes read-only operations on the transaction pool. type Reader interface { PrepareBlockTransactions() block.Txs PendingTx(txID tx.ID) *tx.Tx HasTx(txID tx.ID) bool Size() int EstimatedFee(amt amount.Amount, payloadType payload.Type) amount.Amount AllPendingTxs() []*tx.Tx } // TxPool defines the full transaction pool interface with read and write // operations. type TxPool interface { Reader SetNewSandboxAndRecheck(sbx sandbox.Sandbox) AppendTxAndBroadcast(trx *tx.Tx) error AppendTx(trx *tx.Tx) error HandleCommittedBlock(blk *block.Block) } ================================================ FILE: txpool/pool.go ================================================ package txpool import ( "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/linkedmap" ) type pool struct { list *linkedmap.LinkedMap[tx.ID, *tx.Tx] minFee amount.Amount } func newPool(maxSize int, minFee amount.Amount) pool { return pool{ list: linkedmap.New[tx.ID, *tx.Tx](maxSize), minFee: minFee, } } func (p *pool) estimatedFee() amount.Amount { return p.minFee } ================================================ FILE: txpool/txpool.go ================================================ package txpool import ( "fmt" "sync" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/execution" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/store" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util/linkedlist" "github.com/pactus-project/pactus/util/linkedmap" "github.com/pactus-project/pactus/util/logger" ) type txPool struct { lk sync.RWMutex config *Config sbx sandbox.Sandbox pools map[payload.Type]pool consumptionMap map[crypto.Address]int broadcastPipe pipeline.Pipeline[message.Message] eventPipe pipeline.Pipeline[any] store store.Reader logger *logger.SubLogger } // NewTxPool constructs a new transaction pool with sub-pools per transaction // type. The pool also maintains a consumption map for tracking per-address // daily byte usage. func NewTxPool(conf *Config, storeReader store.Reader, broadcastPipe pipeline.Pipeline[message.Message], eventPipe pipeline.Pipeline[any], ) TxPool { pools := make(map[payload.Type]pool) pools[payload.TypeTransfer] = newPool(conf.transferPoolSize(), conf.fixedFee()) pools[payload.TypeBond] = newPool(conf.bondPoolSize(), conf.fixedFee()) pools[payload.TypeUnbond] = newPool(conf.unbondPoolSize(), 0) pools[payload.TypeWithdraw] = newPool(conf.withdrawPoolSize(), conf.fixedFee()) pools[payload.TypeSortition] = newPool(conf.sortitionPoolSize(), 0) pools[payload.TypeBatchTransfer] = newPool(conf.batchTransferPoolSize(), conf.fixedFee()) pool := &txPool{ config: conf, pools: pools, consumptionMap: make(map[crypto.Address]int), store: storeReader, broadcastPipe: broadcastPipe, eventPipe: eventPipe, } pool.logger = logger.NewSubLogger("_pool", pool) return pool } // SetNewSandboxAndRecheck updates the sandbox and rechecks all transactions, // removing transactions that are now invalid. func (p *txPool) SetNewSandboxAndRecheck(sbx sandbox.Sandbox) { p.lk.Lock() defer p.lk.Unlock() p.sbx = sbx p.logger.Debug("set new sandbox") var next *linkedlist.Element[linkedmap.Pair[tx.ID, *tx.Tx]] for _, pool := range p.pools { for e := pool.list.HeadNode(); e != nil; e = next { next = e.Next trx := e.Data.Value if err := p.checkTx(trx); err != nil { p.logger.Debug("invalid transaction after rechecking", "id", trx.ID()) pool.list.Remove(trx.ID()) } } } } // AppendTx validates the transaction and adds it to the transaction pool // without broadcasting it. func (p *txPool) AppendTx(trx *tx.Tx) error { p.lk.Lock() defer p.lk.Unlock() if err := p.checkTx(trx); err != nil { return err } if err := p.checkFee(trx); err != nil { return err } p.appendTx(trx) return nil } // AppendTxAndBroadcast validates the transaction, adds it to the transaction // pool if the fee is acceptable, and broadcasts it in any case. func (p *txPool) AppendTxAndBroadcast(trx *tx.Tx) error { p.lk.Lock() defer p.lk.Unlock() if err := p.checkTx(trx); err != nil { return err } err := p.checkFee(trx) if err == nil { p.appendTx(trx) } go func(t *tx.Tx) { msg := message.NewTransactionsMessage([]*tx.Tx{t}) p.broadcastPipe.Send(msg) p.eventPipe.Send(t) }(trx) return nil } func (p *txPool) appendTx(trx *tx.Tx) { payloadType := trx.Payload().Type() payloadPool := p.pools[payloadType] payloadPool.list.PushBack(trx.ID(), trx) p.logger.Debug("transaction appended into pool", "trx", trx) } func (p *txPool) checkFee(trx *tx.Tx) error { if !trx.IsFreeTx() { minFee := p.estimatedMinimumFee(trx) if trx.Fee() < minFee { p.logger.Warn("low fee transaction", "txs", trx, "minFee", minFee) return InvalidFeeError{ MinimumFee: minFee, } } } return nil } func (p *txPool) checkTx(trx *tx.Tx) error { if err := trx.BasicCheck(); err != nil { p.logger.Debug("invalid transaction", "trx", trx, "error", err) return err } if err := execution.CheckAndExecute(trx, p.sbx, false); err != nil { p.logger.Debug("invalid transaction", "trx", trx, "error", err) return err } return nil } func (p *txPool) EstimatedFee(_ amount.Amount, payloadType payload.Type) amount.Amount { selectedPool, ok := p.pools[payloadType] if !ok { return 0 } return selectedPool.estimatedFee() } func (p *txPool) HandleCommittedBlock(blk *block.Block) { p.lk.Lock() defer p.lk.Unlock() for _, trx := range blk.Transactions() { p.removeTx(trx.ID()) } if p.config.calculateConsumption() { p.increaseConsumption(blk) p.decreaseConsumption(blk.Height()) } } func (p *txPool) increaseConsumption(blk *block.Block) { // The first transaction is always the subsidy transaction. for _, trx := range blk.Transactions()[1:] { signer := trx.Payload().Signer() p.consumptionMap[signer] += trx.SerializeSize() } } func (p *txPool) decreaseConsumption(curHeight types.Height) { // If height is less than or equal to ConsumptionWindow, nothing to do. if curHeight <= types.Height(p.config.ConsumptionWindow) { return } // Calculate the block height that has passed out of the consumption window. windowedBlockHeight := curHeight.SafeDecrease(p.config.ConsumptionWindow) committedBlock, err := p.store.Block(windowedBlockHeight) if err != nil { p.logger.Error("failed to read block", "height", windowedBlockHeight, "err", err) return } blk, err := committedBlock.ToBlock() if err != nil { p.logger.Error("failed to parse block", "height", windowedBlockHeight, "err", err) return } for _, trx := range blk.Transactions()[1:] { signer := trx.Payload().Signer() if consumption, ok := p.consumptionMap[signer]; ok { // Decrease the consumption by the size of the transaction consumption -= trx.SerializeSize() if consumption <= 0 { // If the new value is zero, remove the signer from the consumptionMap delete(p.consumptionMap, signer) } else { // Otherwise, update the map with the new value p.consumptionMap[signer] = consumption } } } } func (p *txPool) removeTx(txID tx.ID) { for _, pool := range p.pools { if pool.list.Remove(txID) { break } } } // PendingTx searches the transaction pool and returns the associated // transaction. If it doesn't exist in the pool, it returns nil. func (p *txPool) PendingTx(txID tx.ID) *tx.Tx { p.lk.Lock() defer p.lk.Unlock() for _, pool := range p.pools { n := pool.list.GetNode(txID) if n != nil { return n.Data.Value } } return nil } func (p *txPool) PrepareBlockTransactions() block.Txs { trxs := make([]*tx.Tx, 0, p.Size()) p.lk.RLock() defer p.lk.RUnlock() // Appending one sortition transaction poolSortition := p.pools[payload.TypeSortition] for n := poolSortition.list.HeadNode(); n != nil; n = n.Next { trxs = append(trxs, n.Data.Value) } // Appending bond transactions poolBond := p.pools[payload.TypeBond] for n := poolBond.list.HeadNode(); n != nil; n = n.Next { trxs = append(trxs, n.Data.Value) } // Appending unbond transactions poolUnbond := p.pools[payload.TypeUnbond] for n := poolUnbond.list.HeadNode(); n != nil; n = n.Next { trxs = append(trxs, n.Data.Value) } // Appending withdraw transactions poolWithdraw := p.pools[payload.TypeWithdraw] for n := poolWithdraw.list.HeadNode(); n != nil; n = n.Next { trxs = append(trxs, n.Data.Value) } // Appending transfer transactions poolTransfer := p.pools[payload.TypeTransfer] for n := poolTransfer.list.HeadNode(); n != nil; n = n.Next { trxs = append(trxs, n.Data.Value) } poolBatchTransfer := p.pools[payload.TypeBatchTransfer] for n := poolBatchTransfer.list.HeadNode(); n != nil; n = n.Next { trxs = append(trxs, n.Data.Value) } return trxs } func (p *txPool) HasTx(txID tx.ID) bool { p.lk.RLock() defer p.lk.RUnlock() for _, pool := range p.pools { if pool.list.Has(txID) { return true } } return false } func (p *txPool) Size() int { p.lk.RLock() defer p.lk.RUnlock() return p.size() } func (p *txPool) size() int { size := 0 for _, pool := range p.pools { size += pool.list.Size() } return size } func (p *txPool) estimatedMinimumFee(trx *tx.Tx) amount.Amount { return p.fixedFee() + p.consumptionalFee(trx) } func (p *txPool) fixedFee() amount.Amount { return p.config.fixedFee() } // consumptionalFee calculates the dynamic fee based on the amount of data an // address consumes daily. func (p *txPool) consumptionalFee(trx *tx.Tx) amount.Amount { if !p.config.calculateConsumption() { return 0 } var consumption int signer := trx.Payload().Signer() txSize := trx.SerializeSize() if !p.store.HasPublicKey(signer) { consumption = p.config.Fee.DailyLimit } else { consumption = p.consumptionMap[signer] + txSize + p.getPendingConsumption(signer) } coefficient := consumption / p.config.Fee.DailyLimit consumptionalFee, _ := amount.NewAmount(float64(coefficient) * float64(consumption) * p.config.Fee.UnitPrice) return consumptionalFee } func (p *txPool) AllPendingTxs() []*tx.Tx { p.lk.RLock() defer p.lk.RUnlock() txs := make([]*tx.Tx, 0, p.size()) var next *linkedlist.Element[linkedmap.Pair[tx.ID, *tx.Tx]] for _, pool := range p.pools { for e := pool.list.HeadNode(); e != nil; e = next { next = e.Next trx := e.Data.Value txs = append(txs, trx) } } return txs } func (p *txPool) getPendingConsumption(signer crypto.Address) int { totalSize := int(0) // TODO: big o is "o(n * m)" var next *linkedlist.Element[linkedmap.Pair[tx.ID, *tx.Tx]] for _, pool := range p.pools { for e := pool.list.HeadNode(); e != nil; e = next { next = e.Next if e.Data.Value.Payload().Signer() == signer { totalSize += e.Data.Value.SerializeSize() } } } return totalSize } // LogString returns a concise string representation intended for use in logs. func (p *txPool) LogString() string { return fmt.Sprintf("{💸 %v💸 %v 🔐 %v 🔓 %v 🎯 %v 🧾 %v}", p.pools[payload.TypeTransfer].list.Size(), p.pools[payload.TypeBatchTransfer].list.Size(), p.pools[payload.TypeBond].list.Size(), p.pools[payload.TypeUnbond].list.Size(), p.pools[payload.TypeSortition].list.Size(), p.pools[payload.TypeWithdraw].list.Size(), ) } ================================================ FILE: txpool/txpool_mock.go ================================================ // Code generated by MockGen. DO NOT EDIT. // Source: txpool/interface.go // // Generated by this command: // // mockgen -source=txpool/interface.go -destination=txpool/txpool_mock.go -package=txpool // // Package txpool is a generated GoMock package. package txpool import ( reflect "reflect" sandbox "github.com/pactus-project/pactus/sandbox" amount "github.com/pactus-project/pactus/types/amount" block "github.com/pactus-project/pactus/types/block" tx "github.com/pactus-project/pactus/types/tx" payload "github.com/pactus-project/pactus/types/tx/payload" gomock "go.uber.org/mock/gomock" ) // MockReader is a mock of Reader interface. type MockReader struct { ctrl *gomock.Controller recorder *MockReaderMockRecorder isgomock struct{} } // MockReaderMockRecorder is the mock recorder for MockReader. type MockReaderMockRecorder struct { mock *MockReader } // NewMockReader creates a new mock instance. func NewMockReader(ctrl *gomock.Controller) *MockReader { mock := &MockReader{ctrl: ctrl} mock.recorder = &MockReaderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockReader) EXPECT() *MockReaderMockRecorder { return m.recorder } // AllPendingTxs mocks base method. func (m *MockReader) AllPendingTxs() []*tx.Tx { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AllPendingTxs") ret0, _ := ret[0].([]*tx.Tx) return ret0 } // AllPendingTxs indicates an expected call of AllPendingTxs. func (mr *MockReaderMockRecorder) AllPendingTxs() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllPendingTxs", reflect.TypeOf((*MockReader)(nil).AllPendingTxs)) } // EstimatedFee mocks base method. func (m *MockReader) EstimatedFee(amt amount.Amount, payloadType payload.Type) amount.Amount { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EstimatedFee", amt, payloadType) ret0, _ := ret[0].(amount.Amount) return ret0 } // EstimatedFee indicates an expected call of EstimatedFee. func (mr *MockReaderMockRecorder) EstimatedFee(amt, payloadType any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimatedFee", reflect.TypeOf((*MockReader)(nil).EstimatedFee), amt, payloadType) } // HasTx mocks base method. func (m *MockReader) HasTx(txID tx.ID) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasTx", txID) ret0, _ := ret[0].(bool) return ret0 } // HasTx indicates an expected call of HasTx. func (mr *MockReaderMockRecorder) HasTx(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasTx", reflect.TypeOf((*MockReader)(nil).HasTx), txID) } // PendingTx mocks base method. func (m *MockReader) PendingTx(txID tx.ID) *tx.Tx { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PendingTx", txID) ret0, _ := ret[0].(*tx.Tx) return ret0 } // PendingTx indicates an expected call of PendingTx. func (mr *MockReaderMockRecorder) PendingTx(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PendingTx", reflect.TypeOf((*MockReader)(nil).PendingTx), txID) } // PrepareBlockTransactions mocks base method. func (m *MockReader) PrepareBlockTransactions() block.Txs { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PrepareBlockTransactions") ret0, _ := ret[0].(block.Txs) return ret0 } // PrepareBlockTransactions indicates an expected call of PrepareBlockTransactions. func (mr *MockReaderMockRecorder) PrepareBlockTransactions() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrepareBlockTransactions", reflect.TypeOf((*MockReader)(nil).PrepareBlockTransactions)) } // Size mocks base method. func (m *MockReader) Size() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Size") ret0, _ := ret[0].(int) return ret0 } // Size indicates an expected call of Size. func (mr *MockReaderMockRecorder) Size() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Size", reflect.TypeOf((*MockReader)(nil).Size)) } // MockTxPool is a mock of TxPool interface. type MockTxPool struct { ctrl *gomock.Controller recorder *MockTxPoolMockRecorder isgomock struct{} } // MockTxPoolMockRecorder is the mock recorder for MockTxPool. type MockTxPoolMockRecorder struct { mock *MockTxPool } // NewMockTxPool creates a new mock instance. func NewMockTxPool(ctrl *gomock.Controller) *MockTxPool { mock := &MockTxPool{ctrl: ctrl} mock.recorder = &MockTxPoolMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockTxPool) EXPECT() *MockTxPoolMockRecorder { return m.recorder } // AllPendingTxs mocks base method. func (m *MockTxPool) AllPendingTxs() []*tx.Tx { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AllPendingTxs") ret0, _ := ret[0].([]*tx.Tx) return ret0 } // AllPendingTxs indicates an expected call of AllPendingTxs. func (mr *MockTxPoolMockRecorder) AllPendingTxs() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllPendingTxs", reflect.TypeOf((*MockTxPool)(nil).AllPendingTxs)) } // AppendTx mocks base method. func (m *MockTxPool) AppendTx(trx *tx.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppendTx", trx) ret0, _ := ret[0].(error) return ret0 } // AppendTx indicates an expected call of AppendTx. func (mr *MockTxPoolMockRecorder) AppendTx(trx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppendTx", reflect.TypeOf((*MockTxPool)(nil).AppendTx), trx) } // AppendTxAndBroadcast mocks base method. func (m *MockTxPool) AppendTxAndBroadcast(trx *tx.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppendTxAndBroadcast", trx) ret0, _ := ret[0].(error) return ret0 } // AppendTxAndBroadcast indicates an expected call of AppendTxAndBroadcast. func (mr *MockTxPoolMockRecorder) AppendTxAndBroadcast(trx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppendTxAndBroadcast", reflect.TypeOf((*MockTxPool)(nil).AppendTxAndBroadcast), trx) } // EstimatedFee mocks base method. func (m *MockTxPool) EstimatedFee(amt amount.Amount, payloadType payload.Type) amount.Amount { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EstimatedFee", amt, payloadType) ret0, _ := ret[0].(amount.Amount) return ret0 } // EstimatedFee indicates an expected call of EstimatedFee. func (mr *MockTxPoolMockRecorder) EstimatedFee(amt, payloadType any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimatedFee", reflect.TypeOf((*MockTxPool)(nil).EstimatedFee), amt, payloadType) } // HandleCommittedBlock mocks base method. func (m *MockTxPool) HandleCommittedBlock(blk *block.Block) { m.ctrl.T.Helper() m.ctrl.Call(m, "HandleCommittedBlock", blk) } // HandleCommittedBlock indicates an expected call of HandleCommittedBlock. func (mr *MockTxPoolMockRecorder) HandleCommittedBlock(blk any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleCommittedBlock", reflect.TypeOf((*MockTxPool)(nil).HandleCommittedBlock), blk) } // HasTx mocks base method. func (m *MockTxPool) HasTx(txID tx.ID) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasTx", txID) ret0, _ := ret[0].(bool) return ret0 } // HasTx indicates an expected call of HasTx. func (mr *MockTxPoolMockRecorder) HasTx(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasTx", reflect.TypeOf((*MockTxPool)(nil).HasTx), txID) } // PendingTx mocks base method. func (m *MockTxPool) PendingTx(txID tx.ID) *tx.Tx { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PendingTx", txID) ret0, _ := ret[0].(*tx.Tx) return ret0 } // PendingTx indicates an expected call of PendingTx. func (mr *MockTxPoolMockRecorder) PendingTx(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PendingTx", reflect.TypeOf((*MockTxPool)(nil).PendingTx), txID) } // PrepareBlockTransactions mocks base method. func (m *MockTxPool) PrepareBlockTransactions() block.Txs { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PrepareBlockTransactions") ret0, _ := ret[0].(block.Txs) return ret0 } // PrepareBlockTransactions indicates an expected call of PrepareBlockTransactions. func (mr *MockTxPoolMockRecorder) PrepareBlockTransactions() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrepareBlockTransactions", reflect.TypeOf((*MockTxPool)(nil).PrepareBlockTransactions)) } // SetNewSandboxAndRecheck mocks base method. func (m *MockTxPool) SetNewSandboxAndRecheck(sbx sandbox.Sandbox) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetNewSandboxAndRecheck", sbx) } // SetNewSandboxAndRecheck indicates an expected call of SetNewSandboxAndRecheck. func (mr *MockTxPoolMockRecorder) SetNewSandboxAndRecheck(sbx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetNewSandboxAndRecheck", reflect.TypeOf((*MockTxPool)(nil).SetNewSandboxAndRecheck), sbx) } // Size mocks base method. func (m *MockTxPool) Size() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Size") ret0, _ := ret[0].(int) return ret0 } // Size indicates an expected call of Size. func (mr *MockTxPoolMockRecorder) Size() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Size", reflect.TypeOf((*MockTxPool)(nil).Size)) } ================================================ FILE: txpool/txpool_test.go ================================================ package txpool import ( "testing" "time" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/execution" "github.com/pactus-project/pactus/execution/executor" "github.com/pactus-project/pactus/sandbox" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite pool *txPool sbx *sandbox.MockSandbox broadcastPipe pipeline.Pipeline[message.Message] eventPipe pipeline.Pipeline[any] } func testDefaultConfig() *Config { return DefaultConfig() } func testConsumptionalConfig() *Config { return &Config{ MaxSize: 10, ConsumptionWindow: 3, Fee: &FeeConfig{ FixedFee: 0, DailyLimit: 360, UnitPrice: 0.000005, }, } } func setup(t *testing.T, cfg *Config) *testData { t.Helper() ts := testsuite.NewTestSuiteFromSeed(t, 1776497511988844581) broadcastPipe := pipeline.New[message.Message](t.Context()) eventPipe := pipeline.New[any](t.Context()) sbx := sandbox.MockingSandbox(ts) config := testDefaultConfig() if cfg != nil { config = cfg } poolInt := NewTxPool(config, sbx.TestStore, broadcastPipe, eventPipe) poolInt.SetNewSandboxAndRecheck(sbx) pool := poolInt.(*txPool) assert.NotNil(t, pool) sbx.TestAcceptSortition = true randHeight := ts.RandHeight( testsuite.HeightWithMin(sbx.TestParams.UnbondInterval)) _ = sbx.TestStore.AddTestBlock(randHeight) return &testData{ TestSuite: ts, pool: pool, sbx: sbx, broadcastPipe: broadcastPipe, eventPipe: eventPipe, } } func (td *testData) shouldPublishTransaction(t *testing.T, txID tx.ID) { t.Helper() timer := time.NewTimer(1 * time.Second) for { select { case <-timer.C: require.Fail(t, "Publish transaction timeout") return case msg := <-td.broadcastPipe.UnsafeGetChannel(): logger.Info("shouldPublishTransaction", "msg", msg) if msg.Type() == message.TypeTransaction { m := msg.(*message.TransactionsMessage) assert.Equal(t, txID, m.Transactions[0].ID()) return } } } } // makeValidTransferTx makes a valid Transfer transaction for testing purpose. func (td *testData) makeValidTransferTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) trx := td.GenerateTestTransferTx(opts...) signer := trx.Payload().Signer() acc := td.sbx.MakeNewAccount(signer) acc.AddToBalance(trx.Payload().Value() + trx.Fee()) td.sbx.UpdateAccount(signer, acc) return trx } // makeValidBatchTransferTx make a valid Batch transfer transaction for test purpose. func (td *testData) makeValidBatchTransferTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) trx := td.GenerateTestBatchTransferTx(opts...) signer := trx.Payload().Signer() acc := td.sbx.MakeNewAccount(signer) acc.AddToBalance(trx.Payload().Value() + trx.Fee()) td.sbx.UpdateAccount(signer, acc) return trx } // makeValidSubsidyTx make a valid Batch transfer transaction for test purpose. func (td *testData) makeValidSubsidyTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) return td.GenerateTestSubsidyTx(opts...) } // makeValidBondTx makes a valid Bond transaction for testing purpose. func (td *testData) makeValidBondTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) trx := td.GenerateTestBondTx(opts...) signer := trx.Payload().Signer() acc := td.sbx.MakeNewAccount(signer) acc.AddToBalance(trx.Payload().Value() + trx.Fee()) td.sbx.UpdateAccount(signer, acc) return trx } // makeValidUnbondTx makes a valid Unbond transaction for testing purpose. // Ensure that the signer key is set through the opts. func (td *testData) makeValidUnbondTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) trx := td.GenerateTestUnbondTx(opts...) validatorPublicKey := trx.PublicKey().(*bls.PublicKey) val := td.sbx.MakeNewValidator(validatorPublicKey) td.sbx.UpdateValidator(val) return trx } // makeValidWithdrawTx makes a valid Withdraw transaction for testing purpose. // Ensure that the signer key is set through the opts. func (td *testData) makeValidWithdrawTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) trx := td.GenerateTestWithdrawTx(opts...) validatorPublicKey := trx.PublicKey().(*bls.PublicKey) val := td.sbx.MakeNewValidator(validatorPublicKey) val.AddToStake(trx.Payload().Value() + trx.Fee()) val.UpdateUnbondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.TestParams.UnbondInterval + 1)) td.sbx.UpdateValidator(val) return trx } // makeValidSortitionTx makes a valid Sortition transaction for testing purpose. // Ensure that the signer key is set through the opts. func (td *testData) makeValidSortitionTx(opts ...testsuite.TransactionMakerOption) *tx.Tx { opts = util.Prepend(opts, testsuite.TransactionWithLockTime(td.sbx.CurrentHeight())) trx := td.GenerateTestSortitionTx(opts...) validatorPublicKey := trx.PublicKey().(*bls.PublicKey) val := td.sbx.MakeNewValidator(validatorPublicKey) val.UpdateLastBondingHeight(td.sbx.CurrentHeight().SafeDecrease(td.sbx.TestParams.BondInterval + 1)) td.sbx.UpdateValidator(val) return trx } func TestAppendAndRemove(t *testing.T) { td := setup(t, nil) trx := td.makeValidTransferTx() require.NoError(t, td.pool.AppendTx(trx)) assert.True(t, td.pool.HasTx(trx.ID())) assert.Equal(t, trx, td.pool.PendingTx(trx.ID())) td.pool.removeTx(trx.ID()) assert.False(t, td.pool.HasTx(trx.ID()), "Transaction should be removed") assert.Nil(t, td.pool.PendingTx(trx.ID())) } func TestAppendSameTransaction(t *testing.T) { td := setup(t, nil) trx := td.makeValidTransferTx() err := td.pool.AppendTx(trx) require.NoError(t, err) err = td.pool.AppendTx(trx) require.ErrorIs(t, err, execution.TransactionCommittedError{ID: trx.ID()}) } func TestDisableConsumption(t *testing.T) { td := setup(t, testDefaultConfig()) trx := td.GenerateTestTransferTx() assert.Zero(t, td.pool.consumptionalFee(trx)) } func TestCalculatingConsumption(t *testing.T) { td := setup(t, testConsumptionalConfig()) // Generate keys for different transaction signers _, prv1 := td.RandEd25519KeyPair() pub2, prv2 := td.RandEd25519KeyPair() pub3, prv3 := td.RandBLSKeyPair() pub4, prv4 := td.RandBLSKeyPair() // Generate different types of transactions trx10 := td.makeValidSubsidyTx() trx11 := td.makeValidTransferTx(testsuite.TransactionWithSigner(prv1)) trx12 := td.makeValidBondTx(testsuite.TransactionWithSigner(prv2)) trx13 := td.makeValidUnbondTx(testsuite.TransactionWithSigner(prv4)) trx20 := td.makeValidSubsidyTx() trx21 := td.makeValidTransferTx(testsuite.TransactionWithSigner(prv1)) trx30 := td.makeValidSubsidyTx() trx31 := td.makeValidBondTx(testsuite.TransactionWithSigner(prv3)) trx32 := td.makeValidSortitionTx(testsuite.TransactionWithSigner(prv4)) trx40 := td.makeValidSubsidyTx() trx41 := td.makeValidUnbondTx(testsuite.TransactionWithSigner(prv3)) trx42 := td.makeValidTransferTx(testsuite.TransactionWithSigner(prv2)) trx50 := td.makeValidSubsidyTx() trx51 := td.makeValidWithdrawTx(testsuite.TransactionWithSigner(prv3)) trx52 := td.makeValidTransferTx(testsuite.TransactionWithSigner(prv2)) trx53 := td.makeValidBatchTransferTx(testsuite.TransactionWithSigner(prv2)) // Commit the first block blk1, cert1 := td.GenerateTestBlock(1, testsuite.BlockWithTransactions([]*tx.Tx{trx10, trx11, trx12, trx13})) td.sbx.TestStore.SaveBlock(blk1, cert1) // Expected consumption map after transactions diff2 := 0 if trx42.SerializeSize() > trx12.SerializeSize() { diff2 = trx42.SerializeSize() - trx12.SerializeSize() } expected := map[crypto.Address]int{ pub2.AccountAddress(): trx52.SerializeSize() + trx53.SerializeSize() + diff2, pub3.AccountAddress(): trx31.SerializeSize(), pub3.ValidatorAddress(): trx41.SerializeSize() + trx51.SerializeSize(), pub4.ValidatorAddress(): trx32.SerializeSize() - trx13.SerializeSize(), } tests := []struct { height types.Height txs []*tx.Tx }{ {2, []*tx.Tx{trx20, trx21}}, {3, []*tx.Tx{trx30, trx31, trx32}}, {4, []*tx.Tx{trx40, trx41, trx42}}, {5, []*tx.Tx{trx50, trx51, trx52, trx53}}, } for _, tt := range tests { // Generate a block with the transactions for the given height blk, cert := td.GenerateTestBlock(tt.height, testsuite.BlockWithTransactions(tt.txs)) td.sbx.TestStore.SaveBlock(blk, cert) // Handle the block in the transaction pool td.pool.HandleCommittedBlock(blk) t.Logf("consumption Map: %v\n", td.pool.consumptionMap) } require.Equal(t, expected, td.pool.consumptionMap) } func TestEstimatedConsumptionalFee(t *testing.T) { td := setup(t, testConsumptionalConfig()) t.Run("Test indexed signer", func(t *testing.T) { _, accPrv := td.RandEd25519KeyPair() trx := td.makeValidTransferTx(testsuite.TransactionWithSigner(accPrv)) blk, cert := td.GenerateTestBlock(td.RandHeight(), testsuite.BlockWithTransactions([]*tx.Tx{trx})) td.sbx.TestStore.SaveBlock(blk, cert) tests := []struct { fee amount.Amount withErr bool }{ {0, false}, {0, false}, {2_310_000, false}, {3_090_000, false}, {7_740_000, false}, {9_300_000, false}, {0, true}, } for _, tt := range tests { testTrx := td.makeValidTransferTx( testsuite.TransactionWithSigner(accPrv), testsuite.TransactionWithFee(tt.fee)) err := td.pool.AppendTx(testTrx) if tt.withErr { require.Error(t, err) } else { require.NoError(t, err) } } }) t.Run("Test non-indexed signer", func(t *testing.T) { trx := td.makeValidTransferTx(testsuite.TransactionWithFee(0)) err := td.pool.AppendTx(trx) require.Error(t, err) }) } func TestAppendInvalidTransaction(t *testing.T) { td := setup(t, nil) t.Run("basic check error", func(t *testing.T) { trx := td.makeValidTransferTx() trx.SetSignature(nil) err := td.pool.AppendTx(trx) require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "no signature", }) }) t.Run("execution error", func(t *testing.T) { invTrx := td.GenerateTestTransferTx() err := td.pool.AppendTx(invTrx) require.ErrorIs(t, err, executor.AccountNotFoundError{ Address: invTrx.Payload().Signer(), }) }) } // TestFullPool tests if the pool prunes the old transactions when it is full. func TestFullPool(t *testing.T) { conf := testDefaultConfig() conf.MaxSize = 10 td := setup(t, conf) trxs := make([]*tx.Tx, td.pool.config.transferPoolSize()+1) // Make sure the pool is empty assert.Equal(t, 0, td.pool.Size()) for i := 0; i < len(trxs); i++ { trx := td.makeValidTransferTx() require.NoError(t, td.pool.AppendTx(trx)) trxs[i] = trx } assert.False(t, td.pool.HasTx(trxs[0].ID())) assert.True(t, td.pool.HasTx(trxs[1].ID())) assert.Equal(t, td.pool.config.transferPoolSize(), td.pool.Size()) } func TestEmptyPool(t *testing.T) { td := setup(t, nil) trxs := td.pool.AllPendingTxs() assert.Empty(t, trxs, "pool should be empty") } func TestPrepareBlockTransactions(t *testing.T) { td := setup(t, nil) pub1, _ := td.RandBLSKeyPair() _, prv2 := td.RandBLSKeyPair() _, prv3 := td.RandBLSKeyPair() _, prv4 := td.RandBLSKeyPair() _, prv5 := td.RandBLSKeyPair() transferTx := td.makeValidTransferTx() bondTx := td.makeValidBondTx(testsuite.TransactionWithValidatorPublicKey(pub1)) unbondTx := td.makeValidUnbondTx(testsuite.TransactionWithSigner(prv2)) withdrawTx := td.makeValidWithdrawTx(testsuite.TransactionWithSigner(prv3)) sortitionTx := td.makeValidSortitionTx(testsuite.TransactionWithSigner(prv4)) batchTransferTx := td.makeValidBatchTransferTx(testsuite.TransactionWithSigner(prv5)) require.NoError(t, td.pool.AppendTx(transferTx)) require.NoError(t, td.pool.AppendTx(unbondTx)) require.NoError(t, td.pool.AppendTx(withdrawTx)) require.NoError(t, td.pool.AppendTx(bondTx)) require.NoError(t, td.pool.AppendTx(sortitionTx)) require.NoError(t, td.pool.AppendTx(batchTransferTx)) trxs := td.pool.PrepareBlockTransactions() assert.Len(t, trxs, 6) assert.Equal(t, sortitionTx.ID(), trxs[0].ID()) assert.Equal(t, bondTx.ID(), trxs[1].ID()) assert.Equal(t, unbondTx.ID(), trxs[2].ID()) assert.Equal(t, withdrawTx.ID(), trxs[3].ID()) assert.Equal(t, transferTx.ID(), trxs[4].ID()) assert.Equal(t, batchTransferTx.ID(), trxs[5].ID()) } func TestAddSubsidyTransactions(t *testing.T) { t.Run("invalid transaction: Should return error", func(t *testing.T) { td := setup(t, nil) randHeight := td.RandHeight() td.sbx.TestStore.AddTestBlock(randHeight) trx := td.makeValidSubsidyTx(testsuite.TransactionWithLockTime(randHeight)) err := td.pool.AppendTx(trx) require.ErrorIs(t, err, execution.LockTimeExpiredError{ LockTime: randHeight, }) }) t.Run("valid transaction: Should add it to the pool", func(t *testing.T) { td := setup(t, nil) randHeight := td.RandHeight() td.sbx.TestStore.AddTestBlock(randHeight) trx := td.makeValidSubsidyTx(testsuite.TransactionWithLockTime(randHeight + 1)) err := td.pool.AppendTx(trx) require.NoError(t, err) }) } func TestRecheckTransactions(t *testing.T) { td := setup(t, nil) trx := td.makeValidSubsidyTx() err := td.pool.AppendTx(trx) require.NoError(t, err) assert.Equal(t, 1, td.pool.Size()) td.pool.SetNewSandboxAndRecheck(td.sbx) assert.Equal(t, 0, td.pool.Size()) } func TestAppendAndBroadcast(t *testing.T) { t.Run("Invalid transaction: Should return error", func(t *testing.T) { td := setup(t, nil) invTrx := td.GenerateTestTransferTx() require.Error(t, td.pool.AppendTxAndBroadcast(invTrx)) }) t.Run("Valid transaction with valid fee: Should add to pool and broadcast", func(t *testing.T) { td := setup(t, nil) trx := td.makeValidTransferTx() err := td.pool.AppendTxAndBroadcast(trx) require.NoError(t, err) assert.Equal(t, 1, td.pool.Size()) td.shouldPublishTransaction(t, trx.ID()) }) t.Run("Valid transaction with zero fee: Should broadcast but not add to the pool", func(t *testing.T) { td := setup(t, nil) trx := td.makeValidTransferTx(testsuite.TransactionWithFee(0)) err := td.pool.AppendTxAndBroadcast(trx) require.NoError(t, err) assert.Zero(t, td.pool.Size()) td.shouldPublishTransaction(t, trx.ID()) }) } func TestAllPendingTxs(t *testing.T) { td := setup(t, nil) trxs := td.pool.AllPendingTxs() assert.Empty(t, trxs, "%+v", 0) pub1, _ := td.RandBLSKeyPair() _, prv2 := td.RandBLSKeyPair() transferTx := td.makeValidTransferTx() bondTx := td.makeValidBondTx(testsuite.TransactionWithValidatorPublicKey(pub1)) unbondTx := td.makeValidUnbondTx() withdrawTx := td.makeValidWithdrawTx() sortitionTx := td.makeValidSortitionTx(testsuite.TransactionWithSigner(prv2)) batchTransferTx := td.makeValidBatchTransferTx() require.NoError(t, td.pool.AppendTx(transferTx)) require.NoError(t, td.pool.AppendTx(bondTx)) require.NoError(t, td.pool.AppendTx(unbondTx)) require.NoError(t, td.pool.AppendTx(withdrawTx)) require.NoError(t, td.pool.AppendTx(sortitionTx)) require.NoError(t, td.pool.AppendTx(batchTransferTx)) trxs = td.pool.AllPendingTxs() assert.Len(t, trxs, 6) } func TestEstimatedFee(t *testing.T) { td := setup(t, nil) estimatedFee := td.pool.EstimatedFee(td.RandAmount(), payload.TypeTransfer) assert.Equal(t, td.pool.config.fixedFee(), estimatedFee) } ================================================ FILE: types/account/account.go ================================================ // Package account provides functionality for managing account information. package account import ( "bytes" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/encoding" ) // The Account struct represents an account object. type Account struct { data accountData } // accountData contains the data associated with an account. type accountData struct { Number int32 Balance amount.Amount } // NewAccount constructs a new account from the given number. func NewAccount(number int32) *Account { return &Account{ data: accountData{ Number: number, }, } } // FromBytes constructs a new account from raw byte data. func FromBytes(data []byte) (*Account, error) { acc := new(Account) r := bytes.NewReader(data) err := encoding.ReadElements(r, &acc.data.Number, &acc.data.Balance) if err != nil { return nil, err } return acc, nil } // Number returns the number of the account. func (acc Account) Number() int32 { return acc.data.Number } // Balance returns the balance of the account. func (acc Account) Balance() amount.Amount { return acc.data.Balance } // SubtractFromBalance subtracts the given amount from the account's balance. func (acc *Account) SubtractFromBalance(amt amount.Amount) { acc.data.Balance -= amt } // AddToBalance adds the given amount to the account's balance. func (acc *Account) AddToBalance(amt amount.Amount) { acc.data.Balance += amt } // Hash calculates and returns the hash of the account. func (acc *Account) Hash() hash.Hash { bs, err := acc.Bytes() if err != nil { panic(err) } return hash.CalcHash(bs) } // SerializeSize returns the size in bytes required to serialize the account. func (*Account) SerializeSize() int { return 12 // 4+8 } // Bytes returns the serialized byte representation of the account. func (acc *Account) Bytes() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, acc.SerializeSize())) err := encoding.WriteElements(buf, acc.data.Number, acc.data.Balance) if err != nil { return nil, err } return buf.Bytes(), nil } // Clone creates a deep copy of the account. func (acc *Account) Clone() *Account { cloned := new(Account) *cloned = *acc return cloned } ================================================ FILE: types/account/account_test.go ================================================ package account_test import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFromBytes(t *testing.T) { ts := testsuite.NewTestSuite(t) acc, _ := ts.GenerateTestAccount() bs, err := acc.Bytes() require.NoError(t, err) require.Equal(t, len(bs), acc.SerializeSize()) acc2, err := account.FromBytes(bs) require.NoError(t, err) assert.Equal(t, acc, acc2) _, err = account.FromBytes([]byte("asdfghjkl")) require.Error(t, err) } func TestDecoding(t *testing.T) { data, _ := hex.DecodeString( "01000000" + // number "0200000000000000") // balance acc, err := account.FromBytes(data) require.NoError(t, err) assert.Equal(t, int32(1), acc.Number()) assert.Equal(t, amount.Amount(2), acc.Balance()) accData, _ := acc.Bytes() assert.Equal(t, data, accData) assert.Equal(t, hash.CalcHash(data), acc.Hash()) expected, _ := hash.FromString("c3b75f08e64a66cb980fdc03c3a0b78635a7b1db049096e8bbbd9a2873f3071a") assert.Equal(t, expected, acc.Hash()) assert.Equal(t, len(data), acc.SerializeSize()) } func TestAddToBalance(t *testing.T) { ts := testsuite.NewTestSuite(t) acc, _ := ts.GenerateTestAccount() bal := acc.Balance() acc.AddToBalance(1) assert.Equal(t, bal+1, acc.Balance()) } func TestSubtractFromBalance(t *testing.T) { ts := testsuite.NewTestSuite(t) acc, _ := ts.GenerateTestAccount() bal := acc.Balance() acc.SubtractFromBalance(1) assert.Equal(t, bal-1, acc.Balance()) } func TestClone(t *testing.T) { ts := testsuite.NewTestSuite(t) acc, _ := ts.GenerateTestAccount() cloned := acc.Clone() cloned.AddToBalance(1) assert.Equal(t, acc.Number(), cloned.Number()) assert.NotEqual(t, acc.Balance(), cloned.Balance()) } ================================================ FILE: types/amount/amount.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package amount import ( "database/sql/driver" "errors" "math" "strconv" "strings" "github.com/pactus-project/pactus/util" ) const ( // NanoPACPerPAC is the number of NanoPAC in one PAC. NanoPACPerPAC = 1e9 // MaxNanoPAC is the maximum transaction amount allowed in NanoPAC. MaxNanoPAC = 42e6 * NanoPACPerPAC ) // Unit describes a method of converting an Amount to something // other than the base unit of PAC. The value of the Unit // is the exponent component of the decimal multiple to convert from // an amount in PAC to an amount counted in units. type Unit int // These constants define various units used when describing a Pactus // monetary amount. const ( UnitMegaPAC Unit = 6 UnitKiloPAC Unit = 3 UnitPAC Unit = 0 UnitMilliPAC Unit = -3 UnitMicroPAC Unit = -6 UnitNanoPAC Unit = -9 ) // String returns the unit as a string. For recognized units, the SI // prefix is used, or "NanoPAC" for the base unit. For all unrecognized // units, "1eN PAC" is returned, where N is the Unit. func (u Unit) String() string { switch u { case UnitMegaPAC: return "MPAC" case UnitKiloPAC: return "kPAC" case UnitPAC: return "PAC" case UnitMilliPAC: return "mPAC" case UnitMicroPAC: return "μPAC" case UnitNanoPAC: return "NanoPAC" default: return "1e" + strconv.FormatInt(int64(u), 10) + " PAC" } } // Amount represents the atomic unit in Pactus blockchain. // Each unit equals 1e-9 of a PAC. type Amount int64 // round converts a floating point number, which may or may not be representable // as an integer, to the Amount integer type by rounding to the nearest integer. // This is performed by adding or subtracting 0.5 depending on the sign, and // relying on integer truncation to round the value to the nearest Amount. func round(f float64) Amount { if f < 0 { return Amount(f - 0.5) } return Amount(f + 0.5) } // NewAmount creates an Amount from a floating-point value representing // an amount in PAC. NewAmount returns an error if f is NaN or +-Infinity, // but it does not check whether the amount is within the total amount of PAC // producible, as it may not refer to an amount at a single moment in time. // // NewAmount is specifically for converting PAC to NanoPAC. // For creating a new Amount with an int64 value which denotes a quantity of NanoPAC, // do a simple type conversion from type int64 to Amount. func NewAmount(pac float64) (Amount, error) { // The amount is only considered invalid if it cannot be represented // as an integer type. This may happen if f is NaN or +-Infinity. switch { case math.IsNaN(pac), math.IsInf(pac, 1), math.IsInf(pac, -1): return 0, errors.New("invalid PAC amount") } return round(pac * float64(NanoPACPerPAC)), nil } // FromString parses a string representing a value in PAC. // It then uses NewAmount to create an Amount based on the parsed // floating-point value. // If the parsing of the string fails, it returns an error. // TODO: Parse Unit and remove delimiters... func FromString(str string) (Amount, error) { str = strings.Replace(str, "PAC", "", 1) str = strings.TrimSpace(str) f, err := strconv.ParseFloat(str, 64) if err != nil { return 0, err } return NewAmount(f) } // ToUnit converts a monetary amount counted in NanoPAC (base units) to a // floating-point value representing an amount in the specified unit. func (a Amount) ToUnit(u Unit) float64 { return float64(a) / math.Pow10(int(u+9)) } // ToPAC is equivalent to calling ToUnit with UnitPAC. func (a Amount) ToPAC() float64 { return a.ToUnit(UnitPAC) } // ToNanoPAC returns the amount of NanoPAC (atomic units) as a 64-bit integer. func (a Amount) ToNanoPAC() int64 { return int64(a) } // formatOptions holds options for formatting amounts. type formatOptions struct { unit Unit WithUnit bool withDelimiters bool } // FormatOption is a function that configures formatting options. type FormatOption func(*formatOptions) // WithUnit sets the unit for formatting. func WithUnit(u Unit) FormatOption { return func(opts *formatOptions) { opts.unit = u opts.WithUnit = true } } // WithDelimiters enables delimiter formatting (e.g., "1,234.56"). func WithDelimiters() FormatOption { return func(opts *formatOptions) { opts.withDelimiters = true } } // Format formats a monetary amount counted in Pactus base units as a // string for a given unit. The conversion will succeed for any unit, // however, known units will be formatted with an appended label describing // the units with SI notation, and "NanoPAC" for the base unit. // // Format accepts options: // - WithUnit(u Unit): sets the unit for formatting (defaults to no unit) // - WithDelimiters(): enables comma delimiters in the formatted number (defaults to false) func (a Amount) Format(opts ...FormatOption) string { options := &formatOptions{} // Apply options for _, opt := range opts { opt(options) } precision := -int(options.unit + 9) value := a.ToUnit(options.unit) var formatted string if options.withDelimiters { formatted = util.FormatFloatWithDelimiters(value, precision) } else { formatted = strconv.FormatFloat(value, 'f', precision, 64) } if options.WithUnit { formatted += " " + options.unit.String() } return formatted } // String is the equivalent of calling Format with UnitPAC. func (a Amount) String() string { return a.Format(WithUnit(UnitPAC), WithDelimiters()) } // MulF64 multiplies an Amount by a floating point value. func (a Amount) MulF64(f float64) Amount { return round(float64(a) * f) } // Scan implements the sql.Scanner interface for SQL database operations. // It accepts int64 values representing NanoPAC and converts them to Amount. func (a *Amount) Scan(src any) error { switch v := src.(type) { case int64: *a = Amount(v) return nil default: return ErrInvalidSQLType } } // Value implements the driver.Valuer interface for SQL database operations. // It returns the Amount as NanoPAC (int64) to avoid floating-point precision issues. func (a Amount) Value() (driver.Value, error) { return int64(a), nil } ================================================ FILE: types/amount/amount_test.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package amount_test import ( "math" "strconv" "testing" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAmountCreation(t *testing.T) { tests := []struct { name string amount float64 valid bool expected amount.Amount }{ // Positive tests. { name: "zero", amount: 0, valid: true, expected: 0, }, { name: "max producible", amount: 42e6, valid: true, expected: amount.MaxNanoPAC, }, { name: "min producible", amount: -42e6, valid: true, expected: -amount.MaxNanoPAC, }, { name: "exceeds max producible", amount: 42e6 + 8e-9, valid: true, expected: amount.MaxNanoPAC + 8, }, { name: "exceeds min producible", amount: -42e6 - 8e-9, valid: true, expected: -amount.MaxNanoPAC - 8, }, { name: "one hundred", amount: 100, valid: true, expected: 100 * amount.NanoPACPerPAC, }, { name: "fraction", amount: 0.012345678, valid: true, expected: 12345678, }, { name: "rounding up", amount: 54.999999999999943157, valid: true, expected: 55 * amount.NanoPACPerPAC, }, { name: "rounding down", amount: 55.000000000000056843, valid: true, expected: 55 * amount.NanoPACPerPAC, }, // Negative tests. { name: "not-a-number", amount: math.NaN(), valid: false, }, { name: "-infinity", amount: math.Inf(-1), valid: false, }, { name: "+infinity", amount: math.Inf(1), valid: false, }, } for _, tt := range tests { amt, err := amount.NewAmount(tt.amount) if tt.valid { require.NoErrorf(t, err, "%v: Positive test Amount creation failed with: %v", tt.name, err) } else { require.Errorf(t, err, "%v: Negative test Amount creation succeeded (value %v) when should fail", tt.name, amt) } assert.Equal(t, tt.expected, amt, "%v: Created amount %v does not match expected %v", tt.name, amt, tt.expected) } } func TestAmountUnitConversions(t *testing.T) { tests := []struct { name string amount amount.Amount unit amount.Unit converted float64 str string }{ { name: "MPAC", amount: amount.MaxNanoPAC, unit: amount.UnitMegaPAC, converted: 42, str: "42 MPAC", }, { name: "kPAC", amount: 444_333_222_111_000, unit: amount.UnitKiloPAC, converted: 444.333_222_111_000, str: "444.333222111 kPAC", }, { name: "PAC", amount: 444_333_222_111_000, unit: amount.UnitPAC, converted: 444_333.222_111, str: "444,333.222111 PAC", }, { name: "a thousand NanoPAC as PAC", amount: 1_000, unit: amount.UnitPAC, converted: 0.000_001, str: "0.000001 PAC", }, { name: "a single NanoPAC as PAC", amount: 1, unit: amount.UnitPAC, converted: 0.000_000_001, str: "0.000000001 PAC", }, { name: "amount with trailing zero but no decimals", amount: 10_000_000_000, unit: amount.UnitPAC, converted: 10, str: "10 PAC", }, { name: "mPAC", amount: 444_333_222_111_000, unit: amount.UnitMilliPAC, converted: 444_333_222.111_000, str: "444,333,222.111 mPAC", }, { name: "μPAC", amount: 444_333_222_111_000, unit: amount.UnitMicroPAC, converted: 444_333_222_111.000, str: "444,333,222,111 μPAC", }, { name: "NanoPAC", amount: 444_333_222_111_000, unit: amount.UnitNanoPAC, converted: 444_333_222_111_000, str: "444,333,222,111,000 NanoPAC", }, { name: "non-standard unit", amount: 444_333_222_111_000, unit: amount.Unit(-1), converted: 4_443_332.221_110_00, str: "4,443,332.22111 1e-1 PAC", }, } for _, tt := range tests { f := tt.amount.ToUnit(tt.unit) assert.InDelta(t, tt.converted, f, 0.00001, "%v: converted value %v does not match expected %v", tt.name, f, tt.converted) str := tt.amount.Format(amount.WithUnit(tt.unit), amount.WithDelimiters()) assert.Equal(t, tt.str, str, "%v: format '%v' does not match expected '%v'", tt.name, str, tt.str) // Verify that Amount.ToPAC works as advertised. f1 := tt.amount.ToUnit(amount.UnitPAC) f2 := tt.amount.ToPAC() assert.InDelta(t, f1, f2, 0.00001, "%v: ToPAC does not match ToUnit(AmountPAC): %v != %v", tt.name, f1, f2) // Verify that Amount.String works as advertised. s1 := tt.amount.Format(amount.WithUnit(amount.UnitPAC), amount.WithDelimiters()) s2 := tt.amount.String() assert.Equal(t, s1, s2, "%v: String does not match Format(AmountPac): %v != %v", tt.name, s1, s2) } } func TestFormatOptions(t *testing.T) { tests := []struct { name string amt amount.Amount opts []amount.FormatOption expected string }{ { name: "default", amt: 123456e7, opts: []amount.FormatOption{}, expected: "1234.56", }, { name: "with unit", amt: 123456e7, opts: []amount.FormatOption{amount.WithUnit(amount.UnitPAC)}, expected: "1234.56 PAC", }, { name: "with delimiters", amt: 123456e7, opts: []amount.FormatOption{amount.WithDelimiters()}, expected: "1,234.56", }, { name: "with unit and delimiters", amt: 123456e7, opts: []amount.FormatOption{amount.WithUnit(amount.UnitPAC), amount.WithDelimiters()}, expected: "1,234.56 PAC", }, } for _, tt := range tests { assert.Equal(t, tt.expected, tt.amt.Format(tt.opts...), "%v: Format does not match expected %v", tt.name, tt.expected) } } func TestAmountMulF64(t *testing.T) { tests := []struct { name string amt amount.Amount mul float64 res amount.Amount }{ { name: "Multiply 0.1 PAC by 2", amt: 100e6, // 0.1 PAC mul: 2, res: 200e6, // 0.2 PAC }, { name: "Multiply 0.2 PAC by 0.02", amt: 200e6, // 0.2 PAC mul: 1.02, res: 204e6, // 0.204 PAC }, { name: "Multiply 0.1 PAC by -2", amt: 100e6, // 0.1 PAC mul: -2, res: -200e6, // -0.2 PAC }, { name: "Multiply 0.2 PAC by -0.02", amt: 200e6, // 0.2 PAC mul: -1.02, res: -204e6, // -0.204 PAC }, { name: "Multiply -0.1 PAC by 2", amt: -100e6, // -0.1 PAC mul: 2, res: -200e6, // -0.2 PAC }, { name: "Multiply -0.2 PAC by 0.02", amt: -200e6, // -0.2 PAC mul: 1.02, res: -204e6, // -0.204 PAC }, { name: "Multiply -0.1 PAC by -2", amt: -100e6, // -0.1 PAC mul: -2, res: 200e6, // 0.2 PAC }, { name: "Multiply -0.2 PAC by -0.02", amt: -200e6, // -0.2 PAC mul: -1.02, res: 204e6, // 0.204 PAC }, { name: "Round down", amt: 49, // 49 NanoPACs mul: 0.01, res: 0, }, { name: "Round up", amt: 50, // 50 NanoPACs mul: 0.01, res: 1, // 1 NanoPAC }, { name: "Multiply by 0", amt: 1e9, // 1 PAC mul: 0, res: 0, // 0 PAC }, { name: "Multiply 1 by 0.5", amt: 1, // 1 NanoPAC mul: 0.5, res: 1, // 1 NanoPAC }, { name: "Multiply 100 by 66%", amt: 100, // 100 NanoPACs mul: 0.66, res: 66, // 66 NanoPACs }, { name: "Multiply 100 by 66.6%", amt: 100, // 100 NanoPACs mul: 0.666, res: 67, // 67 NanoPACs }, { name: "Multiply 100 by 2/3", amt: 100, // 100 NanoPACs mul: 2.0 / 3, res: 67, // 67 NanoPACs }, } for _, tt := range tests { a := tt.amt.MulF64(tt.mul) if a != tt.res { t.Errorf("%v: expected %v got %v", tt.name, tt.res, a) } } } func TestFromString(t *testing.T) { tests := []struct { amount string PAC float64 NanoPac int64 str string parsErr error }{ {"0", 0, 0, "0 PAC", nil}, {"1", 1, 1000000000, "1 PAC", nil}, {"1 PAC", 1, 1000000000, "1 PAC", nil}, {"123.123", 123.123, 123123000000, "123.123 PAC", nil}, {"123.0123", 123.0123, 123012300000, "123.0123 PAC", nil}, {"123.01230", 123.0123, 123012300000, "123.0123 PAC", nil}, {"123.000123", 123.000123, 123000123000, "123.000123 PAC", nil}, {"123.000000123", 123.000000123, 123000000123, "123.000000123 PAC", nil}, {"-123.000000123", -123.000000123, -123000000123, "-123.000000123 PAC", nil}, {"0123.000000123", 123.000000123, 123000000123, "123.000000123 PAC", nil}, {"+123.000000123", 123.000000123, 123000000123, "123.000000123 PAC", nil}, {"123.0000001234", 123.000000123, 123000000123, "123.000000123 PAC", nil}, {"1coin", 0, 0, "0", strconv.ErrSyntax}, } for _, tt := range tests { amt, err := amount.FromString(tt.amount) if tt.parsErr == nil { require.NoError(t, err) assert.Equal(t, tt.NanoPac, amt.ToNanoPAC()) assert.InDelta(t, tt.PAC, amt.ToPAC(), 0.00001) assert.Equal(t, tt.str, amt.String()) } else { require.ErrorIs(t, err, tt.parsErr) } } } func TestSQLDriver(t *testing.T) { t.Run("Value returns int64", func(t *testing.T) { amt := amount.Amount(123456000000) val, err := amt.Value() require.NoError(t, err) assert.IsType(t, int64(0), val) assert.Equal(t, int64(123456000000), val.(int64)) }) t.Run("Scan from int64 succeeds", func(t *testing.T) { var amt amount.Amount err := amt.Scan(int64(123456000000)) require.NoError(t, err) assert.Equal(t, int64(123456000000), amt.ToNanoPAC()) }) t.Run("Scan from nil fails", func(t *testing.T) { var amt amount.Amount err := amt.Scan(nil) require.ErrorIs(t, err, amount.ErrInvalidSQLType) }) t.Run("Scan from float64 fails", func(t *testing.T) { var amt amount.Amount err := amt.Scan(123.456) require.ErrorIs(t, err, amount.ErrInvalidSQLType) }) t.Run("Round trip Value and Scan", func(t *testing.T) { original := amount.Amount(util.RandInt64(1000e9)) val, err := original.Value() require.NoError(t, err) var scanned amount.Amount err = scanned.Scan(val) require.NoError(t, err) assert.Equal(t, original.ToNanoPAC(), scanned.ToNanoPAC()) }) } ================================================ FILE: types/amount/errors.go ================================================ package amount import ( "errors" ) // ErrInvalidSQLType is returned when the type of the data // is not supported for SQL database operations. var ErrInvalidSQLType = errors.New("invalid SQL type") ================================================ FILE: types/block/block.go ================================================ package block import ( "bytes" "encoding/hex" "fmt" "io" "time" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/encoding" ) type Block struct { memorizedHash *hash.Hash memorizedData []byte data blockData } type blockData struct { Header *Header PrevCert *certificate.Certificate Txs Txs } func NewBlock(header *Header, prevCert *certificate.Certificate, txs Txs) *Block { return &Block{ data: blockData{ Header: header, PrevCert: prevCert, Txs: txs, }, } } // FromString constructs a new block from a hex-encoded string. func FromString(str string) (*Block, error) { bs, err := hex.DecodeString(str) if err != nil { return nil, err } return FromBytes(bs) } // FromBytes constructs a new block from raw byte data. func FromBytes(data []byte) (*Block, error) { blk := new(Block) reader := bytes.NewReader(data) if err := blk.Decode(reader); err != nil { return nil, err } return blk, nil } func MakeBlock(version protocol.Version, timestamp time.Time, txs Txs, prevBlockHash, stateRoot hash.Hash, prevCert *certificate.Certificate, sortitionSeed sortition.VerifiableSeed, proposer crypto.Address, ) *Block { header := NewHeader(version, timestamp, stateRoot, prevBlockHash, sortitionSeed, proposer) return NewBlock(header, prevCert, txs) } func (b *Block) Header() *Header { return b.data.Header } func (b *Block) PrevCertificate() *certificate.Certificate { return b.data.PrevCert } func (b *Block) Transactions() Txs { return b.data.Txs } // BasicCheck performs basic validation checks on the block structure and its contents. func (b *Block) BasicCheck() error { if err := b.Header().BasicCheck(); err != nil { return err } if b.Transactions().Len() == 0 { // block at least should have one transaction return BasicCheckError{ Reason: "no subsidy transaction", } } if b.Transactions().Len() > 1000 { return BasicCheckError{ Reason: "block is full", } } if b.PrevCertificate() != nil { if err := b.PrevCertificate().BasicCheck(); err != nil { return BasicCheckError{ Reason: fmt.Sprintf("invalid certificate: %s", err.Error()), } } } else { // Genesis block checks if !b.Header().PrevBlockHash().IsUndef() { return BasicCheckError{ Reason: "invalid genesis block hash", } } } for _, trx := range b.Transactions() { if err := trx.BasicCheck(); err != nil { return BasicCheckError{ Reason: fmt.Sprintf("invalid transaction: %s", err.Error()), } } } return nil } // Hash returns the hash of the block. // The hash is memorized after the first calculation. func (b *Block) Hash() hash.Hash { if b.memorizedHash != nil { return *b.memorizedHash } buf := bytes.NewBuffer(make([]byte, 0, b.SerializeSize())) if err := b.data.Header.Encode(buf); err != nil { return hash.UndefHash } // Genesis block has no certificate if b.data.PrevCert != nil { buf.Write(b.data.PrevCert.Hash().Bytes()) } buf.Write(b.data.Txs.Root().Bytes()) buf.Write(util.Int32ToBytesLE(int32(b.data.Txs.Len()))) h := hash.CalcHash(buf.Bytes()) b.memorizedHash = &h return h } // Height returns the height of the block. // TODO: return types.Height type. func (b *Block) Height() types.Height { if b.data.PrevCert == nil { return 1 } return b.PrevCertificate().Height() + 1 } // LogString returns a concise string representation intended for use in logs. func (b *Block) LogString() string { return fmt.Sprintf("{⌘ %v 👤 %v 💻 %v 📨 %d}", b.Hash().LogString(), b.data.Header.ProposerAddress().LogString(), b.data.Header.StateRoot().LogString(), b.data.Txs.Len(), ) } func (b *Block) MarshalCBOR() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, b.SerializeSize())) if err := b.Encode(buf); err != nil { return nil, err } return cbor.Marshal(buf.Bytes()) } func (b *Block) UnmarshalCBOR(bs []byte) error { data := make([]byte, 0, b.SerializeSize()) err := cbor.Unmarshal(bs, &data) if err != nil { return err } buf := bytes.NewBuffer(data) return b.Decode(buf) } func (b *Block) Encode(w io.Writer) error { if err := b.data.Header.Encode(w); err != nil { return err } if b.data.PrevCert != nil { if err := b.data.PrevCert.Encode(w); err != nil { return err } } if err := encoding.WriteVarInt(w, uint64(b.data.Txs.Len())); err != nil { return err } for _, trx := range b.Transactions() { if err := trx.Encode(w); err != nil { return err } } return nil } func (b *Block) Decode(r io.Reader) error { b.data.Header = new(Header) if err := b.data.Header.Decode(r); err != nil { return err } if !b.data.Header.PrevBlockHash().IsUndef() { b.data.PrevCert = new(certificate.Certificate) if err := b.data.PrevCert.Decode(r); err != nil { return err } } length, err := encoding.ReadVarInt(r) if err != nil { return err } // We set 1000 as a hardcoded value, // matching the maximum number of transactions allowed in a block. if length > 1000 { return ErrTooManyTransactions } b.data.Txs = make([]*tx.Tx, length) for i := 0; i < int(length); i++ { trx := new(tx.Tx) if err := trx.Decode(r); err != nil { return err } b.data.Txs[i] = trx } return nil } // SerializeSize returns the number of bytes it would take to serialize the block. func (b *Block) SerializeSize() int { size := b.Header().SerializeSize() if b.PrevCertificate() != nil { size += b.PrevCertificate().SerializeSize() } size += encoding.VarIntSerializeSize(uint64(b.Transactions().Len())) for _, trx := range b.Transactions() { size += trx.SerializeSize() } return size } // Bytes returns the serialized bytes for the Block. It caches the // result so subsequent calls are more efficient. func (b *Block) Bytes() ([]byte, error) { // Return the cached serialized bytes if it has already been generated. if len(b.memorizedData) != 0 { return b.memorizedData, nil } writer := bytes.NewBuffer(make([]byte, 0, b.SerializeSize())) err := b.Encode(writer) if err != nil { return nil, err } // Cache the serialized bytes and return them. b.memorizedData = writer.Bytes() return b.memorizedData, nil } ================================================ FILE: types/block/block_test.go ================================================ package block_test import ( "encoding/hex" "testing" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/simplemerkle" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("No transactions", func(t *testing.T) { str := "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "00" // Txs: Len blk, _ := block.FromString(str) err := blk.BasicCheck() require.ErrorIs(t, err, block.BasicCheckError{ Reason: "no subsidy transaction", }) }) t.Run("Too many transactions", func(t *testing.T) { str := "02" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "e907" // Txs: Len (1001) _, err := block.FromString(str) require.ErrorIs(t, err, block.ErrTooManyTransactions) }) t.Run("Without the previous certificate", func(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight(), testsuite.BlockWithPrevCert(nil)) err := blk.BasicCheck() require.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid genesis block hash", }) }) t.Run("Invalid certificate", func(t *testing.T) { str := "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "00000000" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "02" + // Tx[0]: Flags "01" + // Tx[0]: Version "01000000" + // Tx[0]: LockTime "01" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01" // Tx[0]: Amount blk, _ := block.FromString(str) err := blk.BasicCheck() require.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid certificate: height is not positive: 0", }) }) t.Run("Invalid transaction", func(t *testing.T) { str := "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "02" + // Tx[0]: Flags "00" + // Tx[0]: Version "00000000" + // Tx[0]: LockTime "00" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01" // Tx[0]: Amount blk, _ := block.FromString(str) err := blk.BasicCheck() require.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid transaction: invalid version: 0", }) }) t.Run("Invalid previous block hash", func(t *testing.T) { str := "01" + // Version "00000000" + // UnixTime "0000000000000000000000000000000000000000000000000000000000000000" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "00" + // Tx[0]: Flags "01" + // Tx[0]: Version "01000000" + // Tx[0]: LockTime "01" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01" // Tx[0]: Amount _, err := block.FromString(str) require.Error(t, err) }) t.Run("Invalid proposer address (type is 2)", func(t *testing.T) { str := "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "02AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "02" + // Tx[0]: Flags "01" + // Tx[0]: Version "01000000" + // Tx[0]: LockTime "01" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01" // Tx[0]: Amount blk, _ := block.FromString(str) err := blk.BasicCheck() require.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid proposer address: pc1z42424242424242424242424242424242klpmq4", }) }) t.Run("Invalid Version", func(t *testing.T) { str := "00" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "02" + // Tx[0]: Flags "01" + // Tx[0]: Version "01000000" + // Tx[0]: LockTime "00" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01" // Tx[0]: Amount blk, _ := block.FromString(str) err := blk.BasicCheck() require.ErrorIs(t, err, block.BasicCheckError{ Reason: "invalid block version: 0", }) }) t.Run("Ok", func(t *testing.T) { str := "03" + // Version (ProtocolVersionLatest = 3, PIP-49) "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "02" + // Tx[0]: Flags "01" + // Tx[0]: Version "01000000" + // Tx[0]: LockTime "00" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "022222222222222222222222222222222222222222" + // Tx[0]: Receiver "01" // Tx[0]: Amount blk, _ := block.FromString(str) require.NoError(t, blk.BasicCheck()) assert.Zero(t, blk.Header().UnixTime()) assert.Equal(t, protocol.ProtocolVersionLatest, blk.Header().Version()) }) } func TestCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) blk1, _ := ts.GenerateTestBlock(ts.RandHeight()) bz1, err := cbor.Marshal(blk1) require.NoError(t, err) var blk2 block.Block err = cbor.Unmarshal(bz1, &blk2) require.NoError(t, err) require.NoError(t, blk2.BasicCheck()) assert.Equal(t, blk1.Hash(), blk2.Hash()) assert.Equal(t, blk1.Hash(), blk2.Hash()) err = cbor.Unmarshal([]byte{1}, &blk2) require.Error(t, err) } func TestEncodingBlock(t *testing.T) { ts := testsuite.NewTestSuite(t) blk, _ := ts.GenerateTestBlock(ts.RandHeight()) length := blk.SerializeSize() for i := 0; i < length; i++ { w := util.NewFixedWriter(i) require.Error(t, blk.Encode(w), "encode test %v failed", i) } writer := util.NewFixedWriter(length) require.NoError(t, blk.Encode(writer)) for i := 0; i < length; i++ { blk2 := new(block.Block) r := util.NewFixedReader(i, writer.Bytes()) require.Error(t, blk2.Decode(r), "decode test %v failed", i) } blk2 := new(block.Block) r := util.NewFixedReader(length, writer.Bytes()) require.NoError(t, blk2.Decode(r)) assert.Equal(t, blk.Hash(), blk2.Hash()) assert.Equal(t, blk.Header(), blk2.Header()) } func TestInvalidString(t *testing.T) { _, err := block.FromString("badcow") require.Error(t, err) } func TestBlockHash(t *testing.T) { data, _ := hex.DecodeString( "01" + // Version "00000000" + // UnixTime "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // PrevBlockHash "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // StateRoot "333333333333333333333333333333333333333333333333" + // SortitionSeed "333333333333333333333333333333333333333333333333" + "01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // ProposerAddress "04030201" + // PrevCert: Height "0100" + // PrevCert: Round "0401020304" + // PrevCert: Committers "0102" + // PrevCert: Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d" + "2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6" + // PrevCert: Signature "01" + // Txs: Len "02" + // Tx[0]: Flags "01" + // Tx[0]: Version "01000000" + // Tx[0]: LockTime "01" + // Tx[0]: Fee "00" + // Tx[0]: Memo "01" + // Tx[0]: PayloadType "00" + // Tx[0]: Sender (treasury) "012222222222222222222222222222222222222222" + // Tx[0]: Receiver "01") // Tx[0]: Amount blk, err := block.FromBytes(data) require.NoError(t, err) assert.Equal(t, len(data), blk.SerializeSize()) blockData, _ := blk.Bytes() assert.Equal(t, data, blockData) headerSize := blk.Header().SerializeSize() headerData := data[:headerSize] certSize := blk.PrevCertificate().SerializeSize() certData := data[headerSize : headerSize+certSize] certHash := hash.CalcHash(certData) txHashes := make([]hash.Hash, 0, blk.Transactions().Len()) for _, trx := range blk.Transactions() { txHashes = append(txHashes, trx.ID()) } txRoot := simplemerkle.NewTreeFromHashes(txHashes).Root() hashData := headerData hashData = append(hashData, certHash.Bytes()...) hashData = append(hashData, txRoot.Bytes()...) hashData = append(hashData, util.Int32ToBytesLE(int32(blk.Transactions().Len()))...) expected1 := hash.CalcHash(hashData) expected2, _ := hash.FromString("43399fa59adcfb7d8c515460ec9ca27b6a1cb865f5b7d9bde8fe56c18eaec9ab") assert.Equal(t, expected1, blk.Hash()) assert.Equal(t, expected2, blk.Hash()) } func TestMakeBlock(t *testing.T) { ts := testsuite.NewTestSuite(t) blk0, _ := ts.GenerateTestBlock(ts.RandHeight()) blk1 := block.MakeBlock(protocol.ProtocolVersion2, blk0.Header().Time(), blk0.Transactions(), blk0.Header().PrevBlockHash(), blk0.Header().StateRoot(), blk0.PrevCertificate(), blk0.Header().SortitionSeed(), blk0.Header().ProposerAddress()) assert.Equal(t, blk0.Hash(), blk1.Hash()) } func TestBlockHeight(t *testing.T) { ts := testsuite.NewTestSuite(t) blk1, _ := ts.GenerateTestBlock(1, testsuite.BlockWithPrevCert(nil), testsuite.BlockWithPrevHash(hash.UndefHash)) blk2, _ := ts.GenerateTestBlock(2) require.NoError(t, blk1.BasicCheck()) require.NoError(t, blk2.BasicCheck()) assert.Equal(t, types.Height(1), blk1.Height()) assert.Equal(t, types.Height(2), blk2.Height()) } ================================================ FILE: types/block/errors.go ================================================ package block import "errors" var ErrTooManyTransactions = errors.New("too many transactions in block") // BasicCheckError is returned when the basic check on the certificate fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } ================================================ FILE: types/block/header.go ================================================ package block import ( "fmt" "io" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/util/encoding" ) type Header struct { data headerData } type headerData struct { Version protocol.Version UnixTime uint32 PrevBlockHash hash.Hash StateRoot hash.Hash SortitionSeed sortition.VerifiableSeed ProposerAddress crypto.Address } // Version returns the block version. func (h *Header) Version() protocol.Version { return h.data.Version } // Time returns the block time. func (h *Header) Time() time.Time { return time.Unix(int64(h.data.UnixTime), 0) } // UnixTime returns the block time in Unix value. func (h *Header) UnixTime() uint32 { return h.data.UnixTime } // StateRoot returns the state root hash. func (h *Header) StateRoot() hash.Hash { return h.data.StateRoot } // PrevBlockHash returns the previous block hash. func (h *Header) PrevBlockHash() hash.Hash { return h.data.PrevBlockHash } // SortitionSeed returns the sortition seed. func (h *Header) SortitionSeed() sortition.VerifiableSeed { return h.data.SortitionSeed } // ProposerAddress returns the proposer address. func (h *Header) ProposerAddress() crypto.Address { return h.data.ProposerAddress } func NewHeader(version protocol.Version, tme time.Time, stateRoot, prevBlockHash hash.Hash, sortitionSeed sortition.VerifiableSeed, proposerAddress crypto.Address, ) *Header { return &Header{ data: headerData{ Version: version, UnixTime: uint32(tme.Unix()), PrevBlockHash: prevBlockHash, StateRoot: stateRoot, ProposerAddress: proposerAddress, SortitionSeed: sortitionSeed, }, } } func (h *Header) BasicCheck() error { if h.data.Version == 0 { return BasicCheckError{ Reason: "invalid block version: 0", } } if !h.data.ProposerAddress.IsValidatorAddress() { return BasicCheckError{ Reason: fmt.Sprintf("invalid proposer address: %s", h.data.ProposerAddress.String()), } } return nil } // SerializeSize returns the number of bytes it would take to serialize the header. func (*Header) SerializeSize() int { return 138 // 5 + (2 * 32) + 48 + 21 } func (h *Header) Encode(w io.Writer) error { return encoding.WriteElements(w, h.data.Version, h.data.UnixTime, h.data.PrevBlockHash, h.data.StateRoot, h.data.SortitionSeed, h.data.ProposerAddress) } func (h *Header) Decode(r io.Reader) error { return encoding.ReadElements(r, &h.data.Version, &h.data.UnixTime, &h.data.PrevBlockHash, &h.data.StateRoot, &h.data.SortitionSeed, &h.data.ProposerAddress) } ================================================ FILE: types/block/txs.go ================================================ package block import ( "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/simplemerkle" ) type Txs []*tx.Tx func NewTxs() Txs { return make([]*tx.Tx, 0) } func (txs *Txs) Append(trx *tx.Tx) { *txs = append(*txs, trx) } func (txs *Txs) Prepend(trx *tx.Tx) { *txs = append(*txs, nil) copy((*txs)[1:], (*txs)[0:]) (*txs)[0] = trx } func (txs *Txs) Remove(i int) { // https://github.com/golang/go/wiki/SliceTricks#delete copy((*txs)[i:], (*txs)[i+1:]) (*txs)[txs.Len()-1] = nil *txs = (*txs)[:txs.Len()-1] } func (txs Txs) Root() hash.Hash { hashes := make([]hash.Hash, txs.Len()) for i, trx := range txs { hashes[i] = trx.ID() } merkle := simplemerkle.NewTreeFromHashes(hashes) return merkle.Root() } func (txs Txs) IsEmpty() bool { return txs.Len() == 0 } func (txs Txs) Len() int { return len(txs) } func (txs Txs) Get(i int) *tx.Tx { return txs[i] } func (txs Txs) Subsidy() *tx.Tx { return txs[0] } ================================================ FILE: types/block/txs_test.go ================================================ package block_test import ( "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" ) func TestTxsMerkle(t *testing.T) { ts := testsuite.NewTestSuite(t) txs := block.NewTxs() trx1 := ts.GenerateTestTransferTx() trx2 := ts.GenerateTestTransferTx() txs.Append(trx1) merkle := txs.Root() assert.Equal(t, trx1.ID(), merkle) txs.Append(trx2) merkle = txs.Root() data := make([]byte, 64) copy(data[:32], trx1.ID().Bytes()) copy(data[32:], trx2.ID().Bytes()) assert.Equal(t, hash.CalcHash(data), merkle) } func TestAppendPrependRemove(t *testing.T) { ts := testsuite.NewTestSuite(t) txs := block.NewTxs() trx1 := ts.GenerateTestTransferTx() trx2 := ts.GenerateTestTransferTx() trx3 := ts.GenerateTestTransferTx() trx4 := ts.GenerateTestTransferTx() trx5 := ts.GenerateTestTransferTx() txs.Append(trx2) txs.Append(trx3) txs.Prepend(trx1) txs.Append(trx5) txs.Append(trx4) txs.Remove(3) assert.Equal(t, block.Txs{trx1, trx2, trx3, trx4}, txs) } func TestIsEmpty(t *testing.T) { ts := testsuite.NewTestSuite(t) txs := block.NewTxs() assert.True(t, txs.IsEmpty()) trx := ts.GenerateTestTransferTx() txs.Append(trx) assert.False(t, txs.IsEmpty()) } func TestGetTransaction(t *testing.T) { ts := testsuite.NewTestSuite(t) txs := block.NewTxs() trx1 := ts.GenerateTestTransferTx() trx2 := ts.GenerateTestTransferTx() txs.Append(trx1) txs.Append(trx2) assert.Equal(t, trx1, txs.Get(0)) } func TestSubsidy(t *testing.T) { ts := testsuite.NewTestSuite(t) blk, _ := ts.GenerateTestBlock(ts.RandHeight()) assert.Equal(t, blk.Transactions()[0], blk.Transactions().Subsidy()) } ================================================ FILE: types/certificate/certificate.go ================================================ package certificate import ( "bytes" "fmt" "io" "slices" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/encoding" ) // Certificate represents a base structure for both Certificate and Certificate. // As a Certificate, it verifies if a block is signed by a majority of validators. // As a Certificate, it checks whether a majority of validators have voted in the consensus step. type Certificate struct { height types.Height round types.Round committers []int32 absentees []int32 signature *bls.Signature } // NewCertificate creates a new Certificate instance. func NewCertificate(height types.Height, round types.Round) *Certificate { return &Certificate{ height: height, round: round, } } func (cert *Certificate) Height() types.Height { return cert.height } func (cert *Certificate) Round() types.Round { return cert.round } func (cert *Certificate) Committers() []int32 { return cert.committers } func (cert *Certificate) Absentees() []int32 { return cert.absentees } func (cert *Certificate) Signature() *bls.Signature { return cert.signature } func (cert *Certificate) BasicCheck() error { if cert.height <= 0 { return BasicCheckError{ Reason: fmt.Sprintf("height is not positive: %d", cert.height), } } if cert.round < 0 { return BasicCheckError{ Reason: fmt.Sprintf("round is negative: %d", cert.round), } } if cert.signature == nil { return BasicCheckError{ Reason: "signature is missing", } } if cert.committers == nil { return BasicCheckError{ Reason: "committers is missing", } } if cert.absentees == nil { return BasicCheckError{ Reason: "absentees is missing", } } if !util.IsSubset(cert.committers, cert.absentees) { return BasicCheckError{ Reason: fmt.Sprintf("absentees are not a subset of committers: %v, %v", cert.committers, cert.absentees), } } return nil } func (cert *Certificate) Hash() hash.Hash { buf := bytes.NewBuffer(make([]byte, 0, cert.SerializeSize())) if err := cert.Encode(buf); err != nil { return hash.UndefHash } return hash.CalcHash(buf.Bytes()) } func (cert *Certificate) SetSignature(committers, absentees []int32, signature *bls.Signature) { cert.committers = committers cert.absentees = absentees cert.signature = signature } // SerializeSize returns the number of bytes it would take to serialize the block. func (cert *Certificate) SerializeSize() int { size := 6 + // height (4) + round(2) encoding.VarIntSerializeSize(uint64(len(cert.committers))) + encoding.VarIntSerializeSize(uint64(len(cert.absentees))) + bls.SignatureSize for _, n := range cert.committers { size += encoding.VarIntSerializeSize(uint64(n)) } for _, n := range cert.absentees { size += encoding.VarIntSerializeSize(uint64(n)) } return size } func (cert *Certificate) MarshalCBOR() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, cert.SerializeSize())) if err := cert.Encode(buf); err != nil { return nil, err } return cbor.Marshal(buf.Bytes()) } func (cert *Certificate) UnmarshalCBOR(bs []byte) error { data := make([]byte, 0, cert.SerializeSize()) err := cbor.Unmarshal(bs, &data) if err != nil { return err } buf := bytes.NewBuffer(data) return cert.Decode(buf) } func (cert *Certificate) Encode(w io.Writer) error { if err := encoding.WriteElements(w, cert.height, cert.round); err != nil { return err } if err := encoding.WriteVarInt(w, uint64(len(cert.committers))); err != nil { return err } for _, n := range cert.committers { if err := encoding.WriteVarInt(w, uint64(n)); err != nil { return err } } if err := encoding.WriteVarInt(w, uint64(len(cert.absentees))); err != nil { return err } for _, n := range cert.absentees { if err := encoding.WriteVarInt(w, uint64(n)); err != nil { return err } } return cert.signature.Encode(w) } func (cert *Certificate) Decode(r io.Reader) error { err := encoding.ReadElements(r, &cert.height, &cert.round) if err != nil { return err } lenCommitters, err := encoding.ReadVarInt(r) if err != nil { return err } // We set 51 as a hardcoded value, // matching the maximum number of committers allowed in a block. if lenCommitters > 51 { return ErrTooManyCommitters } committers := make([]int32, lenCommitters) for i := 0; i < int(lenCommitters); i++ { n, err := encoding.ReadVarInt(r) if err != nil { return err } committers[i] = int32(n) } lenAbsentees, err := encoding.ReadVarInt(r) if err != nil { return err } // We set 51 as a hardcoded value, // matching the maximum number of committers allowed in a block. if lenAbsentees > 51 { return ErrTooManyAbsentees } absentees := make([]int32, lenAbsentees) for i := 0; i < int(lenAbsentees); i++ { n, err := encoding.ReadVarInt(r) if err != nil { return err } absentees[i] = int32(n) } sig := new(bls.Signature) if err := sig.Decode(r); err != nil { return err } cert.committers = committers cert.absentees = absentees cert.signature = sig return nil } func (cert *Certificate) SignBytesPrepare(blockHash hash.Hash) []byte { return cert.signBytes(blockHash, util.StringToBytes("PREPARE")) } func (cert *Certificate) SignBytesPrecommit(blockHash hash.Hash) []byte { return cert.signBytes(blockHash) } func (cert *Certificate) SignBytesCPPreVote(blockHash hash.Hash, cpRound int16, cpValue byte) []byte { return cert.signBytes(blockHash, util.StringToBytes("PRE-VOTE"), util.Int16ToBytesLE(cpRound), []byte{cpValue}) } func (cert *Certificate) SignBytesCPMainVote(blockHash hash.Hash, cpRound int16, cpValue byte) []byte { return cert.signBytes(blockHash, util.StringToBytes("MAIN-VOTE"), util.Int16ToBytesLE(cpRound), []byte{cpValue}) } func (cert *Certificate) SignBytesCPDecided(blockHash hash.Hash, cpRound int16, cpValue byte) []byte { return cert.signBytes(blockHash, util.StringToBytes("DECIDED"), util.Int16ToBytesLE(cpRound), []byte{cpValue}) } // signBytes returns the sign bytes for the vote certificate. func (cert *Certificate) signBytes(blockHash hash.Hash, extraData ...[]byte) []byte { signBytes := blockHash.Bytes() signBytes = append(signBytes, cert.height.BytesLE()...) signBytes = append(signBytes, cert.round.BytesLE()...) for _, data := range extraData { signBytes = append(signBytes, data...) } return signBytes } func (cert *Certificate) ValidatePrepare(validators []*validator.Validator, blockHash hash.Hash, ) error { signBytes := cert.SignBytesPrepare(blockHash) return cert.validate(validators, signBytes, Required2FP1Power) } func (cert *Certificate) ValidatePrecommit(validators []*validator.Validator, blockHash hash.Hash, ) error { signBytes := cert.SignBytesPrecommit(blockHash) return cert.validate(validators, signBytes, Required2FP1Power) } func (cert *Certificate) ValidateCPPreVote(validators []*validator.Validator, blockHash hash.Hash, cpRound int16, cpValue byte, ) error { signBytes := cert.SignBytesCPPreVote(blockHash, cpRound, cpValue) return cert.validate(validators, signBytes, Required2FP1Power) } func (cert *Certificate) ValidateCPMainVote(validators []*validator.Validator, blockHash hash.Hash, cpRound int16, cpValue byte, ) error { signBytes := cert.SignBytesCPMainVote(blockHash, cpRound, cpValue) return cert.validate(validators, signBytes, Required2FP1Power) } func (cert *Certificate) validate(validators []*validator.Validator, signBytes []byte, requiredPowerFn RequiredPowerFn, ) error { if len(validators) != len(cert.committers) { return UnexpectedCommittersError{ Committers: cert.committers, } } pubs := make([]*bls.PublicKey, 0, len(cert.committers)) committeePower := int64(0) signedPower := int64(0) for index, num := range cert.committers { val := validators[index] if val.Number() != num { return UnexpectedCommittersError{ Committers: cert.committers, } } if !slices.Contains(cert.absentees, num) { pubs = append(pubs, val.PublicKey()) signedPower += val.Power() } committeePower += val.Power() } requiredPower := requiredPowerFn(committeePower) // Check if signers have enough power if signedPower < requiredPower { return InsufficientPowerError{ SignedPower: signedPower, RequiredPower: requiredPower, } } aggPub, _ := bls.PublicKeyAggregate(pubs...) return aggPub.Verify(signBytes, cert.signature) } // AddSignature adds a new signature to the certificate. // It does not check the validity of the signature. // The caller should ensure that the signature is valid. func (cert *Certificate) AddSignature(valNum int32, sig *bls.Signature) { absentees, removed := util.RemoveFirstOccurrenceOf(cert.absentees, valNum) if removed { aggSig, _ := bls.SignatureAggregate(cert.signature, sig) cert.signature = aggSig cert.absentees = absentees } } func (cert *Certificate) Clone() *Certificate { cloned := &Certificate{ height: cert.height, round: cert.round, committers: make([]int32, len(cert.committers)), absentees: make([]int32, len(cert.absentees)), signature: new(bls.Signature), } copy(cloned.committers, cert.committers) copy(cloned.absentees, cert.absentees) *cloned.signature = *cert.signature return cloned } ================================================ FILE: types/certificate/certificate_test.go ================================================ package certificate_test import ( "bytes" "encoding/hex" "fmt" "testing" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/exp/slices" ) func TestDecoding(t *testing.T) { t.Run("Too many committers", func(t *testing.T) { data, _ := hex.DecodeString( "04030201" + // Height "0100" + // Round "34") // Committers: Len (52) r := bytes.NewReader(data) cert := new(certificate.Certificate) err := cert.Decode(r) require.ErrorIs(t, err, certificate.ErrTooManyCommitters) }) t.Run("Too many absentees", func(t *testing.T) { data, _ := hex.DecodeString( "04030201" + // Height "0100" + // Round "0102" + // Committers "34") // Absentees: Len (52) r := bytes.NewReader(data) cert := new(certificate.Certificate) err := cert.Decode(r) require.ErrorIs(t, err, certificate.ErrTooManyAbsentees) }) t.Run("Ok", func(t *testing.T) { data, _ := hex.DecodeString( "04030201" + // Height "0100" + // Round "06010203040506" + // Committers "0102" + // Absentees "b53d79e156e9417e010fa21f2b2a96bee6be46fcd233295d2f697cdb9e782b6112ac01c80d0d9d64c2320664c77fa2a6") // Signature certHash, _ := hash.FromString("ac755295a6850b141286bde42bb8ba06ae1671f0562cbef90043924091177815") r := bytes.NewReader(data) cert := new(certificate.Certificate) err := cert.Decode(r) require.NoError(t, err) assert.Equal(t, types.Height(0x01020304), cert.Height()) assert.Equal(t, types.Round(0x0001), cert.Round()) assert.Equal(t, []int32{1, 2, 3, 4, 5, 6}, cert.Committers()) assert.Equal(t, []int32{2}, cert.Absentees()) assert.Equal(t, certHash, cert.Hash()) blockHash, _ := hash.FromString("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") expectedPrepareSignByte, _ := hex.DecodeString( "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" + // Block hash "04030201" + // Height "0100" + // Round "50524550415245") // PREPARE expectedPrecommitSignByte, _ := hex.DecodeString( "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" + // Block hash "04030201" + // Height "0100") // Round expectedCPPreVoteSignByte, _ := hex.DecodeString( "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" + // Block hash "04030201" + // Height "0100" + // Round "5052452d564f5445" + // PRE-VOTE "0100" + // CP Round "02") // CP Value expectedCPMainVoteSignByte, _ := hex.DecodeString( "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" + // Block hash "04030201" + // Height "0100" + // Round "4d41494e2d564f5445" + // MAIN-VOTE "0100" + // CP Round "02") // CP Value expectedCPDecidedSignByte, _ := hex.DecodeString( "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" + // Block hash "04030201" + // Height "0100" + // Round "44454349444544" + // DECIDED "0100" + // CP Round "02") // CP Value assert.Equal(t, expectedPrepareSignByte, cert.SignBytesPrepare(blockHash)) assert.Equal(t, expectedPrecommitSignByte, cert.SignBytesPrecommit(blockHash)) assert.Equal(t, expectedCPPreVoteSignByte, cert.SignBytesCPPreVote(blockHash, 1, 2)) assert.Equal(t, expectedCPMainVoteSignByte, cert.SignBytesCPMainVote(blockHash, 1, 2)) assert.Equal(t, expectedCPDecidedSignByte, cert.SignBytesCPDecided(blockHash, 1, 2)) }) } func TestCertificateCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) cert1 := ts.GenerateTestCertificate(ts.RandHeight()) bz1, err := cbor.Marshal(cert1) require.NoError(t, err) var cert2 certificate.Certificate err = cbor.Unmarshal(bz1, &cert2) require.NoError(t, err) require.NoError(t, cert2.BasicCheck()) assert.True(t, cert1.Signature().EqualsTo(cert2.Signature())) assert.Equal(t, cert1.Hash(), cert2.Hash()) err = cbor.Unmarshal([]byte{1}, &cert2) require.Error(t, err) } func TestBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Invalid height", func(t *testing.T) { cert := certificate.NewCertificate(0, 0) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "height is not positive: 0", }) }) t.Run("Invalid round", func(t *testing.T) { cert := certificate.NewCertificate(1, -1) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "round is negative: -1", }) }) t.Run("Committers is nil", func(t *testing.T) { cert := certificate.NewCertificate(ts.RandHeight(), ts.RandRound()) cert.SetSignature(nil, []int32{1}, ts.RandBLSSignature()) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "committers is missing", }) }) t.Run("Absentees is nil", func(t *testing.T) { cert := certificate.NewCertificate(ts.RandHeight(), ts.RandRound()) cert.SetSignature([]int32{1, 2, 3, 4}, nil, ts.RandBLSSignature()) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "absentees is missing", }) }) t.Run("Signature is nil", func(t *testing.T) { cert := certificate.NewCertificate(ts.RandHeight(), ts.RandRound()) cert.SetSignature([]int32{1, 2, 3, 4, 5, 6}, []int32{1}, nil) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: "signature is missing", }) }) t.Run("Invalid Absentees ", func(t *testing.T) { cert := certificate.NewCertificate(ts.RandHeight(), ts.RandRound()) cert.SetSignature([]int32{11, 2, 3, 4, 5, 6}, []int32{66}, ts.RandBLSSignature()) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: fmt.Sprintf("absentees are not a subset of committers: %v, %v", cert.Committers(), []int32{66}), }) }) t.Run("Invalid Absentees ", func(t *testing.T) { cert := certificate.NewCertificate(ts.RandHeight(), ts.RandRound()) cert.SetSignature([]int32{1, 2, 3, 4, 5, 6}, []int32{2, 1}, ts.RandBLSSignature()) err := cert.BasicCheck() require.ErrorIs(t, err, certificate.BasicCheckError{ Reason: fmt.Sprintf("absentees are not a subset of committers: %v, %v", cert.Committers(), []int32{2, 1}), }) }) } func TestEncodingCertificate(t *testing.T) { ts := testsuite.NewTestSuite(t) cert1 := ts.GenerateTestCertificate(ts.RandHeight()) length := cert1.SerializeSize() for i := 0; i < length; i++ { w := util.NewFixedWriter(i) require.Error(t, cert1.Encode(w), "encode test %v failed", i) } writer := util.NewFixedWriter(length) require.NoError(t, cert1.Encode(writer)) for i := 0; i < length; i++ { cert := new(certificate.Certificate) r := util.NewFixedReader(i, writer.Bytes()) require.Error(t, cert.Decode(r), "decode test %v failed", i) } cert2 := new(certificate.Certificate) reader := util.NewFixedReader(length, writer.Bytes()) require.NoError(t, cert2.Decode(reader)) assert.Equal(t, cert1.Hash(), cert2.Hash()) } func TestAddSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) blockHash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cert := certificate.NewCertificate(height, round) signBytes := cert.SignBytesPrecommit(blockHash) committers := ts.RandSlice(4) sigs := make([]*bls.Signature, 0, len(committers)) validators := make([]*validator.Validator, 0, len(committers)) for _, committer := range committers { valKey := ts.RandValKey() val := validator.NewValidator(valKey.PublicKey(), committer) sig := valKey.Sign(signBytes) validators = append(validators, val) sigs = append(sigs, sig) } absentees := committers[3:] aggSig, _ := bls.SignatureAggregate(sigs[:3]...) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrecommit(validators, blockHash) require.NoError(t, err) numAbsentees := len(cert.Absentees()) t.Run("Add an existing signature", func(t *testing.T) { cert.AddSignature(validators[0].Number(), sigs[0]) err := cert.ValidatePrecommit(validators, blockHash) require.NoError(t, err) assert.Len(t, cert.Absentees(), numAbsentees) }) t.Run("Add non existing signature", func(t *testing.T) { cert.AddSignature(validators[3].Number(), sigs[3]) err := cert.ValidatePrecommit(validators, blockHash) require.NoError(t, err) assert.Len(t, cert.Absentees(), numAbsentees-1) }) } // Deprecated test. func TestCertificateValidatePrepare(t *testing.T) { ts := testsuite.NewTestSuite(t) blockHash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cert := certificate.NewCertificate(height, round) signBytes := cert.SignBytesPrepare(blockHash) committers := ts.RandSlice(4) sigs := make([]*bls.Signature, 0, len(committers)) validators := make([]*validator.Validator, 0, len(committers)) for _, committer := range committers { valKey := ts.RandValKey() val := validator.NewValidator(valKey.PublicKey(), committer) sig := valKey.Sign(signBytes) validators = append(validators, val) sigs = append(sigs, sig) } t.Run("Doesn't have 2f+1 majority", func(t *testing.T) { absentees := committers[2:] aggSig, sigErr := bls.SignatureAggregate(sigs[:2]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrepare(validators, blockHash) require.ErrorIs(t, err, certificate.InsufficientPowerError{ SignedPower: 2, RequiredPower: 3, }) }) t.Run("Ok, should return no error", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrepare(validators, blockHash) require.NoError(t, err) }) } func TestCertificateValidatePrecommit(t *testing.T) { ts := testsuite.NewTestSuite(t) blockHash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cert := certificate.NewCertificate(height, round) signBytes := cert.SignBytesPrecommit(blockHash) committers := ts.RandSlice(4) sigs := make([]*bls.Signature, 0, len(committers)) validators := make([]*validator.Validator, 0, len(committers)) for _, committer := range committers { valKey := ts.RandValKey() val := validator.NewValidator(valKey.PublicKey(), committer) sig := valKey.Sign(signBytes) validators = append(validators, val) sigs = append(sigs, sig) } t.Run("Invalid committer, should return error", func(t *testing.T) { invCommitters := slices.Clone(committers) invCommitters = append(invCommitters, ts.Rand.Int31n(10000)) absentees := committers[4:] aggSig, sigErr := bls.SignatureAggregate(sigs[:4]...) require.NoError(t, sigErr) cert.SetSignature(invCommitters, absentees, aggSig) err := cert.ValidatePrecommit(validators, blockHash) require.ErrorIs(t, err, certificate.UnexpectedCommittersError{ Committers: invCommitters, }) }) t.Run("Invalid validator", func(t *testing.T) { absentees := committers[4:] aggSig, sigErr := bls.SignatureAggregate(sigs[:4]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) invValidators := slices.Clone(validators) invValidators[0] = ts.GenerateTestValidator() err := cert.ValidatePrecommit(invValidators, blockHash) require.ErrorIs(t, err, certificate.UnexpectedCommittersError{ Committers: committers, }) }) t.Run("Doesn't have 2f+1 majority", func(t *testing.T) { absentees := committers[2:] aggSig, sigErr := bls.SignatureAggregate(sigs[:2]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrecommit(validators, blockHash) require.ErrorIs(t, err, certificate.InsufficientPowerError{ SignedPower: 2, RequiredPower: 3, }) }) t.Run("One signature short, should return an error for invalid signature", func(t *testing.T) { absentees := committers[4:] aggSig, sigErr := bls.SignatureAggregate(sigs[3:]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrecommit(validators, blockHash) require.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Invalid block hash", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrecommit(validators, ts.RandHash()) require.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Ok, should return no error", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidatePrecommit(validators, blockHash) require.NoError(t, err) }) } func TestCertificateValidateCPPreVote(t *testing.T) { ts := testsuite.NewTestSuite(t) blockHash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cpRound := int16(ts.RandRound()) cpValue := byte(2) cert := certificate.NewCertificate(height, round) signBytes := cert.SignBytesCPPreVote(blockHash, cpRound, cpValue) committers := ts.RandSlice(4) sigs := make([]*bls.Signature, 0, len(committers)) validators := make([]*validator.Validator, 0, len(committers)) for _, committer := range committers { valKey := ts.RandValKey() val := validator.NewValidator(valKey.PublicKey(), committer) sig := valKey.Sign(signBytes) validators = append(validators, val) sigs = append(sigs, sig) } t.Run("Invalid cpValue", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidateCPPreVote(validators, blockHash, cpRound, byte(0)) require.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Doesn't have 2f+1 majority", func(t *testing.T) { absentees := committers[2:] aggSig, sigErr := bls.SignatureAggregate(sigs[:2]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidateCPPreVote(validators, blockHash, cpRound, cpValue) require.ErrorIs(t, err, certificate.InsufficientPowerError{ SignedPower: 2, RequiredPower: 3, }) }) t.Run("Ok, should return no error", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidateCPPreVote(validators, blockHash, cpRound, cpValue) require.NoError(t, err) }) } func TestCertificateValidateCPMainVote(t *testing.T) { ts := testsuite.NewTestSuite(t) blockHash := ts.RandHash() height := ts.RandHeight() round := ts.RandRound() cpRound := int16(ts.RandRound()) cpValue := byte(2) cert := certificate.NewCertificate(height, round) signBytes := cert.SignBytesCPMainVote(blockHash, cpRound, cpValue) committers := ts.RandSlice(4) sigs := make([]*bls.Signature, 0, len(committers)) validators := make([]*validator.Validator, 0, len(committers)) for _, committer := range committers { valKey := ts.RandValKey() val := validator.NewValidator(valKey.PublicKey(), committer) sig := valKey.Sign(signBytes) validators = append(validators, val) sigs = append(sigs, sig) } t.Run("Invalid cpValue", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidateCPMainVote(validators, blockHash, cpRound, byte(0)) require.ErrorIs(t, err, crypto.ErrInvalidSignature) }) t.Run("Doesn't have 2f+1 majority", func(t *testing.T) { absentees := committers[2:] aggSig, sigErr := bls.SignatureAggregate(sigs[:2]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidateCPMainVote(validators, blockHash, cpRound, cpValue) require.ErrorIs(t, err, certificate.InsufficientPowerError{ SignedPower: 2, RequiredPower: 3, }) }) t.Run("Ok, should return no error", func(t *testing.T) { absentees := committers[3:] aggSig, sigErr := bls.SignatureAggregate(sigs[:3]...) require.NoError(t, sigErr) cert.SetSignature(committers, absentees, aggSig) err := cert.ValidateCPMainVote(validators, blockHash, cpRound, cpValue) require.NoError(t, err) }) } func TestClone(t *testing.T) { ts := testsuite.NewTestSuite(t) cert1 := ts.GenerateTestCertificate(ts.RandHeight()) cert2 := cert1.Clone() cert2.AddSignature(cert2.Absentees()[0], ts.RandBLSSignature()) assert.NotEqual(t, cert1.Absentees(), cert2.Absentees()) assert.NotEqual(t, cert1, cert2) } ================================================ FILE: types/certificate/errors.go ================================================ package certificate import ( "errors" "fmt" "reflect" ) var ( ErrTooManyCommitters = errors.New("too many committers in certificate") ErrTooManyAbsentees = errors.New("too many absentees in certificate") ) // BasicCheckError is returned when the basic check on the certificate fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } // UnexpectedCommittersError is returned when the list of committers // does not match the expectations. type UnexpectedCommittersError struct { Committers []int32 } func (e UnexpectedCommittersError) Error() string { return fmt.Sprintf("certificate has an unexpected committers: %v", e.Committers) } func (e UnexpectedCommittersError) Is(target error) bool { return reflect.DeepEqual(e, target) } // InsufficientPowerError is returned when the accumulated power does not meet // the required threshold. type InsufficientPowerError struct { SignedPower int64 RequiredPower int64 } func (e InsufficientPowerError) Error() string { return fmt.Sprintf("accumulated power is %v, should be at least %v", e.SignedPower, e.RequiredPower) } ================================================ FILE: types/certificate/power.go ================================================ package certificate // faultyPower calculates the maximum faulty power based on the total voting power. // The formula used is: `f = (n - 1) / 3`, where `n` is the total voting power. func faultyPower(totalPower int64) int64 { return (totalPower - 1) / 3 } type RequiredPowerFn func(int64) int64 var Required3FP1Power = func(power int64) int64 { f := faultyPower(power) p := (3 * f) + 1 return p } var Required2FP1Power = func(power int64) int64 { f := faultyPower(power) p := (2 * f) + 1 return p } var Required1FP1Power = func(totalPower int64) int64 { f := faultyPower(totalPower) p := (1 * f) + 1 return p } // Has1FP1Power checks whether the signed power is greater than or equal to f+1, // where f is the maximum faulty power. func Has1FP1Power(totalPower, signedPower int64) bool { return signedPower >= Required1FP1Power(totalPower) } // Has2FP1Power checks whether the signed power is greater than or equal to 2f+1, // where f is the maximum faulty power. func Has2FP1Power(totalPower, signedPower int64) bool { return signedPower >= Required2FP1Power(totalPower) } // Has3FP1Power checks whether the signed power is greater than or equal to 3f+1, // where f is the maximum faulty power. func Has3FP1Power(totalPower, signedPower int64) bool { return signedPower >= Required3FP1Power(totalPower) } ================================================ FILE: types/certificate/power_test.go ================================================ package certificate_test import ( "testing" "github.com/pactus-project/pactus/types/certificate" "github.com/stretchr/testify/assert" ) func TestPowerFunctions(t *testing.T) { tests := []struct { totalPower int64 signedPower int64 has1FP1Power bool has2FP1Power bool has3FP1Power bool }{ {totalPower: 7, signedPower: 2, has1FP1Power: false, has2FP1Power: false, has3FP1Power: false}, {totalPower: 7, signedPower: 3, has1FP1Power: true, has2FP1Power: false, has3FP1Power: false}, {totalPower: 7, signedPower: 5, has1FP1Power: true, has2FP1Power: true, has3FP1Power: false}, {totalPower: 7, signedPower: 7, has1FP1Power: true, has2FP1Power: true, has3FP1Power: true}, {totalPower: 8, signedPower: 2, has1FP1Power: false, has2FP1Power: false, has3FP1Power: false}, {totalPower: 8, signedPower: 3, has1FP1Power: true, has2FP1Power: false, has3FP1Power: false}, {totalPower: 8, signedPower: 5, has1FP1Power: true, has2FP1Power: true, has3FP1Power: false}, {totalPower: 8, signedPower: 7, has1FP1Power: true, has2FP1Power: true, has3FP1Power: true}, {totalPower: 9, signedPower: 2, has1FP1Power: false, has2FP1Power: false, has3FP1Power: false}, {totalPower: 9, signedPower: 3, has1FP1Power: true, has2FP1Power: false, has3FP1Power: false}, {totalPower: 9, signedPower: 5, has1FP1Power: true, has2FP1Power: true, has3FP1Power: false}, {totalPower: 9, signedPower: 7, has1FP1Power: true, has2FP1Power: true, has3FP1Power: true}, } for _, tt := range tests { assert.Equal(t, tt.has1FP1Power, certificate.Has1FP1Power(tt.totalPower, tt.signedPower), "Has1FP1Power(%d, %d)", tt.totalPower, tt.signedPower) assert.Equal(t, tt.has2FP1Power, certificate.Has2FP1Power(tt.totalPower, tt.signedPower), "Has2FP1Power(%d, %d)", tt.totalPower, tt.signedPower) assert.Equal(t, tt.has3FP1Power, certificate.Has3FP1Power(tt.totalPower, tt.signedPower), "Has3FP1Power(%d, %d)", tt.totalPower, tt.signedPower) } } ================================================ FILE: types/height.go ================================================ package types import "github.com/pactus-project/pactus/util" type Height uint32 // HeightFromBytesLE creates a Height from a byte slice in little-endian format. func HeightFromBytesLE(data []byte) Height { return Height(util.BytesToUint32LE(data)) } // SafeIncrease returns a new Height that is the result of adding count to h. func (h Height) SafeIncrease(count uint32) Height { return Height(uint32(h) + count) } // SafeDecrease returns the result of subtracting other from h, // but it returns 0 if the result would be negative. func (h Height) SafeDecrease(count uint32) Height { if uint32(h) < count { return 0 } return Height(uint32(h) - count) } // SafeSub returns the result of subtracting other from h, // but it returns 0 if the result would be negative. func (h Height) SafeSub(other Height) uint32 { if h < other { return 0 } return uint32(h - other) } // BytesLE encodes the height as a byte slice in little-endian format. func (h Height) BytesLE() []byte { return util.Uint32ToBytesLE(uint32(h)) } ================================================ FILE: types/height_test.go ================================================ package types_test import ( "testing" "github.com/pactus-project/pactus/types" "github.com/stretchr/testify/assert" ) func TestHeightSafeSub(t *testing.T) { sub := types.Height(10).SafeSub(5) assert.Equal(t, uint32(5), sub) sub = types.Height(5).SafeSub(10) assert.Equal(t, uint32(0), sub) sub = types.Height(10).SafeSub(10) assert.Equal(t, uint32(0), sub) } func TestHeightEncodeAsSlice(t *testing.T) { tests := []struct { height types.Height expected []byte }{ {height: 0, expected: []byte{0, 0, 0, 0}}, {height: 1, expected: []byte{1, 0, 0, 0}}, {height: 255, expected: []byte{0xff, 0, 0, 0}}, {height: 256, expected: []byte{0, 1, 0, 0}}, {height: 65535, expected: []byte{0xff, 0xff, 0, 0}}, {height: 65536, expected: []byte{0, 0, 1, 0}}, } for _, test := range tests { slice := test.height.BytesLE() height := types.HeightFromBytesLE(slice) assert.Equal(t, test.expected, slice) assert.Equal(t, test.height, height) } } ================================================ FILE: types/proposal/errors.go ================================================ package proposal import "errors" // BasicCheckError is returned when the basic check on the proposal fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } // ErrNoSignature is returned when the proposal has no signature. var ErrNoSignature = errors.New("no signature") ================================================ FILE: types/proposal/proposal.go ================================================ package proposal import ( "fmt" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" ) type Proposal struct { data proposalData } type proposalData struct { Height types.Height `cbor:"1,keyasint"` Round types.Round `cbor:"2,keyasint"` Block *block.Block `cbor:"3,keyasint"` Signature *bls.Signature `cbor:"4,keyasint"` } func NewProposal(height types.Height, round types.Round, blk *block.Block) *Proposal { return &Proposal{ data: proposalData{ Height: height, Round: round, Block: blk, }, } } func (p *Proposal) Height() types.Height { return p.data.Height } func (p *Proposal) Round() types.Round { return p.data.Round } func (p *Proposal) Block() *block.Block { return p.data.Block } func (p *Proposal) Signature() *bls.Signature { return p.data.Signature } func (p *Proposal) BasicCheck() error { if p.data.Block == nil { return BasicCheckError{Reason: "no block"} } if p.data.Signature == nil { return BasicCheckError{Reason: "no signature"} } if err := p.data.Block.BasicCheck(); err != nil { return BasicCheckError{Reason: fmt.Sprintf("invalid block: %s", err.Error())} } if p.data.Height <= 0 { return BasicCheckError{Reason: "invalid height"} } if p.data.Round < 0 { return BasicCheckError{Reason: "invalid round"} } return nil } func (p *Proposal) SetSignature(sig *bls.Signature) { p.data.Signature = sig } func (p *Proposal) SignBytes() []byte { return SignBytes(p.Block().Hash(), p.Height(), p.Round()) } func (p *Proposal) MarshalCBOR() ([]byte, error) { return cbor.Marshal(p.data) } func (p *Proposal) UnmarshalCBOR(bs []byte) error { return cbor.Unmarshal(bs, &p.data) } func (p *Proposal) Verify(pubKey crypto.PublicKey) error { if p.data.Signature == nil { return ErrNoSignature } if err := pubKey.VerifyAddress(p.data.Block.Header().ProposerAddress()); err != nil { return err } return pubKey.Verify(p.SignBytes(), p.data.Signature) } func (p *Proposal) Hash() hash.Hash { return hash.CalcHash(p.SignBytes()) } func (p *Proposal) IsForBlock(h hash.Hash) bool { return p.Block().Hash() == h } // LogString returns a concise string representation intended for use in logs. func (p Proposal) LogString() string { b := p.Block() return fmt.Sprintf("{%v/%v 🗃 %v}", p.data.Height, p.data.Round, b.LogString()) } func SignBytes(blockHash hash.Hash, height types.Height, round types.Round) []byte { sb := blockHash.Bytes() sb = append(sb, height.BytesLE()...) sb = append(sb, round.BytesLE()...) return sb } func ChecKSignature(blockHash hash.Hash, height types.Height, round types.Round, sig *bls.Signature, pubKey *bls.PublicKey, ) error { sb := SignBytes(blockHash, height, round) return pubKey.Verify(sb, sig) } ================================================ FILE: types/proposal/proposal_test.go ================================================ package proposal_test import ( "testing" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestProposalMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) prop := ts.GenerateTestProposal(10, 10) data, err := prop.MarshalCBOR() require.NoError(t, err) var p2 proposal.Proposal err = p2.UnmarshalCBOR(data) require.NoError(t, err) } func TestProposalSignBytes(t *testing.T) { ts := testsuite.NewTestSuite(t) prop := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound()) sb := prop.Block().Hash().Bytes() sb = append(sb, prop.Height().BytesLE()...) sb = append(sb, prop.Round().BytesLE()...) assert.Equal(t, sb, prop.SignBytes()) assert.Equal(t, hash.CalcHash(sb), prop.Hash()) } func TestIsForBlock(t *testing.T) { ts := testsuite.NewTestSuite(t) prop := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound()) assert.False(t, prop.IsForBlock(ts.RandHash())) assert.True(t, prop.IsForBlock(prop.Block().Hash())) } func TestProposalSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) proposerKey := ts.RandValKey() prop := ts.GenerateTestProposal(ts.RandHeight(), ts.RandRound(), testsuite.ProposalWithKey(proposerKey)) err := prop.Verify(proposerKey.PublicKey()) require.NoError(t, err) rndValKey := ts.RandValKey() err = prop.Verify(rndValKey.PublicKey()) require.ErrorIs(t, err, crypto.AddressMismatchError{ Expected: rndValKey.Address(), Got: prop.Block().Header().ProposerAddress(), }) ts.HelperSignProposal(rndValKey, prop) err = prop.Verify(proposerKey.PublicKey()) require.ErrorIs(t, crypto.ErrInvalidSignature, err) } func TestBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("No block", func(t *testing.T) { p := &proposal.Proposal{} err := p.BasicCheck() require.ErrorIs(t, err, proposal.BasicCheckError{ Reason: "no block", }) }) t.Run("Invalid height", func(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) p := proposal.NewProposal(0, 0, blk) p.SetSignature(ts.RandBLSSignature()) err := p.BasicCheck() require.ErrorIs(t, err, proposal.BasicCheckError{ Reason: "invalid height", }) }) t.Run("Invalid round", func(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) p := proposal.NewProposal(ts.RandHeight(), -1, blk) p.SetSignature(ts.RandBLSSignature()) err := p.BasicCheck() require.ErrorIs(t, err, proposal.BasicCheckError{ Reason: "invalid round", }) }) t.Run("No signature", func(t *testing.T) { pub, _ := ts.RandBLSKeyPair() data := ts.DecodingHex( "a401186402000358c80140da9b641551048b59a859946ca7f9ab95c9cf84da488a1a5c49ba643b29b653dc223bc20a4e9ff03158165f3d42" + "4e2a74677bfe24a7295d1ce2e55ca3644cbe9a5a5e7d913b8e1ba6a020afbd5a25024a12b37cf8e1ed0b9498f91d75b294db0f95123d8593" + "05aa5deea3d4216777e74310b6a601bb4d4d6b13c9b295781ab1533aea032978d4f89305000000010004060f1b23010fab4f72234cc7c120" + "48bbbc616c005573d8ad4d5c6997996d6f488946cdd78410f0a400c4a7f9bdb41506bdf717a892fa0004f6") prop := &proposal.Proposal{} err := cbor.Unmarshal(data, &prop) require.NoError(t, err) err = prop.BasicCheck() require.ErrorIs(t, err, proposal.BasicCheckError{ Reason: "no signature", }) err = prop.Verify(pub) require.Error(t, err) }) t.Run("Ok", func(t *testing.T) { prop := ts.GenerateTestProposal(100, 0) require.NoError(t, prop.BasicCheck()) }) } ================================================ FILE: types/protocol/protocol.go ================================================ package protocol import ( "fmt" "strconv" ) type Version uint8 const ( ProtocolVersionUnknown Version = 0 ProtocolVersion1 Version = 1 // Initial version ProtocolVersion2 Version = 2 // Split Reward Fork (PIP-43) ProtocolVersion3 Version = 3 // Validator Delegation (PIP-49) ProtocolVersionLatest = ProtocolVersion3 ) func ParseVersion(s string) (Version, error) { v, err := strconv.ParseInt(s, 10, 8) if err != nil { return 0, err } return Version(v), nil } func (v Version) String() string { return fmt.Sprintf("%d", v) } ================================================ FILE: types/protocol/protocol_test.go ================================================ package protocol import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestParseVersion(t *testing.T) { tests := []struct { input string expected Version hasError bool }{ {"1", ProtocolVersion1, false}, {"2", ProtocolVersion2, false}, {"3", ProtocolVersion3, false}, {"3", ProtocolVersionLatest, false}, {"invalid", 0, true}, {"0", 0, false}, {"-1", Version(255), false}, {"127", Version(127), false}, {"128", 0, true}, // out of int8 range } for _, test := range tests { result, err := ParseVersion(test.input) if test.hasError { require.Error(t, err, "ParseVersion(%q) should return error", test.input) } else { require.NoError(t, err, "ParseVersion(%q) should not return error", test.input) assert.Equal(t, test.expected, result, "ParseVersion(%q)", test.input) } } } func TestVersionString(t *testing.T) { tests := []struct { version Version expected string }{ {ProtocolVersion1, "1"}, {ProtocolVersion2, "2"}, {ProtocolVersion3, "3"}, {ProtocolVersionLatest, "3"}, {0, "0"}, {127, "127"}, {255, "255"}, } for _, test := range tests { result := test.version.String() assert.Equal(t, test.expected, result, "Version(%d).String()", test.version) } } ================================================ FILE: types/round.go ================================================ package types import "github.com/pactus-project/pactus/util" type Round int16 // RoundFromBytesLE creates a Round from a byte slice in little-endian format. func RoundFromBytesLE(data []byte) Round { return Round(util.BytesToInt16LE(data)) } // SafeIncrease returns a new Round that is the result of adding count to h. func (h Round) SafeIncrease(count uint32) Round { return Round(uint32(h) + count) } // SafeDecrease returns the result of subtracting other from h, // but it returns 0 if the result would be negative. func (h Round) SafeDecrease(count uint32) Round { if uint32(h) < count { return 0 } return Round(uint32(h) - count) } // SafeSub returns the result of subtracting other from h, // but it returns 0 if the result would be negative. func (h Round) SafeSub(other Round) uint32 { if h < other { return 0 } return uint32(h - other) } // BytesLE encodes the Round as a byte slice in little-endian format. func (h Round) BytesLE() []byte { return util.Int16ToBytesLE(int16(h)) } ================================================ FILE: types/round_test.go ================================================ package types_test import ( "testing" "github.com/pactus-project/pactus/types" "github.com/stretchr/testify/assert" ) func TestRoundSafeSub(t *testing.T) { sub := types.Round(10).SafeSub(5) assert.Equal(t, uint32(5), sub) sub = types.Round(5).SafeSub(10) assert.Equal(t, uint32(0), sub) sub = types.Round(10).SafeSub(10) assert.Equal(t, uint32(0), sub) } func TestRoundEncodeAsSlice(t *testing.T) { tests := []struct { round types.Round expected []byte }{ {round: 0, expected: []byte{0, 0}}, {round: 1, expected: []byte{1, 0}}, {round: 255, expected: []byte{0xff, 0}}, {round: 256, expected: []byte{0, 1}}, {round: -1, expected: []byte{0xff, 0xff}}, } for _, test := range tests { slice := test.round.BytesLE() round := types.RoundFromBytesLE(slice) assert.Equal(t, test.expected, slice) assert.Equal(t, test.round, round) } } ================================================ FILE: types/tx/errors.go ================================================ package tx import ( "errors" "github.com/pactus-project/pactus/types/tx/payload" ) // ErrInvalidSigner is returned when the signer address is not valid. var ErrInvalidSigner = errors.New("invalid signer address") // BasicCheckError is returned when the basic check on the transaction fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } // InvalidPayloadTypeError is returned when the payload type is not valid. type InvalidPayloadTypeError struct { PayloadType payload.Type } func (e InvalidPayloadTypeError) Error() string { return "invalid payload type: " + e.PayloadType.String() } ================================================ FILE: types/tx/factory.go ================================================ package tx import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" ) func NewSubsidyTx(lockTime types.Height, recipients []payload.BatchRecipient, opts ...TxOption, ) *Tx { return NewBatchTransferTx( lockTime, crypto.TreasuryAddress, recipients, 0, opts...) } func NewTransferTx(lockTime types.Height, sender, receiver crypto.Address, amt, fee amount.Amount, opts ...TxOption, ) *Tx { pld := &payload.TransferPayload{ From: sender, To: receiver, Amount: amt, } return newTx(lockTime, pld, fee, opts...) } func NewBatchTransferTx(lockTime types.Height, sender crypto.Address, recipients []payload.BatchRecipient, fee amount.Amount, opts ...TxOption, ) *Tx { pld := &payload.BatchTransferPayload{ From: sender, Recipients: recipients, } return newTx(lockTime, pld, fee, opts...) } func NewBondTx(lockTime types.Height, sender, receiver crypto.Address, pubKey *bls.PublicKey, stake, fee amount.Amount, opts ...TxOption, ) *Tx { pld := &payload.BondPayload{ From: sender, To: receiver, PublicKey: pubKey, Stake: stake, } return newTx(lockTime, pld, fee, opts...) } func NewUnbondTx(lockTime types.Height, val crypto.Address, opts ...TxOption, ) *Tx { pld := &payload.UnbondPayload{ Validator: val, } return newTx(lockTime, pld, 0, opts...) } func NewWithdrawTx(lockTime types.Height, val, acc crypto.Address, amt, fee amount.Amount, opts ...TxOption, ) *Tx { pld := &payload.WithdrawPayload{ From: val, To: acc, Amount: amt, } return newTx(lockTime, pld, fee, opts...) } func NewSortitionTx(lockTime types.Height, addr crypto.Address, proof sortition.Proof, ) *Tx { pld := &payload.SortitionPayload{ Validator: addr, Proof: proof, } return newTx(lockTime, pld, 0) } ================================================ FILE: types/tx/payload/batch_transfer.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/encoding" ) const maxBatchRecipients = 8 type BatchRecipient struct { To crypto.Address Amount amount.Amount } func (tr *BatchRecipient) BasicCheck() error { if !tr.To.IsAccountAddress() { return BasicCheckError{ Reason: "receiver is not an account address: " + tr.To.String(), } } if tr.Amount <= 0 { return BasicCheckError{ Reason: fmt.Sprintf("amount must be greater than zero: %d", tr.Amount), } } return nil } func (tr *BatchRecipient) SerializeSize() int { return tr.To.SerializeSize() + encoding.VarIntSerializeSize(uint64(tr.Amount)) } func (tr *BatchRecipient) Encode(w io.Writer) error { err := tr.To.Encode(w) if err != nil { return err } return encoding.WriteVarInt(w, uint64(tr.Amount)) } func (tr *BatchRecipient) Decode(r io.Reader) error { err := tr.To.Decode(r) if err != nil { return err } amt, err := encoding.ReadVarInt(r) if err != nil { return err } tr.Amount = amount.Amount(amt) return nil } type BatchTransferPayload struct { From crypto.Address Recipients []BatchRecipient } func (*BatchTransferPayload) Type() Type { return TypeBatchTransfer } func (p *BatchTransferPayload) Signer() crypto.Address { return p.From } func (p *BatchTransferPayload) Value() amount.Amount { value := amount.Amount(0) for _, r := range p.Recipients { value += r.Amount } return value } // BasicCheck performs basic checks on the Batch Transfer payload. func (p *BatchTransferPayload) BasicCheck() error { if !p.From.IsAccountAddress() { return BasicCheckError{ Reason: "sender is not an account address: " + p.From.String(), } } if len(p.Recipients) < 2 || len(p.Recipients) > maxBatchRecipients { return BasicCheckError{ Reason: fmt.Sprintf("recipients must be between 2 and %d", maxBatchRecipients), } } for _, r := range p.Recipients { if err := r.BasicCheck(); err != nil { return err } } return nil } func (p *BatchTransferPayload) SerializeSize() int { size := p.From.SerializeSize() size += encoding.VarIntSerializeSize(uint64(len(p.Recipients))) for _, r := range p.Recipients { size += r.SerializeSize() } return size } func (p *BatchTransferPayload) Encode(w io.Writer) error { err := p.From.Encode(w) if err != nil { return err } err = encoding.WriteVarInt(w, uint64(len(p.Recipients))) if err != nil { return err } for _, r := range p.Recipients { err = r.Encode(w) if err != nil { return err } } return nil } func (p *BatchTransferPayload) Decode(_ DecodeContext, r io.Reader) error { err := p.From.Decode(r) if err != nil { return err } numberOfRecipients, err := encoding.ReadVarInt(r) if err != nil { return err } if numberOfRecipients > maxBatchRecipients { return ErrTooManyRecipients } p.Recipients = make([]BatchRecipient, numberOfRecipients) for i := uint64(0); i < numberOfRecipients; i++ { err := p.Recipients[i].Decode(r) if err != nil { return err } } return nil } // LogString returns a concise string representation intended for use in logs. func (p *BatchTransferPayload) LogString() string { return fmt.Sprintf("{BatchTransfer 💸 %s->[%d] %s", p.From.LogString(), len(p.Recipients), p.Value()) } ================================================ FILE: types/tx/payload/batch_transfer_test.go ================================================ package payload_test import ( "io" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBatchTransferType(t *testing.T) { pld := payload.BatchTransferPayload{} assert.Equal(t, payload.TypeBatchTransfer, pld.Type()) } func TestBatchTransferString(t *testing.T) { pld := payload.BatchTransferPayload{} assert.Contains(t, pld.LogString(), "{BatchTransfer ") } func TestBatchTransferDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error }{ { raw: []byte{}, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x00, // sender (Treasury) }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x09, // number Of Recipients (9) }, value: 0, readErr: payload.ErrTooManyRecipients, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, // number Of Recipients (2) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, // receiver-1 }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, // number Of Recipients (2) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver-1 0x80, 0x80, 0x80, // amount-1 }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, // number Of Recipients (2) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver-1 0x80, 0x80, 0x80, 0x01, // amount-1 0x02, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x19, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, // receiver-2 0x80, 0x80, 0x80, // amount-2 }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, // number Of Recipients (2) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver-1 0x80, 0x80, 0x80, 0x01, // amount-1 0x02, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x19, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, // receiver-2 0x80, 0x80, 0x80, 0x02, // amount-2 }, value: 0x200000 + 0x400000, readErr: nil, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, // sender }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x02, // number Of Recipients (2) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver-1 0x80, 0x80, 0x80, 0x01, // amount-1 0x02, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x19, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, // receiver-2 0x80, 0x80, 0x80, 0x02, // amount-2 }, value: 0x600000, readErr: nil, }, } for no, tt := range tests { pld := payload.BatchTransferPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check require.NoError(t, pld.BasicCheck()) // Check signer if tt.raw[0] != 0 { assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } assert.Equal(t, tt.value, pld.Value()) } } } func TestBatchTransferBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { pld payload.BatchTransferPayload err string }{ { pld: payload.BatchTransferPayload{ From: ts.RandAccAddress(), Recipients: []payload.BatchRecipient{}, }, err: "recipients must be between 2 and 8", }, { pld: payload.BatchTransferPayload{ From: ts.RandAccAddress(), Recipients: []payload.BatchRecipient{ {To: ts.RandAccAddress(), Amount: ts.RandAmount()}, }, }, err: "recipients must be between 2 and 8", }, { pld: payload.BatchTransferPayload{ From: ts.RandAccAddress(), Recipients: []payload.BatchRecipient{ {To: ts.RandAccAddress(), Amount: ts.RandAmount()}, {To: ts.RandAccAddress(), Amount: -1}, }, }, err: "amount must be greater than zero: -1", }, { pld: payload.BatchTransferPayload{ From: ts.RandAccAddress(), Recipients: []payload.BatchRecipient{ {To: ts.RandValAddress(), Amount: ts.RandAmount()}, {To: ts.RandAccAddress(), Amount: ts.RandAmount()}, }, }, err: "receiver is not an account address", }, { pld: payload.BatchTransferPayload{ From: ts.RandValAddress(), Recipients: []payload.BatchRecipient{ {To: ts.RandAccAddress(), Amount: ts.RandAmount()}, {To: ts.RandAccAddress(), Amount: ts.RandAmount()}, }, }, err: "sender is not an account address", }, } for no, tt := range tests { assert.ErrorContains(t, tt.pld.BasicCheck(), tt.err, "test %v failed", no) } } ================================================ FILE: types/tx/payload/bond.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/encoding" ) type BondPayload struct { From crypto.Address To crypto.Address PublicKey *bls.PublicKey Stake amount.Amount // Delegation fields DelegateOwner crypto.Address DelegateShare amount.Amount DelegateExpiry types.Height } func (*BondPayload) Type() Type { return TypeBond } func (p *BondPayload) Signer() crypto.Address { return p.From } func (p *BondPayload) Value() amount.Amount { return p.Stake } func (p *BondPayload) IsDelegated() bool { return p.DelegateOwner != crypto.TreasuryAddress } // BasicCheck performs basic checks on the Bond payload. func (p *BondPayload) BasicCheck() error { if !p.From.IsAccountAddress() { return BasicCheckError{ Reason: "sender is not an account address: " + p.From.String(), } } if !p.To.IsValidatorAddress() { return BasicCheckError{ Reason: "receiver is not a validator address: " + p.To.String(), } } if p.PublicKey != nil { if err := p.PublicKey.VerifyAddress(p.To); err != nil { return err } } if p.IsDelegated() { if !p.DelegateOwner.IsAccountAddress() { return BasicCheckError{ Reason: "delegate owner is not an account address: " + p.DelegateOwner.String(), } } if p.DelegateShare < 0 || p.DelegateShare > param.MaxDelegateOwnerRewardShare { return BasicCheckError{ Reason: "delegate share must be between 0 and 0.7 PAC", } } } return nil } func (p *BondPayload) SerializeSize() int { size := 43 + encoding.VarIntSerializeSize(uint64(p.Stake)) if p.PublicKey != nil { size += 96 // pubkey size } if p.IsDelegated() { // delegate owner size (21) + delegate share size (var) + delegate expiry size (4) size += 21 + encoding.VarIntSerializeSize(uint64(p.DelegateShare)) + 4 } return size } func (p *BondPayload) Encode(w io.Writer) error { err := p.From.Encode(w) if err != nil { return err } err = p.To.Encode(w) if err != nil { return err } if p.PublicKey != nil { err := encoding.WriteElements(w, uint8(bls.PublicKeySize)) if err != nil { return err } err = p.PublicKey.Encode(w) if err != nil { return err } } else { err := encoding.WriteElements(w, uint8(0)) if err != nil { return err } } if err := encoding.WriteVarInt(w, uint64(p.Stake)); err != nil { return err } if p.IsDelegated() { if err := p.DelegateOwner.Encode(w); err != nil { return err } if err := encoding.WriteVarInt(w, uint64(p.DelegateShare)); err != nil { return err } if err := encoding.WriteElement(w, p.DelegateExpiry); err != nil { return err } } return nil } func (p *BondPayload) Decode(ctx DecodeContext, r io.Reader) error { err := p.From.Decode(r) if err != nil { return err } err = p.To.Decode(r) if err != nil { return err } pubKeySize, err := encoding.ReadVarInt(r) if err != nil { return err } if pubKeySize == bls.PublicKeySize { p.PublicKey = new(bls.PublicKey) err = p.PublicKey.Decode(r) if err != nil { return err } } else if pubKeySize != 0 { return ErrInvalidPublicKeySize } stake, err := encoding.ReadVarInt(r) if err != nil { return err } p.Stake = amount.Amount(stake) if ctx.WithDelegation { if err := p.DelegateOwner.Decode(r); err != nil { return err } share, err := encoding.ReadVarInt(r) if err != nil { return err } p.DelegateShare = amount.Amount(share) if err := encoding.ReadElement(r, &p.DelegateExpiry); err != nil { return err } } return nil } // LogString returns a concise string representation intended for use in logs. func (p *BondPayload) LogString() string { return fmt.Sprintf("{Bond 🔐 %s->%s %s", p.From.LogString(), p.To.LogString(), p.Stake) } ================================================ FILE: types/tx/payload/bond_test.go ================================================ package payload_test import ( "io" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/state/param" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBondType(t *testing.T) { pld := payload.BondPayload{} assert.Equal(t, payload.TypeBond, pld.Type()) } func TestBondString(t *testing.T) { pld := payload.BondPayload{} assert.Contains(t, pld.LogString(), "{Bond ") } func TestBondDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error }{ { raw: []byte{}, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, // sender }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, // receiver }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x80, 0x80, 0x80, // stake }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x80, 0x80, 0x80, 0x01, // stake }, value: 0x200000, readErr: nil, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x00, // stake is zero }, value: 0x0, readErr: nil, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x01, // public key size }, value: 0x200000, readErr: payload.ErrInvalidPublicKeySize, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x60, // public key size 0xaf, // public key }, value: 0x200000, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0xa1, 0x95, 0xd7, 0xfe, 0xcb, 0xa4, 0xc6, 0x36, 0x83, 0x2f, 0x1d, 0xb0, 0xcd, 0x0e, 0xa1, 0x4d, 0xb6, 0xdb, 0x8c, 0x71, // receiver 0x60, // public key size 0xaf, 0x0f, 0x74, 0x91, 0x7f, 0x50, 0x65, 0xaf, 0x94, 0x72, 0x7a, 0xe9, 0x54, 0x1b, 0x0d, 0xdc, 0xfb, 0x5b, 0x82, 0x8a, 0x9e, 0x01, 0x6b, 0x02, 0x49, 0x8f, 0x47, 0x7e, 0xd3, 0x7f, 0xb4, 0x4d, 0x5d, 0x88, 0x24, 0x95, 0xaf, 0xb6, 0xfd, 0x4f, 0x97, 0x73, 0xe4, 0xea, 0x9d, 0xee, 0xe4, 0x36, 0x03, 0x0c, 0x4d, 0x61, 0xc6, 0xe3, 0xa1, 0x15, 0x15, 0x85, 0xe1, 0xd8, 0x38, 0xca, 0xe1, 0x44, 0x4a, 0x43, 0x8d, 0x08, 0x9c, 0xe7, 0x7e, 0x10, 0xc4, 0x92, 0xa5, 0x5f, 0x69, 0x08, 0x12, 0x5c, 0x5b, 0xe9, 0xb2, 0x36, 0xa2, 0x46, 0xe4, 0x08, 0x2d, 0x08, 0xde, 0x56, 0x4e, 0x11, 0x1e, 0x65, // public key 0x80, 0x80, 0x80, 0x01, // stake }, value: 0x200000, readErr: nil, }, } for no, tt := range tests { pld := payload.BondPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check require.NoError(t, pld.BasicCheck()) // Check signer assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) assert.Equal(t, tt.value, pld.Value()) } } } func TestBondWithDelegateDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error basicErr error }{ { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x80, 0x80, 0x80, 0x01, // stake }, value: 0x200000, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x80, 0x80, 0x80, 0x01, // stake 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, // Delegate Owner }, value: 0x200000, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x80, 0x80, 0x80, 0x01, // stake 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, // Delegate Owner 0x80, 0xca, 0xb5, 0xee, 0x01, // Delegate share: 0.5 PAC }, value: 0x200000, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x00, // public key size 0x80, 0x80, 0x80, 0x01, // stake 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, // Delegate Owner 0x80, 0xca, 0xb5, 0xee, 0x01, // Delegate share: 0.5 PAC 0x10, 0x00, 0x00, 0x00, // Delegate expiry: 1 }, value: 0x200000, readErr: nil, }, } for no, tt := range tests { pld := payload.BondPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{WithDelegation: true}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check if tt.basicErr != nil { err := pld.BasicCheck() require.ErrorIs(t, err, tt.basicErr, "basic check %v failed", no) } else { require.NoError(t, pld.BasicCheck()) // Check signer assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) assert.Equal(t, tt.value, pld.Value()) } } } } func TestBondBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) ranPub, _ := ts.RandBLSKeyPair() tests := []struct { pld payload.BondPayload err string }{ { pld: payload.BondPayload{ From: ts.RandValAddress(), To: ts.RandValAddress(), Stake: ts.RandAmount(), }, err: "sender is not an account address", }, { pld: payload.BondPayload{ From: ts.RandAccAddress(), To: ts.RandAccAddress(), Stake: ts.RandAmount(), }, err: "receiver is not a validator address", }, { pld: payload.BondPayload{ From: ts.RandAccAddress(), To: ts.RandValAddress(), Stake: ts.RandAmount(), PublicKey: ranPub, }, err: "address mismatch", }, { pld: payload.BondPayload{ From: ts.RandAccAddress(), To: ts.RandValAddress(), Stake: ts.RandAmount(), DelegateOwner: ts.RandValAddress(), }, err: "delegate owner is not an account address", }, { pld: payload.BondPayload{ From: ts.RandAccAddress(), To: ts.RandValAddress(), Stake: ts.RandAmount(), DelegateOwner: ts.RandAccAddress(), DelegateShare: -1, }, err: "delegate share must be between 0 and 0.7 PAC", }, { pld: payload.BondPayload{ From: ts.RandAccAddress(), To: ts.RandValAddress(), Stake: ts.RandAmount(), DelegateOwner: ts.RandAccAddress(), DelegateShare: param.MaxDelegateOwnerRewardShare + 1, }, err: "delegate share must be between 0 and 0.7 PAC", }, { pld: payload.BondPayload{ From: ts.RandAccAddress(), To: ts.RandValAddress(), Stake: ts.RandAmount(), DelegateOwner: ts.RandAccAddress(), DelegateShare: 0, // 0 PAC }, err: "", }, } for no, tt := range tests { if tt.err == "" { require.NoError(t, tt.pld.BasicCheck(), "test %v failed", no) } else { assert.ErrorContains(t, tt.pld.BasicCheck(), tt.err, "test %v failed", no) } } } ================================================ FILE: types/tx/payload/errors.go ================================================ package payload import "errors" // ErrInvalidPublicKeySize is returned when the public key size is not valid. var ( ErrInvalidPublicKeySize = errors.New("invalid public key size") ErrTooManyRecipients = errors.New("too many recipients in batch transfer") ) // BasicCheckError describes is returned when the basic check on the transaction's payload fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } ================================================ FILE: types/tx/payload/payload.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" ) type Type uint8 const ( TypeTransfer = Type(1) TypeBond = Type(2) TypeSortition = Type(3) TypeUnbond = Type(4) TypeWithdraw = Type(5) TypeBatchTransfer = Type(6) ) func (t Type) String() string { switch t { case TypeTransfer: return "transfer" case TypeBond: return "bond" case TypeUnbond: return "unbond" case TypeWithdraw: return "withdraw" case TypeSortition: return "sortition" case TypeBatchTransfer: return "batch-transfer" } return fmt.Sprintf("%d", t) } // DecodeContext holds options passed when decoding a payload. type DecodeContext struct { WithDelegation bool } type Payload interface { Signer() crypto.Address Value() amount.Amount Type() Type SerializeSize() int Encode(io.Writer) error Decode(DecodeContext, io.Reader) error BasicCheck() error LogString() string } ================================================ FILE: types/tx/payload/sortition.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/encoding" ) type SortitionPayload struct { Validator crypto.Address Proof sortition.Proof } func (*SortitionPayload) Type() Type { return TypeSortition } func (p *SortitionPayload) Signer() crypto.Address { return p.Validator } func (*SortitionPayload) Value() amount.Amount { return 0 } // BasicCheck performs basic checks on the Sortition payload. func (p *SortitionPayload) BasicCheck() error { if !p.Validator.IsValidatorAddress() { return BasicCheckError{ Reason: "address is not a validator address: " + p.Validator.String(), } } return nil } func (*SortitionPayload) SerializeSize() int { return 69 // 48+21 } func (p *SortitionPayload) Encode(w io.Writer) error { err := p.Validator.Encode(w) if err != nil { return err } return encoding.WriteElements(w, &p.Proof) } func (p *SortitionPayload) Decode(_ DecodeContext, r io.Reader) error { return encoding.ReadElements(r, &p.Validator, &p.Proof) } // LogString returns a concise string representation intended for use in logs. func (p *SortitionPayload) LogString() string { return fmt.Sprintf("{Sortition 🎯 %s", p.Validator.LogString()) } ================================================ FILE: types/tx/payload/sortition_test.go ================================================ package payload_test import ( "io" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSortitionType(t *testing.T) { pld := payload.SortitionPayload{} assert.Equal(t, payload.TypeSortition, pld.Type()) } func TestSortitionString(t *testing.T) { pld := payload.SortitionPayload{} assert.Contains(t, pld.LogString(), "{Sortition ") } func TestSortitionDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error }{ { raw: []byte{}, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, // address }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // address 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, // proof }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // address 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // proof }, value: 0, readErr: nil, }, } for no, tt := range tests { pld := payload.SortitionPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check require.NoError(t, pld.BasicCheck()) // Check signer if tt.raw[0] != 0 { assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } assert.Equal(t, tt.value, pld.Value()) } } } func TestSortitionBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { pld payload.SortitionPayload err string }{ { pld: payload.SortitionPayload{ Validator: ts.RandAccAddress(), }, err: "address is not a validator address", }, } for no, tt := range tests { assert.ErrorContains(t, tt.pld.BasicCheck(), tt.err, "test %v failed", no) } } ================================================ FILE: types/tx/payload/transfer.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/encoding" ) type TransferPayload struct { From crypto.Address To crypto.Address Amount amount.Amount } func (*TransferPayload) Type() Type { return TypeTransfer } func (p *TransferPayload) Signer() crypto.Address { return p.From } func (p *TransferPayload) Value() amount.Amount { return p.Amount } // BasicCheck performs basic checks on the Transfer payload. func (p *TransferPayload) BasicCheck() error { if !p.From.IsAccountAddress() { return BasicCheckError{ Reason: "sender is not an account address: " + p.From.String(), } } if !p.To.IsAccountAddress() { return BasicCheckError{ Reason: "receiver is not an account address: " + p.To.String(), } } return nil } func (p *TransferPayload) SerializeSize() int { return p.From.SerializeSize() + p.To.SerializeSize() + encoding.VarIntSerializeSize(uint64(p.Amount)) } func (p *TransferPayload) Encode(w io.Writer) error { err := p.From.Encode(w) if err != nil { return err } err = p.To.Encode(w) if err != nil { return err } return encoding.WriteVarInt(w, uint64(p.Amount)) } func (p *TransferPayload) Decode(_ DecodeContext, r io.Reader) error { err := p.From.Decode(r) if err != nil { return err } err = p.To.Decode(r) if err != nil { return err } amt, err := encoding.ReadVarInt(r) if err != nil { return err } p.Amount = amount.Amount(amt) return nil } // LogString returns a concise string representation intended for use in logs. func (p *TransferPayload) LogString() string { return fmt.Sprintf("{Transfer 💸 %s->%s %s", p.From.LogString(), p.To.LogString(), p.Amount) } ================================================ FILE: types/tx/payload/transfer_test.go ================================================ package payload_test import ( "io" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTransferType(t *testing.T) { pld := payload.TransferPayload{} assert.Equal(t, payload.TypeTransfer, pld.Type()) } func TestTransferString(t *testing.T) { pld := payload.TransferPayload{} assert.Contains(t, pld.LogString(), "{Transfer ") } func TestTransferDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error }{ { raw: []byte{}, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, // receiver }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x80, 0x80, 0x80, // amount }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x00, // sender (Treasury) 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x80, 0x80, 0x80, 0x01, // amount }, value: 0x200000, readErr: nil, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, // sender }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // sender 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // receiver 0x80, 0x80, 0x80, 0x01, // amount }, value: 0x200000, readErr: nil, }, } for no, tt := range tests { pld := payload.TransferPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check require.NoError(t, pld.BasicCheck()) // Check signer if tt.raw[0] != 0 { assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } assert.Equal(t, tt.value, pld.Value()) } } } func TestTransferBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { pld payload.TransferPayload err string }{ { pld: payload.TransferPayload{ From: ts.RandValAddress(), To: ts.RandAccAddress(), }, err: "sender is not an account address", }, { pld: payload.TransferPayload{ From: ts.RandAccAddress(), To: ts.RandValAddress(), }, err: "receiver is not an account address", }, } for no, tt := range tests { assert.ErrorContains(t, tt.pld.BasicCheck(), tt.err, "test %v failed", no) } } ================================================ FILE: types/tx/payload/unbond.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" ) type UnbondPayload struct { Validator crypto.Address // Delegation fields DelegateOwner crypto.Address } func (*UnbondPayload) Type() Type { return TypeUnbond } func (p *UnbondPayload) Signer() crypto.Address { if p.IsDelegated() { return p.DelegateOwner } return p.Validator } func (*UnbondPayload) Value() amount.Amount { return 0 } // BasicCheck performs basic checks on the Unbond payload. func (p *UnbondPayload) BasicCheck() error { if !p.Validator.IsValidatorAddress() { return BasicCheckError{ Reason: "address is not a validator address: " + p.Validator.String(), } } if p.IsDelegated() { if !p.DelegateOwner.IsAccountAddress() { return BasicCheckError{ Reason: "delegation owner is not an account address: " + p.DelegateOwner.String(), } } } return nil } func (p *UnbondPayload) SerializeSize() int { size := 21 // Validator address size if p.IsDelegated() { size += 21 // Delegate owner address size } return size } func (p *UnbondPayload) Encode(w io.Writer) error { if err := p.Validator.Encode(w); err != nil { return err } if p.IsDelegated() { if err := p.DelegateOwner.Encode(w); err != nil { return err } } return nil } func (p *UnbondPayload) Decode(ctx DecodeContext, r io.Reader) error { if err := p.Validator.Decode(r); err != nil { return err } if ctx.WithDelegation { if err := p.DelegateOwner.Decode(r); err != nil { return err } } return nil } func (p *UnbondPayload) IsDelegated() bool { return p.DelegateOwner != crypto.TreasuryAddress } // LogString returns a concise string representation intended for use in logs. func (p *UnbondPayload) LogString() string { return fmt.Sprintf("{Unbond 🔓 %s", p.Validator.LogString(), ) } ================================================ FILE: types/tx/payload/unbond_test.go ================================================ package payload_test import ( "io" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUnbondType(t *testing.T) { pld := payload.UnbondPayload{} assert.Equal(t, payload.TypeUnbond, pld.Type()) } func TestUnbondString(t *testing.T) { pld := payload.UnbondPayload{} assert.Contains(t, pld.LogString(), "{Unbond ") } func TestUnbondDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error }{ { raw: []byte{}, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, }, value: 0, readErr: io.ErrUnexpectedEOF, }, { raw: []byte{ 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // validator }, value: 0, readErr: nil, }, } for no, tt := range tests { pld := payload.UnbondPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check require.NoError(t, pld.BasicCheck()) // Check signer if tt.raw[0] != 0 { assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } assert.Equal(t, tt.value, pld.Value()) } } } func TestUnbondWithDelegationDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error }{ { raw: []byte{ 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // validator }, value: 0, readErr: io.EOF, }, { raw: []byte{ 0x01, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // validator 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // Delegate Owner }, value: 0, readErr: nil, }, } for no, tt := range tests { pld := payload.UnbondPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{WithDelegation: true}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check require.NoError(t, pld.BasicCheck()) // Check signer if tt.raw[0] != 0 { assert.Equal(t, crypto.Address(tt.raw[21:42]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } assert.Equal(t, tt.value, pld.Value()) } } } func TestUnbondBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { pld payload.UnbondPayload err string }{ { pld: payload.UnbondPayload{ Validator: ts.RandAccAddress(), }, err: "address is not a validator address", }, { pld: payload.UnbondPayload{ Validator: ts.RandValAddress(), DelegateOwner: ts.RandValAddress(), }, err: "delegation owner is not an account address", }, } for no, tt := range tests { assert.ErrorContains(t, tt.pld.BasicCheck(), tt.err, "test %v failed", no) } } ================================================ FILE: types/tx/payload/withdraw.go ================================================ package payload import ( "fmt" "io" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util/encoding" ) type WithdrawPayload struct { From crypto.Address // withdraw from validator address To crypto.Address // deposit to account address Amount amount.Amount // amount to deposit } func (*WithdrawPayload) Type() Type { return TypeWithdraw } func (p *WithdrawPayload) Signer() crypto.Address { return p.From } func (p *WithdrawPayload) Value() amount.Amount { return p.Amount } // BasicCheck performs basic checks on the Withdraw payload. func (p *WithdrawPayload) BasicCheck() error { if !p.From.IsValidatorAddress() { return BasicCheckError{ Reason: "sender is not a validator address: " + p.From.String(), } } if !p.To.IsAccountAddress() { return BasicCheckError{ Reason: "receiver is not an account address: " + p.To.String(), } } return nil } func (p *WithdrawPayload) SerializeSize() int { return p.From.SerializeSize() + p.To.SerializeSize() + encoding.VarIntSerializeSize(uint64(p.Amount)) } func (p *WithdrawPayload) Encode(w io.Writer) error { err := p.From.Encode(w) if err != nil { return err } err = p.To.Encode(w) if err != nil { return err } return encoding.WriteVarInt(w, uint64(p.Amount)) } func (p *WithdrawPayload) Decode(_ DecodeContext, r io.Reader) error { err := p.From.Decode(r) if err != nil { return err } err = p.To.Decode(r) if err != nil { return err } amt, err := encoding.ReadVarInt(r) if err != nil { return err } p.Amount = amount.Amount(amt) return nil } // LogString returns a concise string representation intended for use in logs. func (p *WithdrawPayload) LogString() string { return fmt.Sprintf("{Withdraw 🧾 %s->%s %s", p.From.LogString(), p.To.LogString(), p.Amount) } ================================================ FILE: types/tx/payload/withdraw_test.go ================================================ package payload_test import ( "io" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestWithdrawType(t *testing.T) { pld := payload.WithdrawPayload{} assert.Equal(t, payload.TypeWithdraw, pld.Type()) } func TestWithdrawString(t *testing.T) { pld := payload.WithdrawPayload{} assert.Contains(t, pld.LogString(), "{Withdraw ") } func TestWithdrawDecoding(t *testing.T) { tests := []struct { raw []byte value amount.Amount readErr error basicErr error }{ { raw: []byte{}, value: 0, readErr: io.EOF, basicErr: nil, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, // from }, value: 0, readErr: io.ErrUnexpectedEOF, basicErr: nil, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // from 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, // to }, value: 0, readErr: io.ErrUnexpectedEOF, basicErr: nil, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // from 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // to 0x80, 0x80, 0x80, // amount }, value: 0, readErr: io.EOF, basicErr: nil, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // from 0x02, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x12, 0x23, 0x24, 0x25, // to 0x80, 0x80, 0x80, 0x01, // amount }, value: 0x200000, readErr: nil, basicErr: nil, }, { raw: []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // from 0x00, // to (treasury address) 0x80, 0x80, 0x80, 0x01, // amount }, value: 0x200000, readErr: nil, basicErr: nil, }, } for no, tt := range tests { pld := payload.WithdrawPayload{} r := util.NewFixedReader(len(tt.raw), tt.raw) err := pld.Decode(payload.DecodeContext{}, r) if tt.readErr != nil { require.ErrorIs(t, err, tt.readErr) } else { require.NoError(t, err) for i := 0; i < pld.SerializeSize(); i++ { w := util.NewFixedWriter(i) require.Error(t, pld.Encode(w), "encode test %v failed", no) } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) assert.Len(t, w.Bytes(), pld.SerializeSize()) assert.Equal(t, tt.raw, w.Bytes()) // Basic check if tt.basicErr != nil { require.ErrorIs(t, pld.BasicCheck(), tt.basicErr) } else { require.NoError(t, pld.BasicCheck()) // Check signer if tt.raw[0] != 0 { assert.Equal(t, crypto.Address(tt.raw[:21]), pld.Signer()) } else { assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } assert.Equal(t, tt.value, pld.Value()) } } } } func TestWithdrawBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { pld payload.WithdrawPayload err string }{ { pld: payload.WithdrawPayload{ From: ts.RandAccAddress(), To: ts.RandAccAddress(), }, err: "sender is not a validator address", }, { pld: payload.WithdrawPayload{ From: ts.RandValAddress(), To: ts.RandValAddress(), }, err: "receiver is not an account address", }, } for no, tt := range tests { assert.ErrorContains(t, tt.pld.BasicCheck(), tt.err, "test %v failed", no) } } ================================================ FILE: types/tx/tx.go ================================================ package tx import ( "bytes" "encoding/hex" "fmt" "io" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/encoding" ) const ( versionLatest = 0x01 flagStripedPublicKey = 0x01 flagNotSigned = 0x02 flagWithDelegation = 0x04 maxMemoLength = 64 ) type ID = hash.Hash type Tx struct { memorizedID *ID basicChecked bool data txData } type txData struct { Version uint8 LockTime types.Height Fee amount.Amount Memo string Payload payload.Payload Signature crypto.Signature PublicKey crypto.PublicKey } type TxOption func(*txData) func WithMemo(memo string) TxOption { return func(td *txData) { td.Memo = memo } } func newTx(lockTime types.Height, pld payload.Payload, fee amount.Amount, opts ...TxOption) *Tx { data := txData{ LockTime: lockTime, Version: versionLatest, Payload: pld, Fee: fee, } for _, opt := range opts { opt(&data) } return &Tx{data: data} } // FromString constructs a new transaction from a hex-encoded string. func FromString(str string) (*Tx, error) { bs, err := hex.DecodeString(str) if err != nil { return nil, err } return FromBytes(bs) } // FromBytes constructs a new transaction from raw byte data. func FromBytes(bs []byte) (*Tx, error) { trx := new(Tx) r := bytes.NewReader(bs) if err := trx.Decode(r); err != nil { return nil, err } return trx, nil } func (tx *Tx) Version() uint8 { return tx.data.Version & 0x0f } func (tx *Tx) LockTime() types.Height { return tx.data.LockTime } func (tx *Tx) Payload() payload.Payload { return tx.data.Payload } func (tx *Tx) Fee() amount.Amount { return tx.data.Fee } func (tx *Tx) Memo() string { return tx.data.Memo } func (tx *Tx) PublicKey() crypto.PublicKey { return tx.data.PublicKey } func (tx *Tx) Signature() crypto.Signature { return tx.data.Signature } // IsFreeTx checks if the transaction fee should be set to zero. func (tx *Tx) IsFreeTx() bool { return tx.IsSubsidyTx() || tx.IsSortitionTx() || tx.IsUnbondTx() } func (tx *Tx) SetSignature(sig crypto.Signature) { tx.basicChecked = false tx.data.Signature = sig } func (tx *Tx) SetPublicKey(pub crypto.PublicKey) { tx.basicChecked = false tx.data.PublicKey = pub } func (tx *Tx) BasicCheck() error { if tx.basicChecked { return nil } if tx.Version() != versionLatest { return BasicCheckError{ Reason: fmt.Sprintf("invalid version: %d", tx.Version()), } } if tx.LockTime() == 0 { return BasicCheckError{ Reason: "lock time is not defined", } } if len(tx.Memo()) > maxMemoLength { return BasicCheckError{ Reason: fmt.Sprintf("memo length exceeded: %d", len(tx.Memo())), } } if tx.Payload().Value() < 0 || tx.Payload().Value() > amount.MaxNanoPAC { return BasicCheckError{ Reason: fmt.Sprintf("invalid amount: %s", tx.Payload().Value()), } } if err := tx.Payload().BasicCheck(); err != nil { return BasicCheckError{ Reason: fmt.Sprintf("invalid payload: %s", err.Error()), } } if err := tx.checkFee(); err != nil { return err } if err := tx.checkSignature(); err != nil { return err } tx.basicChecked = true return nil } func (tx *Tx) checkFee() error { if tx.Fee() < 0 || tx.Fee() > amount.MaxNanoPAC { return BasicCheckError{ Reason: fmt.Sprintf("invalid fee: %s", tx.Fee()), } } if tx.IsFreeTx() { if tx.Fee() != 0 { return BasicCheckError{ Reason: fmt.Sprintf("invalid fee: %s", tx.Fee()), } } } return nil } func (tx *Tx) checkSignature() error { if tx.IsSubsidyTx() { // Ensure no signatory is set for subsidy transactions. if tx.PublicKey() != nil || tx.Signature() != nil { return BasicCheckError{ Reason: "subsidy transaction with signatory", } } return nil } // Non-subsidy transactions should have a valid signatory. if tx.PublicKey() == nil { return BasicCheckError{ Reason: "no public key", } } if tx.Signature() == nil { return BasicCheckError{ Reason: "no signature", } } if err := tx.PublicKey().VerifyAddress(tx.Payload().Signer()); err != nil { return BasicCheckError{ Reason: err.Error(), } } signBytes := tx.SignBytes() if err := tx.PublicKey().Verify(signBytes, tx.Signature()); err != nil { return BasicCheckError{ Reason: "invalid signature", } } return nil } // Bytes returns the serialized bytes for the Transaction. func (tx *Tx) Bytes() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) err := tx.Encode(buf) if err != nil { return nil, err } return buf.Bytes(), nil } func (tx *Tx) MarshalCBOR() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) if err := tx.Encode(buf); err != nil { return nil, err } return cbor.Marshal(buf.Bytes()) } func (tx *Tx) UnmarshalCBOR(bs []byte) error { data := make([]byte, 0, tx.SerializeSize()) err := cbor.Unmarshal(bs, &data) if err != nil { return err } buf := bytes.NewBuffer(data) return tx.Decode(buf) } // SerializeSize returns the number of bytes it would take to serialize the transaction. func (tx *Tx) SerializeSize() int { size := 7 + // flag (1) + version (1) + payload type (1) + lock_time (4) encoding.VarIntSerializeSize(uint64(tx.Fee())) + encoding.VarStringSerializeSize(tx.Memo()) if tx.Payload() != nil { size += tx.Payload().SerializeSize() } if tx.data.Signature != nil { size += tx.data.Signature.SerializeSize() } if tx.data.PublicKey != nil { size += tx.data.PublicKey.SerializeSize() } return size } type EncodeOption func(*encodeOptions) type encodeOptions struct { stripPublicKey bool } func defaultEncodeOptions() *encodeOptions { return &encodeOptions{ stripPublicKey: false, } } func StripPublicKey() EncodeOption { return func(opts *encodeOptions) { opts.stripPublicKey = true } } func (tx *Tx) Encode(w io.Writer, opts ...EncodeOption) error { encOpts := defaultEncodeOptions() for _, opt := range opts { opt(encOpts) } flags := uint8(flagNotSigned) if tx.IsSigned() { flags = util.UnsetFlag(flags, flagNotSigned) if encOpts.stripPublicKey || tx.IsPublicKeyStriped() { flags = util.SetFlag(flags, flagStripedPublicKey) } } if pld, ok := tx.data.Payload.(*payload.BondPayload); ok && pld.IsDelegated() { flags = util.SetFlag(flags, flagWithDelegation) } if pld, ok := tx.data.Payload.(*payload.UnbondPayload); ok && pld.IsDelegated() { flags = util.SetFlag(flags, flagWithDelegation) } err := encoding.WriteElement(w, flags) if err != nil { return err } err = tx.encodeWithNoSignatory(w) if err != nil { return err } if tx.data.Signature != nil { err = tx.data.Signature.Encode(w) if err != nil { return err } } if tx.data.PublicKey != nil && !encOpts.stripPublicKey { err = tx.data.PublicKey.Encode(w) if err != nil { return err } } return nil } func (tx *Tx) encodeWithNoSignatory(w io.Writer) error { err := encoding.WriteElements(w, tx.data.Version, tx.data.LockTime) if err != nil { return err } err = encoding.WriteVarInt(w, uint64(tx.data.Fee)) if err != nil { return err } err = encoding.WriteVarString(w, tx.data.Memo) if err != nil { return err } err = encoding.WriteElement(w, uint8(tx.data.Payload.Type())) if err != nil { return err } err = tx.data.Payload.Encode(w) if err != nil { return err } return nil } func (tx *Tx) Decode(r io.Reader) error { flags := uint8(0) err := encoding.ReadElements(r, &flags, &tx.data.Version, &tx.data.LockTime) if err != nil { return err } fee, err := encoding.ReadVarInt(r) if err != nil { return err } tx.data.Fee = amount.Amount(fee) tx.data.Memo, err = encoding.ReadVarString(r) if err != nil { return err } payloadType := uint8(0) err = encoding.ReadElement(r, &payloadType) if err != nil { return err } switch typ := payload.Type(payloadType); typ { case payload.TypeTransfer: tx.data.Payload = new(payload.TransferPayload) case payload.TypeBond: tx.data.Payload = new(payload.BondPayload) case payload.TypeUnbond: tx.data.Payload = new(payload.UnbondPayload) case payload.TypeWithdraw: tx.data.Payload = new(payload.WithdrawPayload) case payload.TypeSortition: tx.data.Payload = new(payload.SortitionPayload) case payload.TypeBatchTransfer: tx.data.Payload = new(payload.BatchTransferPayload) default: return InvalidPayloadTypeError{ PayloadType: typ, } } ctx := payload.DecodeContext{ WithDelegation: util.IsFlagSet(flags, flagWithDelegation), } err = tx.data.Payload.Decode(ctx, r) if err != nil { return err } if util.IsFlagSet(flags, flagNotSigned) { return nil } // It is a signed transaction, Decode signatory. sig, err := tx.decodeSignature(r) if err != nil { return err } tx.data.Signature = sig if util.IsFlagSet(flags, flagStripedPublicKey) { return nil } // It has a public key, decode it. pub, err := tx.decodePublicKey(r) if err != nil { return err } tx.data.PublicKey = pub return nil } func (tx *Tx) decodeSignature(r io.Reader) (crypto.Signature, error) { switch tx.data.Payload.Signer().Type() { case crypto.AddressTypeValidator, crypto.AddressTypeBLSAccount: sig := new(bls.Signature) err := sig.Decode(r) return sig, err case crypto.AddressTypeEd25519Account: sig := new(ed25519.Signature) err := sig.Decode(r) return sig, err case crypto.AddressTypeTreasury: return nil, ErrInvalidSigner default: return nil, ErrInvalidSigner } } func (tx *Tx) decodePublicKey(r io.Reader) (crypto.PublicKey, error) { switch tx.data.Payload.Signer().Type() { case crypto.AddressTypeValidator, crypto.AddressTypeBLSAccount: pub := new(bls.PublicKey) err := pub.Decode(r) return pub, err case crypto.AddressTypeEd25519Account: pub := new(ed25519.PublicKey) err := pub.Decode(r) return pub, err case crypto.AddressTypeTreasury: return nil, ErrInvalidSigner default: return nil, ErrInvalidSigner } } // LogString returns a concise string representation intended for use in logs. func (tx *Tx) LogString() string { return fmt.Sprintf("{⌘ %v - %v 🏵 %v}", tx.ID().LogString(), tx.LockTime(), tx.data.Payload.LogString()) } func (tx *Tx) SignBytes() []byte { buf := bytes.Buffer{} err := tx.encodeWithNoSignatory(&buf) if err != nil { return nil } return buf.Bytes() } func (tx *Tx) ID() ID { if tx.memorizedID != nil { return *tx.memorizedID } id := hash.CalcHash(tx.SignBytes()) tx.memorizedID = &id return id } func (tx *Tx) IsTransferTx() bool { return tx.Payload().Type() == payload.TypeTransfer } func (tx *Tx) IsBatchTransferTx() bool { return tx.Payload().Type() == payload.TypeBatchTransfer } func (tx *Tx) IsBondTx() bool { return tx.Payload().Type() == payload.TypeBond } func (tx *Tx) IsSubsidyTx() bool { return tx.Payload().Signer() == crypto.TreasuryAddress } func (tx *Tx) IsSortitionTx() bool { return tx.Payload().Type() == payload.TypeSortition } func (tx *Tx) IsUnbondTx() bool { return tx.Payload().Type() == payload.TypeUnbond } func (tx *Tx) IsWithdrawTx() bool { return tx.Payload().Type() == payload.TypeWithdraw } // StripPublicKey removes the public key from the transaction. // It is an alias function for `SetPublicKey(nil)`. func (tx *Tx) StripPublicKey() { tx.SetPublicKey(nil) } // IsPublicKeyStriped returns true if the public key stripped from the transaction. func (tx *Tx) IsPublicKeyStriped() bool { if tx.data.PublicKey != nil { return false } if tx.IsSubsidyTx() { // Subsidy transactions do not have a public key, but they are not considered striped. return false } return true } // IsSigned returns true if the transaction has been signed and includes the signature. func (tx *Tx) IsSigned() bool { return tx.data.Signature != nil } ================================================ FILE: types/tx/tx_test.go ================================================ package tx_test import ( "encoding/hex" "fmt" "strings" "testing" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCBORMarshaling(t *testing.T) { ts := testsuite.NewTestSuite(t) tx1 := ts.GenerateTestTransferTx() bz, err := cbor.Marshal(tx1) require.NoError(t, err) tx2 := new(tx.Tx) require.NoError(t, cbor.Unmarshal(bz, tx2)) assert.Equal(t, tx1.ID(), tx2.ID()) require.Error(t, cbor.Unmarshal([]byte{1}, tx2)) } func TestEncodingTx(t *testing.T) { ts := testsuite.NewTestSuite(t) trx1 := ts.GenerateTestTransferTx() trx2 := ts.GenerateTestSubsidyTx() trx3 := ts.GenerateTestBatchTransferTx() trx4 := ts.GenerateTestBondTx() trx5 := ts.GenerateTestUnbondTx() trx6 := ts.GenerateTestWithdrawTx() trx7 := ts.GenerateTestSortitionTx() tests := []*tx.Tx{trx1, trx2, trx3, trx4, trx5, trx6, trx7} for _, trx := range tests { require.NoError(t, trx.BasicCheck()) require.NoError(t, trx.BasicCheck()) // double basic check length := trx.SerializeSize() for i := 0; i < length; i++ { w := util.NewFixedWriter(i) require.Error(t, trx.Encode(w), "encode test %v failed", i) } w := util.NewFixedWriter(length) require.NoError(t, trx.Encode(w)) for i := 0; i < length; i++ { newTrx := new(tx.Tx) r := util.NewFixedReader(i, w.Bytes()) require.Error(t, newTrx.Decode(r), "decode test %v failed", i) } bz, err := trx.Bytes() require.NoError(t, err) decodedTrx, err := tx.FromBytes(bz) require.NoError(t, err) assert.Equal(t, trx.ID(), decodedTrx.ID()) } _, err := tx.FromString("badcow") require.Error(t, err) } func TestTxIDNoSignatory(t *testing.T) { ts := testsuite.NewTestSuite(t) trx := ts.GenerateTestTransferTx() id1 := trx.ID() trx.SetSignature(nil) trx.SetPublicKey(nil) id2 := trx.ID() require.Equal(t, id1, id2) } func TestBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("LockTime is not defined", func(t *testing.T) { trx := tx.NewTransferTx(0, ts.RandAccAddress(), ts.RandAccAddress(), ts.RandAmount(), ts.RandFee()) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "lock time is not defined", }) }) t.Run("Big memo, Should returns error", func(t *testing.T) { bigMemo := strings.Repeat("a", 65) trx := tx.NewTransferTx(ts.RandHeight(), ts.RandAccAddress(), ts.RandAccAddress(), ts.RandAmount(), ts.RandFee(), tx.WithMemo(bigMemo)) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "memo length exceeded: 65", }) }) t.Run("Invalid payload, Should returns error", func(t *testing.T) { invAddr := ts.RandAccAddress() invAddr[0] = 4 trx := tx.NewTransferTx(ts.RandHeight(), ts.RandAccAddress(), invAddr, 1e9, ts.RandFee()) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid payload: receiver is not an account address: " + invAddr.String(), }) }) t.Run("Invalid amount", func(t *testing.T) { trx := tx.NewTransferTx(ts.RandHeight(), ts.RandAccAddress(), ts.RandAccAddress(), -1, 1) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid amount: -0.000000001 PAC", }) }) t.Run("Invalid amount", func(t *testing.T) { trx := tx.NewTransferTx(ts.RandHeight(), ts.RandAccAddress(), ts.RandAccAddress(), (42e15)+1, 1) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid amount: 42,000,000 PAC", }) }) t.Run("Invalid signer address", func(t *testing.T) { valKey := ts.RandValKey() trx := tx.NewTransferTx(ts.RandHeight(), ts.RandAccAddress(), ts.RandAccAddress(), 1, 1) sig := valKey.PrivateKey().Sign(trx.SignBytes()) trx.SetSignature(sig) trx.SetPublicKey(valKey.PublicKey()) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: fmt.Sprintf("address mismatch: expected %s, got %s", valKey.PublicKey().AccountAddress(), trx.Payload().Signer()), }) }) t.Run("Invalid version", func(t *testing.T) { str := "02" + // Flags "02" + // Version "01020304" + // LockTime "01" + // Fee "00" + // Memo "01" + // PayloadType "00" + // Sender (treasury) "012222222222222222222222222222222222222222" + // Receiver "01" // Amount trx, err := tx.FromString(str) require.NoError(t, err) err = trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid version: 2", }) }) } func TestInvalidPayloadType(t *testing.T) { str := "02" + // Flags "01" + // Version "01020300" + // LockTime "01" + // Fee "00" + // Memo "07" + // PayloadType "00" + // Sender (treasury) "012222222222222222222222222222222222222222" + // Receiver "01" // Amount _, err := tx.FromString(str) require.ErrorIs(t, err, tx.InvalidPayloadTypeError{ PayloadType: payload.Type(7), }) } func TestSubsidyTx(t *testing.T) { ts := testsuite.NewTestSuite(t) pub, prv := ts.RandEd25519KeyPair() t.Run("Has signature", func(t *testing.T) { trx := ts.GenerateTestSubsidyTx() sig := prv.Sign(trx.SignBytes()) trx.SetSignature(sig) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "subsidy transaction with signatory", }) }) t.Run("Has public key", func(t *testing.T) { trx := ts.GenerateTestSubsidyTx() trx.SetPublicKey(pub) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "subsidy transaction with signatory", }) }) t.Run("Strip public key", func(t *testing.T) { trx := ts.GenerateTestSubsidyTx() trx.StripPublicKey() err := trx.BasicCheck() require.NoError(t, err) assert.False(t, trx.IsPublicKeyStriped()) }) } func TestInvalidSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Good", func(t *testing.T) { trx := ts.GenerateTestTransferTx() require.NoError(t, trx.BasicCheck()) }) t.Run("No signature", func(t *testing.T) { trx := ts.GenerateTestTransferTx() trx.SetSignature(nil) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "no signature", }) }) t.Run("No public key", func(t *testing.T) { trx := ts.GenerateTestTransferTx() trx.SetPublicKey(nil) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "no public key", }) }) pbInv, pvInv := ts.RandBLSKeyPair() t.Run("Invalid signature", func(t *testing.T) { trx := ts.GenerateTestTransferTx() sig := pvInv.Sign(trx.SignBytes()) trx.SetSignature(sig) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid signature", }) }) t.Run("Invalid public key", func(t *testing.T) { trx := ts.GenerateTestTransferTx() trx.SetPublicKey(pbInv) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: fmt.Sprintf("address mismatch: expected %s, got %s", pbInv.AccountAddress(), trx.Payload().Signer()), }) }) t.Run("Invalid sign Bytes", func(t *testing.T) { valKey := ts.RandValKey() trx0 := ts.GenerateTestUnbondTx(testsuite.TransactionWithSigner(valKey.PrivateKey())) trx := tx.NewUnbondTx(trx0.LockTime(), valKey.Address(), tx.WithMemo("invalidate signature")) trx.SetPublicKey(trx0.PublicKey()) trx.SetSignature(trx0.Signature()) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid signature", }) }) t.Run("Zero signature", func(t *testing.T) { trx := ts.GenerateTestTransferTx() trx.SetSignature(&bls.Signature{}) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid signature", }) }) t.Run("Zero public key", func(t *testing.T) { trx := ts.GenerateTestTransferTx() zeroPubKey := &bls.PublicKey{} trx.SetPublicKey(zeroPubKey) err := trx.BasicCheck() require.ErrorIs(t, err, tx.BasicCheckError{ Reason: fmt.Sprintf("address mismatch: expected %s, got %s", zeroPubKey.AccountAddress().String(), trx.Payload().Signer()), }) }) } func TestSignBytesBLS(t *testing.T) { data, _ := hex.DecodeString( "00" + // Flags "01" + // Version "01020304" + // LockTime "e807" + // Fee "0474657374" + // Memo "01" + // PayloadType "022109324a70c5bd7a0591bcd8d597cb3a06a91770" + // Sender (pc1zyyynyjnsck7h5pv3hnvdt97t8gr2j9ms0vrrp7) "02b00c16e60f46390455baff5a8b69ac70e67f10c8" + // Receiver (pc1zkqxpdes0gcusg4d6ladgk6dvwrn87yxgumzwn3) "a09c01" + // Amount "86d45b6532d447070cf1ee67d4a04a13f337f6a2bfd6c54419efdd4b502b529d3f3be52567d8adaf494e0edc93d4ae51" + // Signature "b805043a816c3213c67f365f83c6946546049f517ebe470f186b36ff53fb996ae2468b119582a7f18fe8f0bfb4e055d5" + // PublicKey "190601a983fb4636c36287a73d80dbb14f244f319da5eeac02ce7ee9026245ac36b9978cabd6d2cbb3c1f87e55e2fc29") txID, _ := hash.FromString("7ab1287fe4882918e69b9f83215378ea08f2d91e0700c2e35a73b7aae1d7bf2d") trx, err := tx.FromBytes(data) require.NoError(t, err) assert.Equal(t, len(data), trx.SerializeSize()) signBytes := data[1 : len(data)-bls.PublicKeySize-bls.SignatureSize] assert.Equal(t, signBytes, trx.SignBytes()) assert.Equal(t, hash.CalcHash(signBytes), trx.ID()) assert.Equal(t, txID, trx.ID()) assert.Equal(t, types.Height(0x04030201), trx.LockTime()) assert.Equal(t, "test", trx.Memo()) assert.Equal(t, amount.Amount(1000), trx.Fee()) assert.Equal(t, amount.Amount(20000), trx.Payload().Value()) assert.Equal(t, "pc1zyyynyjnsck7h5pv3hnvdt97t8gr2j9ms0vrrp7", trx.Payload().Signer().String()) } func TestSignBytesEd25519(t *testing.T) { data, _ := hex.DecodeString( "00" + // Flags "01" + // Version "01020300" + // LockTime "e807" + // Fee (1000) "0474657374" + // Memo ("test") "01" + // PayloadType "037098338e0b6808119dfd4457ab806b9c2059b89b" + // Sender (pc1rwzvr8rstdqypr80ag3t6hqrtnss9nwymcxy3lr) "037a14ae24533816e7faaa6ed28fcdde8e55a7df21" + // Receiver (pc1r0g22ufzn8qtw0742dmfglnw73e260hep0k3yra) "a09c01" + // Amount (20000) "95794161374b22c696dabb98e93f6ca9300b22f3b904921fbf560bb72145f4fa" + // Signature "50ac25c7125271489b0cd230549257c93fb8c6265f2914a988ba7b81c1bc47ff" + // PublicKey "f027412dd59447867911035ff69742d171060a1f132ac38b95acc6e39ec0bd09") txID, _ := hash.FromString("34cd4656a98f7eb996e83efdc384cefbe3a9c52dca79a99245b4eacc0b0b4311") trx, err := tx.FromBytes(data) require.NoError(t, err) assert.Equal(t, len(data), trx.SerializeSize()) signBytes := data[1 : len(data)-ed25519.PublicKeySize-ed25519.SignatureSize] assert.Equal(t, signBytes, trx.SignBytes()) assert.Equal(t, hash.CalcHash(signBytes), trx.ID()) assert.Equal(t, txID, trx.ID()) assert.Equal(t, types.Height(0x00030201), trx.LockTime()) assert.Equal(t, "test", trx.Memo()) assert.Equal(t, amount.Amount(1000), trx.Fee()) assert.Equal(t, amount.Amount(20000), trx.Payload().Value()) assert.Equal(t, "pc1rwzvr8rstdqypr80ag3t6hqrtnss9nwymcxy3lr", trx.Payload().Signer().String()) } func TestStripPublicKey(t *testing.T) { ts := testsuite.NewTestSuite(t) trx1 := ts.GenerateTestTransferTx() id1 := trx1.ID() require.NoError(t, trx1.BasicCheck()) trx1.StripPublicKey() assert.True(t, trx1.IsPublicKeyStriped()) assert.Equal(t, id1, trx1.ID()) require.ErrorIs(t, trx1.BasicCheck(), tx.BasicCheckError{ Reason: "no public key", }) bs1, _ := trx1.Bytes() trx2, _ := tx.FromBytes(bs1) bs2, _ := trx2.Bytes() assert.Equal(t, bs1, bs2) assert.Equal(t, trx1.ID(), trx2.ID()) assert.Nil(t, trx2.PublicKey()) } func TestFlagNotSigned(t *testing.T) { ts := testsuite.NewTestSuite(t) trx := tx.NewTransferTx(ts.RandHeight(), ts.RandAccAddress(), ts.RandAccAddress(), ts.RandAmount(), ts.RandFee()) assert.False(t, trx.IsSigned(), "FlagNotSigned should not be set for new transactions") trx.SetSignature(ts.RandBLSSignature()) assert.True(t, trx.IsSigned(), "FlagNotSigned should be set for a signed transaction") trx.SetSignature(nil) assert.False(t, trx.IsSigned(), "FlagNotSigned should not be set when the signature is set to nil") } func TestInvalidSignerSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) trx := tx.NewTransferTx(ts.RandHeight(), crypto.TreasuryAddress, ts.RandAccAddress(), ts.RandAmount(), ts.RandFee()) trx.SetSignature(ts.RandBLSSignature()) bytes, _ := trx.Bytes() _, err := tx.FromBytes(bytes) require.ErrorIs(t, err, tx.ErrInvalidSigner) } func TestInvalidSignerPublicKey(t *testing.T) { ts := testsuite.NewTestSuite(t) trx := tx.NewTransferTx(ts.RandHeight(), crypto.TreasuryAddress, ts.RandAccAddress(), ts.RandAmount(), ts.RandFee()) pub, _ := ts.RandBLSKeyPair() trx.SetSignature(ts.RandBLSSignature()) trx.SetPublicKey(pub) bytes, _ := trx.Bytes() _, err := tx.FromBytes(bytes) require.ErrorIs(t, err, tx.ErrInvalidSigner) } func TestIsFreeTx(t *testing.T) { ts := testsuite.NewTestSuite(t) trx1 := ts.GenerateTestTransferTx() trx2 := ts.GenerateTestBatchTransferTx() trx3 := ts.GenerateTestBondTx() trx4 := ts.GenerateTestUnbondTx() trx5 := ts.GenerateTestWithdrawTx() trx6 := ts.GenerateTestSortitionTx() assert.True(t, trx1.IsTransferTx()) assert.True(t, trx2.IsBatchTransferTx()) assert.True(t, trx3.IsBondTx()) assert.True(t, trx4.IsUnbondTx()) assert.True(t, trx5.IsWithdrawTx()) assert.True(t, trx6.IsSortitionTx()) assert.False(t, trx1.IsFreeTx()) assert.False(t, trx2.IsFreeTx()) assert.False(t, trx3.IsFreeTx()) assert.True(t, trx4.IsFreeTx()) assert.False(t, trx5.IsFreeTx()) assert.True(t, trx6.IsFreeTx()) } func TestCheckFee(t *testing.T) { ts := testsuite.NewTestSuite(t) tests := []struct { name string trx *tx.Tx expectedErr error }{ { name: "Negative fee", trx: ts.GenerateTestTransferTx( testsuite.TransactionWithFee(-1)), expectedErr: tx.BasicCheckError{Reason: "invalid fee: -0.000000001 PAC"}, }, { name: "Big fee", trx: ts.GenerateTestTransferTx( testsuite.TransactionWithFee(42e15 + 1)), expectedErr: tx.BasicCheckError{Reason: "invalid fee: 42,000,000 PAC"}, }, { name: "Subsidy transaction with fee", trx: tx.NewTransferTx(ts.RandHeight(), crypto.TreasuryAddress, ts.RandAccAddress(), ts.RandAmount(), 1), expectedErr: tx.BasicCheckError{Reason: "invalid fee: 0.000000001 PAC"}, }, { name: "Subsidy transaction with zero fee", trx: tx.NewTransferTx(ts.RandHeight(), crypto.TreasuryAddress, ts.RandAccAddress(), ts.RandAmount(), 0), expectedErr: nil, }, { name: "Transfer transaction with zero fee", trx: ts.GenerateTestTransferTx( testsuite.TransactionWithFee(0)), expectedErr: nil, }, { name: "Transfer transaction with non-zero fee", trx: ts.GenerateTestTransferTx( testsuite.TransactionWithFee(1)), expectedErr: nil, }, { name: "Unbond transaction with zero fee", trx: ts.GenerateTestUnbondTx( testsuite.TransactionWithFee(0)), expectedErr: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.trx.BasicCheck() require.ErrorIs(t, err, tt.expectedErr) }) } } ================================================ FILE: types/validator/validator.go ================================================ // Package validator provides functionality for managing validator information. package validator import ( "bytes" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/util/encoding" ) // The Validator struct represents a validator object. type Validator struct { data validatorData } // validatorData contains the data associated with a validator. type validatorData struct { PublicKey *bls.PublicKey Number int32 Stake amount.Amount LastBondingHeight types.Height UnbondingHeight types.Height LastSortitionHeight types.Height // Optional delegation (PIP-49). Zero DelegateOwner means not delegated. DelegateOwner crypto.Address DelegateShare amount.Amount DelegateExpiry types.Height // The protocol version of the validator. // This is in memory and not saved to the blockchain. ProtocolVersion protocol.Version } const delegationPayloadSize = 21 + 8 + 4 // owner + share + expiry // NewValidator constructs a new validator from the given public key and number. func NewValidator(publicKey *bls.PublicKey, number int32) *Validator { val := &Validator{ data: validatorData{ PublicKey: publicKey, Number: number, }, } return val } // FromBytes constructs a new validator from raw byte data. func FromBytes(data []byte) (*Validator, error) { val := new(Validator) reader := bytes.NewReader(data) val.data.PublicKey = new(bls.PublicKey) if err := val.data.PublicKey.Decode(reader); err != nil { return nil, err } err := encoding.ReadElements(reader, &val.data.Number, &val.data.Stake, &val.data.LastBondingHeight, &val.data.UnbondingHeight, &val.data.LastSortitionHeight, ) if err != nil { return nil, err } // Optional delegation (PIP-49) if reader.Len() > 0 { if err := val.data.DelegateOwner.Decode(reader); err != nil { return nil, err } if err := encoding.ReadElements(reader, &val.data.DelegateShare, &val.data.DelegateExpiry); err != nil { return nil, err } } return val, nil } // PublicKey returns the public key of the validator. func (val *Validator) PublicKey() *bls.PublicKey { return val.data.PublicKey } // Address returns the address of the validator. func (val *Validator) Address() crypto.Address { return val.data.PublicKey.ValidatorAddress() } // Number returns the number of the validator. func (val *Validator) Number() int32 { return val.data.Number } // Stake returns the stake of the validator. func (val *Validator) Stake() amount.Amount { return val.data.Stake } // LastBondingHeight returns the last height in which the validator bonded stake. func (val *Validator) LastBondingHeight() types.Height { return val.data.LastBondingHeight } // UnbondingHeight returns the last height in which the validator unbonded stake. func (val *Validator) UnbondingHeight() types.Height { return val.data.UnbondingHeight } // IsUnbonded returns true if the validator is unbonded. func (val *Validator) IsUnbonded() bool { return val.data.UnbondingHeight > 0 } // IsDelegated returns true if the validator has delegation (stake owner != operator). func (val *Validator) IsDelegated() bool { return val.data.DelegateOwner != crypto.TreasuryAddress } // DelegateOwner returns the stake owner account address for delegated validators. func (val *Validator) DelegateOwner() crypto.Address { return val.data.DelegateOwner } // DelegateShare returns the stake owner's reward share (in nano PAC) for delegated validators. func (val *Validator) DelegateShare() amount.Amount { return val.data.DelegateShare } // DelegateExpiry returns the block height at which delegation expires (0 = no expiry). func (val *Validator) DelegateExpiry() types.Height { return val.data.DelegateExpiry } // DelegateExpired returns true if delegation has expired at the given height. func (val *Validator) DelegateExpired(height types.Height) bool { if !val.IsDelegated() { return false } return val.data.DelegateExpiry <= height } // SetDelegation sets the delegation fields (PIP-49). Use zero owner to clear delegation. func (val *Validator) SetDelegation(owner crypto.Address, share amount.Amount, expiry types.Height) { val.data.DelegateOwner = owner val.data.DelegateShare = share val.data.DelegateExpiry = expiry } // LastSortitionHeight returns the last height in which the validator evaluated sortition. func (val *Validator) LastSortitionHeight() types.Height { return val.data.LastSortitionHeight } // Power returns the power of the validator. func (val *Validator) Power() int64 { if val.data.UnbondingHeight > 0 { // Power for unbonded validators is set to zero. return 0 } else if val.data.Stake == 0 { // Only bootstrap validators at the genesis block have no stake. return 1 } return int64(val.data.Stake) } // SubtractFromStake subtracts the given amount from the validator's stake. func (val *Validator) SubtractFromStake(amt amount.Amount) { val.data.Stake -= amt } // AddToStake adds the given amount to the validator's stake. func (val *Validator) AddToStake(amt amount.Amount) { val.data.Stake += amt } // UpdateLastSortitionHeight updates the last height at which the validator performed a valid sortition. func (val *Validator) UpdateLastSortitionHeight(height types.Height) { val.data.LastSortitionHeight = height } // UpdateLastBondingHeight updates the last height at which the validator bonded some stakes. func (val *Validator) UpdateLastBondingHeight(height types.Height) { val.data.LastBondingHeight = height } // UpdateUnbondingHeight updates the unbonding height for the validator. func (val *Validator) UpdateUnbondingHeight(height types.Height) { val.data.UnbondingHeight = height } // Hash calculates and returns the hash of the validator. func (val *Validator) Hash() hash.Hash { bs, err := val.Bytes() if err != nil { panic(err) } return hash.CalcHash(bs) } // SerializeSize returns the size in bytes required to serialize the validator. func (val *Validator) SerializeSize() int { size := 120 // 96+4+4+8+4+4 if val.IsDelegated() { size += delegationPayloadSize } return size } // Bytes returns the serialized byte representation of the validator. func (val *Validator) Bytes() ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, val.SerializeSize())) if err := val.data.PublicKey.Encode(buf); err != nil { return nil, err } err := encoding.WriteElements(buf, val.data.Number, val.data.Stake, val.data.LastBondingHeight, val.data.UnbondingHeight, val.data.LastSortitionHeight) if err != nil { return nil, err } if val.IsDelegated() { if err := val.data.DelegateOwner.Encode(buf); err != nil { return nil, err } if err := encoding.WriteElements(buf, val.data.DelegateShare, val.data.DelegateExpiry); err != nil { return nil, err } } return buf.Bytes(), nil } // Clone creates a deep copy of the validator. func (val *Validator) Clone() *Validator { cloned := new(Validator) *cloned = *val return cloned } // UpdateProtocolVersion updates the protocol version of the validator. func (val *Validator) UpdateProtocolVersion(ver protocol.Version) { val.data.ProtocolVersion = ver } // ProtocolVersion returns the protocol version of the validator. func (val *Validator) ProtocolVersion() protocol.Version { return val.data.ProtocolVersion } // IsActive returns true if the validator is active (has stake and is not unbonded). func (val *Validator) IsActive() bool { return val.Stake() > 0 && !val.IsUnbonded() } ================================================ FILE: types/validator/validator_test.go ================================================ package validator_test import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFromBytes(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator() assert.False(t, val1.IsDelegated()) assert.False(t, val1.DelegateExpired(ts.RandHeight())) // Round-trip serialization data, err := val1.Bytes() require.NoError(t, err) assert.Len(t, data, 120) for i := range len(data) { _, err := validator.FromBytes(data[:i]) require.Error(t, err) } val2, err := validator.FromBytes(data) require.NoError(t, err) assert.Equal(t, val1.Hash(), val2.Hash()) assert.Equal(t, val1.Address(), val2.Address()) assert.Equal(t, val1.Number(), val2.Number()) } func TestFromBytesDelegation(t *testing.T) { ts := testsuite.NewTestSuite(t) val1 := ts.GenerateTestValidator() owner := ts.RandAccAddress() share := amount.Amount(350_000_000) // 0.35 PAC expiry := types.Height(1000) val1.SetDelegation(owner, share, expiry) assert.True(t, val1.IsDelegated()) assert.Equal(t, owner, val1.DelegateOwner()) assert.Equal(t, share, val1.DelegateShare()) assert.Equal(t, expiry, val1.DelegateExpiry()) assert.False(t, val1.DelegateExpired(999)) assert.True(t, val1.DelegateExpired(1000)) assert.True(t, val1.DelegateExpired(1001)) // Round-trip serialization with delegation data, err := val1.Bytes() require.NoError(t, err) assert.Len(t, data, 120+21+8+4) for i := range 32 { _, err := validator.FromBytes(data[0 : 121+i]) require.Error(t, err) } val2, err := validator.FromBytes(data) require.NoError(t, err) assert.Equal(t, val1.Hash(), val2.Hash()) } func TestUpdateValidator(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() bondingHeight := ts.RandHeight() sortitionHeight := ts.RandHeight() unbondingHeight := ts.RandHeight() val.UpdateLastBondingHeight(bondingHeight) val.UpdateLastSortitionHeight(sortitionHeight) val.UpdateUnbondingHeight(unbondingHeight) assert.Equal(t, bondingHeight, val.LastBondingHeight()) assert.Equal(t, sortitionHeight, val.LastSortitionHeight()) assert.Equal(t, unbondingHeight, val.UnbondingHeight()) } func TestDecoding(t *testing.T) { data, _ := hex.DecodeString( "8d82fa4fcac04a3b565267685e90db1b01420285d2f8295683c138c092c209479983ba1591370778846681b7b558e061" + // PublicKey "1776208c0718006311c84b4a113335c70d1f5c7c5dd93a5625c4af51c48847abd0b590c055306162d2a03ca1cbf7bcc1" + "01000000" + // Number "0200000000000000" + // Stake "03000000" + // LastBondingHeight "04000000" + // UnbondingHeight "05000000") // LastSortitionHeight val, err := validator.FromBytes(data) require.NoError(t, err) assert.Equal(t, int32(1), val.Number()) assert.Equal(t, amount.Amount(2), val.Stake()) assert.Equal(t, types.Height(3), val.LastBondingHeight()) assert.Equal(t, types.Height(4), val.UnbondingHeight()) assert.Equal(t, types.Height(5), val.LastSortitionHeight()) d2, _ := val.Bytes() assert.Equal(t, data, d2) assert.Equal(t, len(data), val.SerializeSize()) assert.Equal(t, hash.CalcHash(data), val.Hash()) expected, _ := hash.FromString("243e65ae04727f21d5f7618cea9ff8d4bc82fded1179cf8bd9e11a6b99ac42b2") assert.Equal(t, expected, val.Hash()) } func TestPower(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() val.SubtractFromStake(val.Stake()) assert.Equal(t, amount.Amount(0), val.Stake()) assert.Equal(t, int64(1), val.Power()) val.AddToStake(1) assert.Equal(t, amount.Amount(1), val.Stake()) assert.Equal(t, int64(1), val.Power()) val.UpdateUnbondingHeight(1) assert.Equal(t, amount.Amount(1), val.Stake()) assert.Equal(t, int64(0), val.Power()) } func TestAddToStake(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() stake := val.Stake() val.AddToStake(1) assert.Equal(t, stake+1, val.Stake()) } func TestSubtractFromStake(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() stake := val.Stake() val.SubtractFromStake(1) assert.Equal(t, stake-1, val.Stake()) } func TestClone(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() cloned := val.Clone() cloned.AddToStake(1) assert.Equal(t, val.Number(), cloned.Number()) assert.Equal(t, val.PublicKey(), cloned.PublicKey()) assert.NotEqual(t, val.Stake(), cloned.Stake()) } func TestIsUnbonded(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() assert.False(t, val.IsUnbonded()) val.UpdateUnbondingHeight(ts.RandHeight()) assert.True(t, val.IsUnbonded()) } func TestUpdateProtocolVersion(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() assert.Equal(t, protocol.Version(0), val.ProtocolVersion()) val.UpdateProtocolVersion(1) assert.Equal(t, protocol.Version(1), val.ProtocolVersion()) } func TestIsActive(t *testing.T) { ts := testsuite.NewTestSuite(t) val := ts.GenerateTestValidator() assert.True(t, val.IsActive()) val.UpdateUnbondingHeight(ts.RandHeight()) assert.False(t, val.IsActive()) val.UpdateUnbondingHeight(0) val.SubtractFromStake(val.Stake()) assert.False(t, val.IsActive()) } ================================================ FILE: types/vote/cp_just.go ================================================ package vote import ( "github.com/pactus-project/pactus/types/certificate" ) type JustType uint8 const ( JustTypeInitNo = JustType(1) JustTypeInitYes = JustType(2) JustTypePreVoteSoft = JustType(3) JustTypePreVoteHard = JustType(4) JustTypeMainVoteConflict = JustType(5) JustTypeMainVoteNoConflict = JustType(6) JustTypeDecided = JustType(7) ) func (t JustType) String() string { switch t { case JustTypeInitNo: return "JustInitNo" case JustTypeInitYes: return "JustInitYes" case JustTypePreVoteSoft: return "JustPreVoteSoft" case JustTypePreVoteHard: return "JustPreVoteHard" case JustTypeMainVoteConflict: return "JustMainVoteConflict" case JustTypeMainVoteNoConflict: return "JustMainVoteNoConflict" case JustTypeDecided: return "JustDecided" default: return "Unknown" } } type Just interface { Type() JustType BasicCheck() error } func makeJust(t JustType) Just { switch t { case JustTypeInitNo: return &JustInitNo{} case JustTypeInitYes: return &JustInitYes{} case JustTypePreVoteSoft: return &JustPreVoteSoft{} case JustTypePreVoteHard: return &JustPreVoteHard{} case JustTypeMainVoteConflict: return &JustMainVoteConflict{} case JustTypeMainVoteNoConflict: return &JustMainVoteNoConflict{} case JustTypeDecided: return &JustDecided{} default: return nil } } type JustInitNo struct { QCert *certificate.Certificate `cbor:"1,keyasint"` } type JustInitYes struct { // } type JustPreVoteSoft struct { QCert *certificate.Certificate `cbor:"1,keyasint"` } type JustPreVoteHard struct { QCert *certificate.Certificate `cbor:"1,keyasint"` } type JustMainVoteConflict struct { JustNo Just JustYes Just } type JustMainVoteConflictV2 struct { Just1 Just Just2 Just } type JustMainVoteNoConflict struct { QCert *certificate.Certificate `cbor:"1,keyasint"` } type JustDecided struct { QCert *certificate.Certificate `cbor:"1,keyasint"` } func (*JustInitNo) Type() JustType { return JustTypeInitNo } func (*JustInitYes) Type() JustType { return JustTypeInitYes } func (*JustPreVoteSoft) Type() JustType { return JustTypePreVoteSoft } func (*JustPreVoteHard) Type() JustType { return JustTypePreVoteHard } func (*JustMainVoteConflict) Type() JustType { return JustTypeMainVoteConflict } func (*JustMainVoteNoConflict) Type() JustType { return JustTypeMainVoteNoConflict } func (*JustDecided) Type() JustType { return JustTypeDecided } func (j *JustInitNo) BasicCheck() error { err := j.QCert.BasicCheck() if err != nil { return err } return nil } func (*JustInitYes) BasicCheck() error { return nil } func (j *JustPreVoteSoft) BasicCheck() error { return j.QCert.BasicCheck() } func (j *JustPreVoteHard) BasicCheck() error { return j.QCert.BasicCheck() } func (j *JustMainVoteConflict) BasicCheck() error { if err := j.JustNo.BasicCheck(); err != nil { return err } return j.JustYes.BasicCheck() } func (j *JustMainVoteNoConflict) BasicCheck() error { return j.QCert.BasicCheck() } func (j *JustDecided) BasicCheck() error { return j.QCert.BasicCheck() } ================================================ FILE: types/vote/cp_vote.go ================================================ package vote import ( "fmt" "github.com/fxamacker/cbor/v2" ) type CPValue int8 const ( CPValueNo = CPValue(0) CPValueYes = CPValue(1) CPValueAbstain = CPValue(2) ) func (v CPValue) String() string { switch v { case CPValueNo: return "no" case CPValueYes: return "yes" case CPValueAbstain: return "abstain" default: return fmt.Sprintf("unknown: %d", v) } } type cpVote struct { Round int16 Value CPValue Just Just } func (v *cpVote) BasicCheck() error { if v.Round < 0 { return BasicCheckError{ Reason: "invalid CP round", } } if v.Value < CPValueNo || v.Value > CPValueAbstain { // Invalid values return BasicCheckError{ Reason: "invalid CP value", } } return v.Just.BasicCheck() } type _cpVote struct { Round int16 `cbor:"1,keyasint"` Value CPValue `cbor:"2,keyasint"` JustType JustType `cbor:"3,keyasint"` JustData []byte `cbor:"4,keyasint"` } type _JustMainVoteConflict struct { Just0Type JustType `cbor:"1,keyasint"` Just0Data []byte `cbor:"2,keyasint"` Just1Type JustType `cbor:"3,keyasint"` Just1Data []byte `cbor:"4,keyasint"` } // MarshalCBOR encodes the cpVote into CBOR format. func (v *cpVote) MarshalCBOR() ([]byte, error) { justData := []byte{} if v.Just.Type() == JustTypeMainVoteConflict { conflictJust := v.Just.(*JustMainVoteConflict) data0, err := cbor.Marshal(conflictJust.JustNo) if err != nil { return nil, err } data1, err := cbor.Marshal(conflictJust.JustYes) if err != nil { return nil, err } _conflictingJust := _JustMainVoteConflict{ Just0Type: conflictJust.JustNo.Type(), Just0Data: data0, Just1Type: conflictJust.JustYes.Type(), Just1Data: data1, } data, err := cbor.Marshal(_conflictingJust) if err != nil { return nil, err } justData = append(justData, data...) } else { data, err := cbor.Marshal(v.Just) if err != nil { return nil, err } justData = append(justData, data...) } msg := &_cpVote{ Round: v.Round, Value: v.Value, JustType: v.Just.Type(), JustData: justData, } return cbor.Marshal(msg) } // UnmarshalCBOR decodes the cpVote from CBOR format. func (v *cpVote) UnmarshalCBOR(bs []byte) error { var _cp _cpVote err := cbor.Unmarshal(bs, &_cp) if err != nil { return err } var just Just if _cp.JustType == JustTypeMainVoteConflict { _conflictingJust := &_JustMainVoteConflict{} err := cbor.Unmarshal(_cp.JustData, _conflictingJust) if err != nil { return err } just0 := makeJust(_conflictingJust.Just0Type) err = cbor.Unmarshal(_conflictingJust.Just0Data, just0) if err != nil { return err } just1 := makeJust(_conflictingJust.Just1Type) err = cbor.Unmarshal(_conflictingJust.Just1Data, just1) if err != nil { return err } just = &JustMainVoteConflict{ JustNo: just0, JustYes: just1, } } else { just = makeJust(_cp.JustType) err := cbor.Unmarshal(_cp.JustData, just) if err != nil { return err } } v.Round = _cp.Round v.Value = _cp.Value v.Just = just return nil } ================================================ FILE: types/vote/errors.go ================================================ package vote import ( "fmt" "github.com/pactus-project/pactus/crypto" ) // BasicCheckError is returned when the basic check on the transaction fails. type BasicCheckError struct { Reason string } func (e BasicCheckError) Error() string { return e.Reason } // InvalidSignerError is returned when the vote signer does not match with the // public key. type InvalidSignerError struct { Expected crypto.Address Got crypto.Address } func (e InvalidSignerError) Error() string { return fmt.Sprintf("invalid signer, expected: %s, got: %s", e.Expected.String(), e.Got.String()) } ================================================ FILE: types/vote/vote.go ================================================ package vote import ( "fmt" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/certificate" ) // Vote is a struct that represents a consensus vote. type Vote struct { data voteData } type voteData struct { Type Type `cbor:"1,keyasint"` Height types.Height `cbor:"2,keyasint"` Round types.Round `cbor:"3,keyasint"` BlockHash hash.Hash `cbor:"4,keyasint"` Signer crypto.Address `cbor:"5,keyasint"` CPVote *cpVote `cbor:"6,keyasint"` Signature *bls.Signature `cbor:"7,keyasint"` } // NewPrepareVote creates a new PREPARE with the specified parameters. func NewPrepareVote(blockHash hash.Hash, height types.Height, round types.Round, signer crypto.Address) *Vote { return newVote(VoteTypePrepare, blockHash, height, round, signer) } // NewPrecommitVote creates a new PRECOMMIT with the specified parameters. func NewPrecommitVote(blockHash hash.Hash, height types.Height, round types.Round, signer crypto.Address) *Vote { return newVote(VoteTypePrecommit, blockHash, height, round, signer) } // NewCPPreVote creates a new cp:PRE-VOTE with the specified parameters. func NewCPPreVote(blockHash hash.Hash, height types.Height, round types.Round, cpRound int16, cpValue CPValue, just Just, signer crypto.Address, ) *Vote { vote := newVote(VoteTypeCPPreVote, blockHash, height, round, signer) vote.data.CPVote = &cpVote{ Round: cpRound, Value: cpValue, Just: just, } return vote } // NewCPMainVote creates a new cp:MAIN-VOTE with the specified parameters. func NewCPMainVote(blockHash hash.Hash, height types.Height, round types.Round, cpRound int16, cpValue CPValue, just Just, signer crypto.Address, ) *Vote { vote := newVote(VoteTypeCPMainVote, blockHash, height, round, signer) vote.data.CPVote = &cpVote{ Round: cpRound, Value: cpValue, Just: just, } return vote } // NewCPDecidedVote creates a new cp:Decided with the specified parameters. func NewCPDecidedVote(blockHash hash.Hash, height types.Height, round types.Round, cpRound int16, cpValue CPValue, just Just, signer crypto.Address, ) *Vote { vote := newVote(VoteTypeCPDecided, blockHash, height, round, signer) vote.data.CPVote = &cpVote{ Round: cpRound, Value: cpValue, Just: just, } return vote } // newVote creates a new vote with the specified parameters. func newVote(voteType Type, blockHash hash.Hash, height types.Height, round types.Round, signer crypto.Address, ) *Vote { return &Vote{ data: voteData{ Type: voteType, Height: height, Round: round, BlockHash: blockHash, Signer: signer, }, } } // SignBytes generates the bytes to be signed for the vote. func (v *Vote) SignBytes() []byte { cert := certificate.NewCertificate(v.data.Height, v.data.Round) switch typ := v.Type(); typ { case VoteTypePrecommit: return cert.SignBytesPrecommit(v.data.BlockHash) case VoteTypePrepare: return cert.SignBytesPrepare(v.data.BlockHash) case VoteTypeCPPreVote: return cert.SignBytesCPPreVote(v.data.BlockHash, v.data.CPVote.Round, byte(v.data.CPVote.Value)) case VoteTypeCPMainVote: return cert.SignBytesCPMainVote(v.data.BlockHash, v.data.CPVote.Round, byte(v.data.CPVote.Value)) case VoteTypeCPDecided: return cert.SignBytesCPDecided(v.data.BlockHash, v.data.CPVote.Round, byte(v.data.CPVote.Value)) default: return nil } } // Type returns the type of the vote. func (v *Vote) Type() Type { return v.data.Type } // Height returns the height of the block in the vote. func (v *Vote) Height() types.Height { return v.data.Height } // Round returns the round the vote. func (v *Vote) Round() types.Round { return v.data.Round } // CPRound returns the change proposer round the vote. func (v *Vote) CPRound() int16 { return v.data.CPVote.Round } // CPValue returns the change proposer value the vote. func (v *Vote) CPValue() CPValue { return v.data.CPVote.Value } // CPJust returns the change proposer justification for the vote. func (v *Vote) CPJust() Just { return v.data.CPVote.Just } // BlockHash returns the hash of the block in the vote. func (v *Vote) BlockHash() hash.Hash { return v.data.BlockHash } // Signer returns the address of the signer of the vote. func (v *Vote) Signer() crypto.Address { return v.data.Signer } // Signature returns the signature of the vote. func (v *Vote) Signature() *bls.Signature { return v.data.Signature } // SetSignature sets the signature of the vote. func (v *Vote) SetSignature(sig *bls.Signature) { v.data.Signature = sig } // MarshalCBOR encodes the vote into CBOR format. func (v *Vote) MarshalCBOR() ([]byte, error) { return cbor.Marshal(v.data) } // UnmarshalCBOR decodes the vote from CBOR format. func (v *Vote) UnmarshalCBOR(bs []byte) error { return cbor.Unmarshal(bs, &v.data) } // Hash calculates the hash of the vote. func (v *Vote) Hash() hash.Hash { bz, _ := cbor.Marshal(v.data) return hash.CalcHash(bz) } // Verify checks the signature of the vote with the given public key. func (v *Vote) Verify(pubKey *bls.PublicKey) error { if v.Signer() != pubKey.ValidatorAddress() { return InvalidSignerError{ Expected: pubKey.ValidatorAddress(), Got: v.Signer(), } } return pubKey.Verify(v.SignBytes(), v.Signature()) } func (v *Vote) IsCPVote() bool { if v.data.Type == VoteTypeCPPreVote || v.data.Type == VoteTypeCPMainVote || v.data.Type == VoteTypeCPDecided { return true } return false } // BasicCheck performs a basic check on the vote. func (v *Vote) BasicCheck() error { if !v.data.Type.IsValid() { return BasicCheckError{ Reason: "invalid vote type", } } if v.data.Height <= 0 { return BasicCheckError{ Reason: "invalid height", } } if v.data.Round < 0 { return BasicCheckError{ Reason: "invalid round", } } if v.IsCPVote() { if v.data.CPVote == nil { return BasicCheckError{ Reason: "should have CP data", } } if err := v.data.CPVote.BasicCheck(); err != nil { return err } } else if v.data.CPVote != nil { return BasicCheckError{ Reason: "should not have CP data", } } if v.Signature() == nil { return BasicCheckError{ Reason: "no signature", } } return nil } // LogString returns a concise string representation intended for use in logs. func (v *Vote) LogString() string { switch v.Type() { case VoteTypePrepare, VoteTypePrecommit: return fmt.Sprintf("{%d/%d/%s ⌘ %v 👤 %s}", v.Height(), v.Round(), v.Type(), v.BlockHash().LogString(), v.Signer().LogString(), ) case VoteTypeCPPreVote, VoteTypeCPMainVote, VoteTypeCPDecided: return fmt.Sprintf("{%d/%d/%s/%d/%s ⌘ %v 👤 %s}", v.Height(), v.Round(), v.Type(), v.CPRound(), v.CPValue(), v.BlockHash().LogString(), v.Signer().LogString(), ) default: return "unknown type" } } ================================================ FILE: types/vote/vote_test.go ================================================ package vote_test import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestVoteMarshaling(t *testing.T) { tests := []struct { data string justType string signBytes string }{ { "A7" + // map(7) "0101" + // Type: 1 (prepare vote) "021832" + // Height: 50 "0301" + // Round: 1 "045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06f6" + // CP_vote -> Null "07f6", // Signature -> Null "", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB32000000010050524550415245", }, { "A7" + // map(7) "0102" + // Type: 2 (precommit vote) "021832" + // Height: 50 "0301" + // Round: 1 "045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06f6" + // CP_vote -> Null "07f6", // Signature -> Null "", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB320000000100", }, { "A7" + // map(7) "0103" + // Type: 3 (cp:pre-vote) "021832" + // Height: 50 "0301" + // Round: 1 "045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0100" + // CP_Round: 0 "0200" + // CP_Value: 0 "0301" + // Just type: 1 "045840" + // Just: JustTypeInitNo "A1" + // map(1) "01583C" + // Certificate (60 bytes) "32000000010004010203040094D25422904AC1D130AC981374AA4424F988" + // Certificate Data "61E99131078EFEFD62FC52CF072B0C08BB04E4E6496BA48DE4F3D3309AAB" + "07f6", // Signature -> Null "JustInitNo", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB3200000001005052452d564f5445000000", }, { "A7" + // map(7) "0103" + // Type: 3 (cp:pre-vote) "021832" + // Height: 50 "0301" + // Round: 1 "0458200000000000000000000000000000000000000000000000000000000000000000" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0100" + // CP_Round: 0 "0201" + // CP_Value: 1 "0302" + // Just type: 2 "0441" + // Just: JustTypeInitYes "A0" + // Empty Array "07f6", // Signature -> Null "JustInitYes", "00000000000000000000000000000000000000000000000000000000000000003200000001005052452d564f5445000001", }, { "A7" + // map(7) "0103" + // Type: 3 (cp:pre-vote) "021832" + // Height: 50 "0301" + // Round: 1 "045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0101" + // CP_Round: 1 "0200" + // CP_Value: 0 "0303" + // Just type: 3 "045840" + // Just: JustPreVoteSoft "A1" + // map(1) "01583C" + // Certificate (60 bytes) "32000000010004010203040094D25422904AC1D130AC981374AA4424F988" + // Certificate Data "61E99131078EFEFD62FC52CF072B0C08BB04E4E6496BA48DE4F3D3309AAB" + "07f6", // Signature -> Null "JustPreVoteSoft", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB3200000001005052452d564f5445010000", }, { "A7" + // map(7) "0103" + // Type: 3 (cp:pre-vote) "021832" + // Height: 50 "0301" + // Round: 1 "045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0101" + // CP_Round: 1 "0200" + // CP_Value: 0 "0304" + // Just type: 4 "045840" + // Just: JustPreVoteHard "A1" + // map(1) "01583C" + // Certificate (60 bytes) "32000000010004010203040094D25422904AC1D130AC981374AA4424F988" + // Certificate Data "61E99131078EFEFD62FC52CF072B0C08BB04E4E6496BA48DE4F3D3309AAB" + "07f6", // Signature -> Null "JustPreVoteHard", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB3200000001005052452d564f5445010000", }, { "A7" + // map(7) "0104" + // Type: 4 (cp:main-vote) "021832" + // Height: 50 "0301" + // Round: 1 "045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0101" + // CP_Round: 1 "0202" + // CP_Value: 2 (abstain) "0305" + // Just type: 5 "04584b" + // Just: JustTypeMainVoteConflict "A4" + // map(4) "0101" + // Just0: Type (No) "025840" + // Just0Data "A1" + // map(1) "01583C" + // Certificate (60 bytes) "32000000010004010203040094D25422904AC1D130AC981374AA4424F988" + // Certificate Data "61E99131078EFEFD62FC52CF072B0C08BB04E4E6496BA48DE4F3D3309AAB" + "0302" + // Just1: Type (JustTypeInitYes) "0441" + // Just1Data "A0" + // Empty Array "07f6", // Signature -> Null "JustMainVoteConflict", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB3200000001004d41494e2d564f5445010002", }, { "A7" + // map(7) "0104" + // Type: 4 (cp:main-vote) "021832" + // Height: 50 "0301" + // Round: 1 "0458200000000000000000000000000000000000000000000000000000000000000000" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0101" + // CP_Round: 1 "0201" + // CP_Value: 1 "0306" + // Just type: 6 "045840" + // Just: JustTypeMainVoteNoConflict "A1" + // map(1) "01583C" + // Certificate (60 bytes) "32000000010004010203040094D25422904AC1D130AC981374AA4424F988" + // Certificate Data "61E99131078EFEFD62FC52CF072B0C08BB04E4E6496BA48DE4F3D3309AAB" + "07f6", // Signature -> Null "JustMainVoteNoConflict", "00000000000000000000000000000000000000000000000000000000000000003200000001004d41494e2d564f5445010001", }, { "A7" + // map(7) "0105" + // Type: 4 (cp:decided) "021832" + // Height: 50 "0301" + // Round: 1 "0458200000000000000000000000000000000000000000000000000000000000000000" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0101" + // CP_Round: 1 "0201" + // CP_Value: 1 "0307" + // Just type: 7 "045840" + // Just: JustTypeDecided "A1" + // map(1) "01583C" + // Certificate (60 bytes) "32000000010004010203040094D25422904AC1D130AC981374AA4424F988" + // Certificate Data "61E99131078EFEFD62FC52CF072B0C08BB04E4E6496BA48DE4F3D3309AAB" + "07f6", // Signature -> Null "JustDecided", "000000000000000000000000000000000000000000000000000000000000000032000000010044454349444544010001", }, } ts := testsuite.NewTestSuite(t) for _, tt := range tests { bz1, _ := hex.DecodeString(tt.data) vote := new(vote.Vote) err := vote.UnmarshalCBOR(bz1) require.NoError(t, err) bz2, err := vote.MarshalCBOR() require.NoError(t, err) assert.Equal(t, bz1, bz2) expectedHash := hash.CalcHash(bz1) assert.Equal(t, expectedHash, vote.Hash()) vote.SetSignature(ts.RandBLSSignature()) require.NoError(t, vote.BasicCheck()) expectedSignBytes, _ := hex.DecodeString(tt.signBytes) assert.Equal(t, expectedSignBytes, vote.SignBytes()) if tt.justType != "" { assert.Equal(t, tt.justType, vote.CPJust().Type().String()) } } } func TestVoteSignature(t *testing.T) { ts := testsuite.NewTestSuite(t) hash1 := ts.RandHash() pub1, prv1 := ts.RandBLSKeyPair() pub2, prv2 := ts.RandBLSKeyPair() vote1 := vote.NewPrepareVote(hash1, 101, 5, pub1.ValidatorAddress()) vote2 := vote.NewPrepareVote(hash1, 101, 5, pub2.ValidatorAddress()) require.Error(t, vote1.BasicCheck(), "No signature") sig1 := prv1.SignNative(vote1.SignBytes()) vote1.SetSignature(sig1) err1 := vote1.Verify(pub1) require.NoError(t, err1, "Ok") sig2 := prv2.SignNative(vote2.SignBytes()) vote2.SetSignature(sig2) err2 := vote2.Verify(pub1) require.ErrorIs(t, err2, vote.InvalidSignerError{ Expected: pub1.ValidatorAddress(), Got: pub2.ValidatorAddress(), }) sig3 := prv1.SignNative(vote2.SignBytes()) vote2.SetSignature(sig3) err3 := vote2.Verify(pub2) require.ErrorIs(t, err3, crypto.ErrInvalidSignature) } func TestCPPreVote(t *testing.T) { ts := testsuite.NewTestSuite(t) height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} t.Run("Invalid CP round", func(t *testing.T) { invalidCPRound := int16(-1) cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, invalidCPRound, vote.CPValueYes, just, ts.RandAccAddress()) err := cpVote.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP round"}) }) t.Run("invalid CP value", func(t *testing.T) { invalidCPValue := vote.CPValue(3) cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 1, invalidCPValue, just, ts.RandAccAddress()) err := cpVote.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP value"}) }) t.Run("Ok", func(t *testing.T) { cpVote := vote.NewCPPreVote(hash.UndefHash, height, round, 1, vote.CPValueNo, just, ts.RandAccAddress()) cpVote.SetSignature(ts.RandBLSSignature()) err := cpVote.BasicCheck() require.NoError(t, err) assert.Equal(t, int16(1), cpVote.CPRound()) assert.Equal(t, vote.CPValueNo, cpVote.CPValue()) assert.NotNil(t, cpVote.CPJust()) }) } func TestCPMainVote(t *testing.T) { ts := testsuite.NewTestSuite(t) height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} t.Run("Invalid CP round", func(t *testing.T) { invalidCPRound := int16(-1) invVote := vote.NewCPMainVote(hash.UndefHash, height, round, invalidCPRound, vote.CPValueNo, just, ts.RandAccAddress()) err := invVote.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP round"}) }) t.Run("No CP data", func(t *testing.T) { data, _ := hex.DecodeString( "A701040218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") decVote := new(vote.Vote) _ = decVote.UnmarshalCBOR(data) decVote.SetSignature(ts.RandBLSSignature()) err := decVote.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "should have CP data"}) }) t.Run("Invalid CP value", func(t *testing.T) { invalidCPValue := vote.CPValue(3) cpVote := vote.NewCPMainVote(hash.UndefHash, height, round, 1, invalidCPValue, just, ts.RandAccAddress()) err := cpVote.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP value"}) }) t.Run("Ok", func(t *testing.T) { cpVote := vote.NewCPMainVote(hash.UndefHash, height, round, 1, vote.CPValueAbstain, just, ts.RandAccAddress()) cpVote.SetSignature(ts.RandBLSSignature()) err := cpVote.BasicCheck() require.NoError(t, err) assert.Equal(t, int16(1), cpVote.CPRound()) assert.Equal(t, vote.CPValueAbstain, cpVote.CPValue()) assert.NotNil(t, cpVote.CPJust()) }) } func TestCPDecided(t *testing.T) { ts := testsuite.NewTestSuite(t) height := ts.RandHeight() round := ts.RandRound() just := &vote.JustInitYes{} t.Run("Invalid round", func(t *testing.T) { invalidCPRound := int16(-1) v := vote.NewCPDecidedVote(hash.UndefHash, height, round, invalidCPRound, vote.CPValueNo, just, ts.RandAccAddress()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP round"}) }) t.Run("No CP data", func(t *testing.T) { data, _ := hex.DecodeString("A701050218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") v := new(vote.Vote) _ = v.UnmarshalCBOR(data) v.SetSignature(ts.RandBLSSignature()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "should have CP data"}) }) t.Run("Invalid CP value", func(t *testing.T) { invalidCPValue := vote.CPValue(3) v := vote.NewCPDecidedVote(hash.UndefHash, height, round, 1, invalidCPValue, just, ts.RandAccAddress()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid CP value"}) }) t.Run("Ok", func(t *testing.T) { vte := vote.NewCPDecidedVote(hash.UndefHash, height, round, 1, vote.CPValueAbstain, just, ts.RandAccAddress()) vte.SetSignature(ts.RandBLSSignature()) err := vte.BasicCheck() require.NoError(t, err) assert.Equal(t, int16(1), vte.CPRound()) assert.Equal(t, vote.CPValueAbstain, vte.CPValue()) assert.NotNil(t, vte.CPJust()) }) } func TestBasicCheck(t *testing.T) { ts := testsuite.NewTestSuite(t) t.Run("Should have CP data", func(t *testing.T) { data, _ := hex.DecodeString("A701050218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06f607f6") v := new(vote.Vote) err := v.UnmarshalCBOR(data) require.NoError(t, err) err = v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "should have CP data"}) }) t.Run("Invalid height", func(t *testing.T) { v := vote.NewPrepareVote(ts.RandHash(), 0, 0, ts.RandAccAddress()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid height"}) }) t.Run("Invalid round", func(t *testing.T) { v := vote.NewPrepareVote(ts.RandHash(), 100, -1, ts.RandAccAddress()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "invalid round"}) }) t.Run("No signature", func(t *testing.T) { v := vote.NewPrepareVote(ts.RandHash(), 100, 0, ts.RandAccAddress()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "no signature"}) }) t.Run("Should not have CP data", func(t *testing.T) { data, _ := hex.DecodeString("A701020218320301045820BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA06A40100020103020441A007f6") v := new(vote.Vote) _ = v.UnmarshalCBOR(data) v.SetSignature(ts.RandBLSSignature()) err := v.BasicCheck() require.ErrorIs(t, err, vote.BasicCheckError{Reason: "should not have CP data"}) }) t.Run("Ok", func(t *testing.T) { v := vote.NewPrepareVote(ts.RandHash(), 100, 0, ts.RandAccAddress()) v.SetSignature(ts.RandBLSSignature()) require.NoError(t, v.BasicCheck()) }) } func TestSignBytes(t *testing.T) { ts := testsuite.NewTestSuite(t) signer := ts.RandAccAddress() blockHash := ts.RandHash() height := ts.RandHeight() round := types.Round(10) cpRound := int16(10) just := &vote.JustInitNo{} vote1 := vote.NewPrepareVote(blockHash, height, round, signer) vote2 := vote.NewPrecommitVote(blockHash, height, round, signer) vote3 := vote.NewCPPreVote(blockHash, height, round, cpRound, vote.CPValueNo, just, signer) vote4 := vote.NewCPMainVote(blockHash, height, round, cpRound, vote.CPValueAbstain, just, signer) vote5 := vote.NewCPDecidedVote(blockHash, height, round, cpRound, vote.CPValueYes, just, signer) sby1 := vote1.SignBytes() sby2 := vote2.SignBytes() sby3 := vote3.SignBytes() sby4 := vote4.SignBytes() sby5 := vote5.SignBytes() assert.Len(t, sby1, 45) assert.Len(t, sby2, 38) assert.Len(t, sby3, 49) assert.Len(t, sby4, 50) assert.Len(t, sby5, 48) assert.Contains(t, string(sby1), "PREPARE") assert.Contains(t, string(sby3), "PRE-VOTE") assert.Contains(t, string(sby4), "MAIN-VOTE") assert.Contains(t, string(sby5), "DECIDED") } func TestLogString(t *testing.T) { ts := testsuite.NewTestSuite(t) signer := ts.RandAccAddress() blockHash := ts.RandHash() height := types.Height(100) round := types.Round(2) just := &vote.JustInitNo{} v1 := vote.NewPrepareVote(blockHash, height, round, signer) v2 := vote.NewPrecommitVote(blockHash, height, round, signer) v3 := vote.NewCPPreVote(blockHash, height, round, 1, vote.CPValueNo, just, signer) v4 := vote.NewCPMainVote(blockHash, height, round, 1, vote.CPValueAbstain, just, signer) assert.Contains(t, v1.LogString(), "100/2/PREPARE") assert.Contains(t, v2.LogString(), "100/2/PRECOMMIT") assert.Contains(t, v3.LogString(), "100/2/PRE-VOTE/1") assert.Contains(t, v4.LogString(), "100/2/MAIN-VOTE/1") } func TestCPValueToString(t *testing.T) { assert.Equal(t, "no", vote.CPValueNo.String()) assert.Equal(t, "yes", vote.CPValueYes.String()) assert.Equal(t, "abstain", vote.CPValueAbstain.String()) assert.Equal(t, "unknown: -1", vote.CPValue(-1).String()) } func TestCPInvalidJustType(t *testing.T) { voteData, _ := hex.DecodeString( "A7" + // map(7) "0103" + // Type: 3 (cp:pre-vote) "021832" + // Height: 50 "0301" + // Round: 1 "0458200000000000000000000000000000000000000000000000000000000000000000" + // Block Hash "055501AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + // Signer "06" + // CP_vote "A4" + // map(4) "0100" + // CP_Round: 0 "0201" + // CP_Value: 1 "0308" + // Just type: 8 <<<(Unknown Just Type)>>> "0441" + // Just: JustTypeInitYes "A0" + // Empty Array "07f6") // Signature -> Null v := new(vote.Vote) err := v.UnmarshalCBOR(voteData) require.Error(t, err) } ================================================ FILE: types/vote/vote_type.go ================================================ package vote import "fmt" type Type int const ( VoteTypePrepare = Type(1) // Deprecated prepare vote VoteTypePrecommit = Type(2) // precommit vote VoteTypeCPPreVote = Type(3) // change-proposer:pre-vote VoteTypeCPMainVote = Type(4) // change-proposer:main-vote VoteTypeCPDecided = Type(5) // change-proposer:decided ) func (t Type) IsValid() bool { switch t { case VoteTypePrepare, VoteTypePrecommit, VoteTypeCPPreVote, VoteTypeCPMainVote, VoteTypeCPDecided: return true } return false } func (t Type) String() string { switch t { case VoteTypePrepare: return "PREPARE" case VoteTypePrecommit: return "PRECOMMIT" case VoteTypeCPPreVote: return "PRE-VOTE" case VoteTypeCPMainVote: return "MAIN-VOTE" case VoteTypeCPDecided: return "DECIDED" default: return fmt.Sprintf("%d", t) } } ================================================ FILE: util/bech32m/bech32m.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package bech32m import ( "strings" ) // ChecksumConst is a type that represents the currently defined bech32 // checksum constants. const ChecksumConst = int(0x2bc830a3) // charset is the set of characters used in the data section of bech32 strings. // Note that this is ordered, such that for a given charset[i], i is the binary // value of the character. const charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" // gen encodes the generator polynomial for the bech32 BCH checksum. var gen = []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} // toBytes converts each character in the string 'chars' to the value of the // index of the corresponding character in 'charset'. func toBytes(chars string) ([]byte, error) { decoded := make([]byte, 0, len(chars)) for i := 0; i < len(chars); i++ { index := strings.IndexByte(charset, chars[i]) if index < 0 { return nil, NonCharsetCharError(chars[i]) } decoded = append(decoded, byte(index)) } return decoded, nil } // bech32Polymod calculates the BCH checksum for a given hrp, values and // checksum data. Checksum is optional, and if nil a 0 checksum is assumed. // // Values and checksum (if provided) MUST be encoded as 5 bits per element (base // 32), otherwise the results are undefined. // // For more details on the polymod calculation, please refer to BIP 173. // //nolint:gocognit // complexity can't be reduced more. func bech32Polymod(hrp string, values, checksum []byte) int { chk := 1 // Account for the high bits of the HRP in the checksum. for i := 0; i < len(hrp); i++ { b := chk >> 25 hiBits := int(hrp[i]) >> 5 chk = (chk&0x1ffffff)<<5 ^ hiBits for j := 0; j < 5; j++ { if (b>>uint(j))&1 == 1 { chk ^= gen[j] } } } // Account for the separator (0) between high and low bits of the HRP. // x^0 == x, so we eliminate the redundant xor used in the other rounds. b0 := chk >> 25 chk = (chk & 0x1ffffff) << 5 for i := 0; i < 5; i++ { if (b0>>uint(i))&1 == 1 { chk ^= gen[i] } } // Account for the low bits of the HRP. for i := 0; i < len(hrp); i++ { b := chk >> 25 loBits := int(hrp[i]) & 31 chk = (chk&0x1ffffff)<<5 ^ loBits for j := 0; j < 5; j++ { if (b>>uint(j))&1 == 1 { chk ^= gen[j] } } } // Account for the values. for _, v := range values { b := chk >> 25 chk = (chk&0x1ffffff)<<5 ^ int(v) for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { chk ^= gen[i] } } } if checksum == nil { // A nil checksum is used during encoding, so assume all bytes are zero. // x^0 == x, so we eliminate the redundant xor used in the other rounds. for v := 0; v < 6; v++ { b := chk >> 25 chk = (chk & 0x1ffffff) << 5 for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { chk ^= gen[i] } } } } else { // Checksum is provided during decoding, so use it. for _, v := range checksum { b := chk >> 25 chk = (chk&0x1ffffff)<<5 ^ int(v) for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { chk ^= gen[i] } } } } return chk } // writeBech32Checksum calculates the checksum data expected for a string that // will have the given hrp and payload data and writes it to the provided string // builder. // // The payload data MUST be encoded as a base 32 (5 bits per element) byte slice // and the hrp MUST only use the allowed character set (ascii chars between 33 // and 126), otherwise the results are undefined. // // For more details on the checksum calculation, please refer to BIP 173. func writeBech32Checksum(hrp string, data []byte, bldr *strings.Builder) { polymod := bech32Polymod(hrp, data, nil) ^ ChecksumConst for i := 0; i < 6; i++ { b := byte((polymod >> uint(5*(5-i))) & 31) // This can't fail, given we explicitly cap the previous b byte by the // first 31 bits. c := charset[b] bldr.WriteByte(c) } } // bech32VerifyChecksum verifies whether the bech32 string specified by the // provided hrp and payload data (encoded as 5 bits per element byte slice) has // the correct checksum suffix. // // Data MUST have more than 6 elements, otherwise this function panics. // // For more details on the checksum verification, please refer to BIP 173. func bech32VerifyChecksum(hrp string, data []byte) bool { checksum := data[len(data)-6:] values := data[:len(data)-6] polymod := bech32Polymod(hrp, values, checksum) return polymod == ChecksumConst } // DecodeNoLimit decodes a bech32 encoded string, returning the human-readable // part and the data part excluding the checksum. This function does NOT // validate against the BIP-173 maximum length allowed for bech32 strings. // // Note that the returned data is 5-bit (base32) encoded and the human-readable // part will be lowercase. func DecodeNoLimit(bech string) (string, []byte, error) { // The minimum allowed size of a bech32 string is 8 characters, since it // needs a non-empty HRP, a separator, and a 6 character checksum. if len(bech) < 8 { return "", nil, InvalidLengthError(len(bech)) } // Only ASCII characters between 33 and 126 are allowed. var hasLower, hasUpper bool for index := 0; index < len(bech); index++ { if bech[index] < 33 || bech[index] > 126 { return "", nil, InvalidCharacterError(bech[index]) } // The characters must be either all lowercase or all uppercase. Testing // directly with ascii codes is safe here, given the previous test. hasLower = hasLower || (bech[index] >= 97 && bech[index] <= 122) hasUpper = hasUpper || (bech[index] >= 65 && bech[index] <= 90) if hasLower && hasUpper { return "", nil, MixedCaseError{} } } // Bech32 standard uses only the lowercase for of strings for checksum // calculation. if hasUpper { bech = strings.ToLower(bech) } // The string is invalid if the last '1' is non-existent, it is the // first character of the string (no human-readable part) or one of the // last 6 characters of the string (since checksum cannot contain '1'). one := strings.LastIndexByte(bech, '1') if one < 1 || one+7 > len(bech) { return "", nil, InvalidSeparatorIndexError(one) } // The human-readable part is everything before the last '1'. hrp := bech[:one] data := bech[one+1:] // Each character corresponds to the byte with value of the index in // 'charset'. decoded, err := toBytes(data) if err != nil { return "", nil, err } // Verify if the checksum (stored inside decoded[:]) is valid, given the // previously decoded hrp. if !bech32VerifyChecksum(hrp, decoded) { // Invalid checksum. Calculate what it should have been, so that the // error contains this information. // Extract the payload bytes and actual checksum in the string. actual := bech[len(bech)-6:] payload := decoded[:len(decoded)-6] // Calculate the expected checksum, given the hrp and payload data. var expectedBldr strings.Builder expectedBldr.Grow(6) writeBech32Checksum(hrp, payload, &expectedBldr) expected := expectedBldr.String() err = InvalidChecksumError{ Expected: expected, Actual: actual, } return "", nil, err } // We exclude the last 6 bytes, which is the checksum. return hrp, decoded[:len(decoded)-6], nil } // Decode decodes a bech32 encoded string, returning the human-readable part and // the data part excluding the checksum. // // Note that the returned data is 5-bit (base32) encoded and the human-readable // part will be lowercase. func Decode(bech string) (string, []byte, error) { // The maximum allowed length for a bech32 string is 90. if len(bech) > 90 { return "", nil, InvalidLengthError(len(bech)) } return DecodeNoLimit(bech) } // Encode encodes a byte slice into a bech32 string with the given // human-readable part (HRP). The HRP will be converted to lowercase if needed // since mixed cased encodings are not permitted and lowercase is used for // checksum purposes. Note that the bytes must each encode 5 bits (base32). func Encode(hrp string, data []byte) (string, error) { // The resulting bech32 string is the concatenation of the lowercase hrp, // the separator 1, data and the 6-byte checksum. hrp = strings.ToLower(hrp) var bldr strings.Builder bldr.Grow(len(hrp) + 1 + len(data) + 6) bldr.WriteString(hrp) bldr.WriteString("1") // Write the data part, using the bech32 charset. for _, b := range data { if int(b) >= len(charset) { return "", InvalidDataByteError(b) } bldr.WriteByte(charset[b]) } // Calculate and write the checksum of the data. writeBech32Checksum(hrp, data, &bldr) return bldr.String(), nil } // ConvertBits converts a byte slice where each byte is encoding fromBits bits, // to a byte slice where each byte is encoding toBits bits. func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) { if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 { return nil, InvalidBitGroupsError{} } // Determine the maximum size the resulting array can have after base // conversion, so that we can size it a single time. This might be off // by a byte depending on whether padding is used or not and if the input // data is a multiple of both fromBits and toBits, but we ignore that and // just size it to the maximum possible. maxSize := len(data)*int(fromBits)/int(toBits) + 1 // The final bytes, each byte encoding toBits bits. regrouped := make([]byte, 0, maxSize) // Keep track of the next byte we create and how many bits we have // added to it out of the toBits goal. nextByte := byte(0) filledBits := uint8(0) for _, byt := range data { // Discard unused bits. byt <<= (8 - fromBits) // How many bits remaining to extract from the input data. remFromBits := fromBits for remFromBits > 0 { // How many bits remaining to be added to the next byte. remToBits := toBits - filledBits // The number of bytes to next extract is the minimum of // remFromBits and remToBits. toExtract := min(remToBits, remFromBits) // Add the next bits to nextByte, shifting the already // added bits to the left. nextByte = (nextByte << toExtract) | (byt >> (8 - toExtract)) // Discard the bits we just extracted and get ready for // next iteration. byt <<= toExtract remFromBits -= toExtract filledBits += toExtract // If the nextByte is completely filled, we add it to // our regrouped bytes and start on the next byte. if filledBits == toBits { regrouped = append(regrouped, nextByte) filledBits = 0 nextByte = 0 } } } // We pad any unfinished group if specified. if pad && filledBits > 0 { nextByte <<= (toBits - filledBits) regrouped = append(regrouped, nextByte) filledBits = 0 nextByte = 0 } // Any incomplete group must be <= 4 bits, and all zeroes. if filledBits > 0 && (filledBits > 4 || nextByte != 0) { return nil, InvalidIncompleteGroupError{} } return regrouped, nil } // EncodeFromBase256 converts a base256-encoded byte slice into a base32-encoded // byte slice and then encodes it into a bech32 string with the given // human-readable part (HRP). The HRP will be converted to lowercase if needed // since mixed cased encodings are not permitted and lowercase is used for // checksum purposes. func EncodeFromBase256(hrp string, data []byte) (string, error) { converted, err := ConvertBits(data, 8, 5, true) if err != nil { return "", err } return Encode(hrp, converted) } // DecodeToBase256 decodes a bech32-encoded string into its associated // human-readable part (HRP) and base32-encoded data, converts that data to a // base256-encoded byte slice and returns it along with the lowercase HRP. func DecodeToBase256(bech string) (string, []byte, error) { hrp, data, err := Decode(bech) if err != nil { return "", nil, err } converted, err := ConvertBits(data, 5, 8, false) if err != nil { return "", nil, err } return hrp, converted, nil } // EncodeFromBase256WithType converts a base256-encoded byte slice into a // base32-encoded byte slice and, concatenates the given type at the beginning // and then encodes it into a bech32 string with the given human-readable part (HRP). // // The HRP will be converted to lowercase if needed since mixed cased encodings // are not permitted and lowercase is used for checksum purposes. The maximum // size of type byte is 5 bits. func EncodeFromBase256WithType(hrp string, typ byte, data []byte) (string, error) { // Group the data bytes into 5 bit groups, as this is what is used to // encode each character in the bech32 string. converted, err := ConvertBits(data, 8, 5, true) if err != nil { return "", err } // Concatenate the type and encode the resulting bytes using bech32m encoding. combined := make([]byte, len(converted)+1) combined[0] = typ copy(combined[1:], converted) str, err := Encode(hrp, combined) if err != nil { return "", err } return str, nil } // DecodeToBase256WithTypeNoLimit decodes a bech32-encoded string into its associated // human-readable part (HRP), type byte and base32-encoded data, converts that data // to a base256-encoded byte slice. // // This function does NOT validate against the BIP-173 maximum length allowed // for bech32 strings. func DecodeToBase256WithTypeNoLimit(bech string) (string, byte, []byte, error) { // Decode the bech32m encoded string. hrp, data, err := DecodeNoLimit(bech) if err != nil { return "", 0, nil, err } // The first byte of the decoded data is the type, it must exist. if len(data) < 1 { return "", 0, nil, InvalidLengthError(0) } // The remaining characters of the data are grouped into // words of 5 bits. In order to restore the original program // bytes, we'll need to regroup into 8 bit words. regrouped, err := ConvertBits(data[1:], 5, 8, false) if err != nil { return "", 0, nil, err } return hrp, data[0], regrouped, nil } ================================================ FILE: util/bech32m/bech32m_test.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package bech32m import ( "bytes" "encoding/hex" "errors" "fmt" "strings" "testing" ) // TestBech32M tests that the following set of strings, based on the test // vectors in BIP-350 are either valid or invalid using the new bech32m // checksum algo. Some of these strings are similar to the set of above test // vectors, but end up with different checksums. func TestBech32M(t *testing.T) { tests := []struct { str string expectedError error }{ {"A1LQFN3A", nil}, {"a1lqfn3a", nil}, {"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6", nil}, {"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx", nil}, {"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8", nil}, {"split1checkupstagehandshakeupstreamerranterredcaperredlc445v", nil}, {"?1v759aa", nil}, // Additional test vectors used in bitcoin core {"\x201xj0phk", InvalidCharacterError('\x20')}, {"\x7f1g6xzxy", InvalidCharacterError('\x7f')}, {"\x801vctc34", InvalidCharacterError('\x80')}, { "an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4", InvalidLengthError(91), }, {"qyrz8wqd2c9m", InvalidSeparatorIndexError(-1)}, {"1qyrz8wqd2c9m", InvalidSeparatorIndexError(0)}, {"y1b0jsk6g", NonCharsetCharError(98)}, {"lt1igcx5c0", NonCharsetCharError(105)}, {"in1muywd", InvalidSeparatorIndexError(2)}, {"mm1crxm3i", NonCharsetCharError(105)}, {"au1s5cgom", NonCharsetCharError(111)}, {"16plkw9", InvalidLengthError(7)}, {"1p2gdwpf", InvalidSeparatorIndexError(0)}, {" 1nwldj5", InvalidCharacterError(' ')}, {"\x7f" + "1axkwrx", InvalidCharacterError(0x7f)}, {"\x801eym55h", InvalidCharacterError(0x80)}, } for no, tt := range tests { str := tt.str hrp, decoded, err := Decode(str) if !errors.Is(err, tt.expectedError) { t.Errorf("%d: (%v) expected decoding error %v "+ "instead got %v", no, str, tt.expectedError, err) continue } if err != nil { // End test case here if a decoding error was expected. continue } // Check that it encodes to the same string, using bech32 m. encoded, err := Encode(hrp, decoded) if err != nil { t.Errorf("encoding failed: %v", err) } if !strings.EqualFold(encoded, str) { t.Errorf("expected data to encode to %v, but got %v", str, encoded) } // Flip a bit in the string an make sure it is caught. pos := strings.LastIndexAny(str, "1") flipped := str[:pos+1] + string((str[pos+1] ^ 1)) + str[pos+2:] _, _, err = Decode(flipped) if err == nil { t.Error("expected decoding to fail") } } } // TestMixedCaseEncode ensures mixed case HRPs are converted to lowercase as // expected when encoding and that decoding the produced encoding when converted // to all uppercase produces the lowercase HRP and original data. func TestMixedCaseEncode(t *testing.T) { tests := []struct { name string hrp string data string encoded string }{{ name: "all uppercase HRP with no data", hrp: "A", data: "", encoded: "a1lqfn3a", }, { name: "all uppercase HRP with data", hrp: "UPPERCASE", data: "787878", encoded: "uppercase10pu8s9vw67r", }, { name: "mixed case HRP even offsets uppercase", hrp: "AbCdEf", data: "00443214c74254b635cf84653a56d7c675be77df", encoded: "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lwusvrv", }, { name: "mixed case HRP odd offsets uppercase ", hrp: "aBcDeF", data: "00443214c74254b635cf84653a56d7c675be77df", encoded: "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lwusvrv", }, { name: "all lowercase HRP", hrp: "abcdef", data: "00443214c74254b635cf84653a56d7c675be77df", encoded: "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lwusvrv", }} for _, tt := range tests { // Convert the text hex to bytes, convert those bytes from base256 to // base32, then ensure the encoded result with the HRP provided in the // test data is as expected. data, err := hex.DecodeString(tt.data) if err != nil { t.Errorf("%q: invalid hex %q: %v", tt.name, tt.data, err) continue } convertedData, err := ConvertBits(data, 8, 5, true) if err != nil { t.Errorf("%q: unexpected convert bits error: %v", tt.name, err) continue } gotEncoded, err := Encode(tt.hrp, convertedData) if err != nil { t.Errorf("%q: unexpected encode error: %v", tt.name, err) continue } if gotEncoded != tt.encoded { t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, tt.encoded) continue } // Ensure the decoding the expected lowercase encoding converted to all // uppercase produces the lowercase HRP and original data. gotHRP, gotData, err := Decode(strings.ToUpper(tt.encoded)) if err != nil { t.Errorf("%q: unexpected decode error: %v", tt.name, err) continue } wantHRP := strings.ToLower(tt.hrp) if gotHRP != wantHRP { t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", tt.name, gotHRP, wantHRP) continue } convertedGotData, err := ConvertBits(gotData, 5, 8, false) if err != nil { t.Errorf("%q: unexpected convert bits error: %v", tt.name, err) continue } if !bytes.Equal(convertedGotData, data) { t.Errorf("%q: mismatched data -- got %x, want %x", tt.name, convertedGotData, data) continue } } } // TestCanDecodeUnlimtedBech32 tests whether decoding a large bech32 string works // when using the DecodeNoLimit version. func TestCanDecodeUnlimtedBech32(t *testing.T) { input := "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqp2krp0" // basic check that an input of this length errors on regular Decode() _, _, err := Decode(input) if err == nil { t.Fatal("Test vector not appropriate") } // Try and decode it. hrp, data, err := DecodeNoLimit(input) if err != nil { t.Fatalf("Expected decoding of large string to work. Got error: %v", err) } // Verify data for correctness. if hrp != "1" { t.Fatalf("Unexpected hrp: %v", hrp) } decodedHex := fmt.Sprintf("%x", data) expected := "00000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000010000000000000000000000000000000000000000000000000000000000000000000000000" if decodedHex != expected { t.Fatalf("Unexpected decoded data: %s", decodedHex) } } // TestBech32Base256 ensures decoding and encoding various bech32, HRPs, and // data produces the expected results when using EncodeFromBase256 and // DecodeToBase256. It includes tests for proper handling of case // manipulations. func TestBech32Base256(t *testing.T) { tests := []struct { name string // test name encoded string // bech32 string to decode hrp string // expected human-readable part data string // expected hex-encoded data err error // expected error }{{ name: "all uppercase, no data", encoded: "A1LQFN3A", hrp: "a", data: "", }, { name: "long hrp with separator and excluded chars, no data", encoded: "an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio17hy8dj", hrp: "an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio", data: "", }, { name: "6 char hrp with data with leading zero", encoded: "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lwusvrv", hrp: "abcdef", data: "00443214c74254b635cf84653a56d7c675be77df", }, { name: "hrp same as separator and max length encoded string", encoded: "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqdm6ems", hrp: "1", data: "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", }, { name: "5 char hrp with data chosen to produce human-readable data part", encoded: "split1checkupstagehandshakeupstreamerranterredcaperredlc445v", hrp: "split", data: "c5f38b70305f519bf66d85fb6cf03058f3dde463ecd7918f2dc743918f2d", }, { name: "same as previous but with checksum invalidated", encoded: "split1checkupstagehandshakeupstreamerranterredcaperred2y9e2w", err: InvalidChecksumError{"lc445v", "2y9e2w"}, }, { name: "hrp with invalid character (space)", encoded: "s lit1checkupstagehandshakeupstreamerranterredcaperredp8hs2p", err: InvalidCharacterError(' '), }, { name: "hrp with invalid character (DEL)", encoded: "spl\x7ft1checkupstagehandshakeupstreamerranterredcaperredlc445v", err: InvalidCharacterError(127), }, { name: "data part with invalid character (o)", encoded: "split1cheo2y9e2w", err: NonCharsetCharError('o'), }, { name: "data part too short", encoded: "split1a2y9w", err: InvalidSeparatorIndexError(5), }, { name: "empty hrp", encoded: "1checkupstagehandshakeupstreamerranterredcaperredlc445v", err: InvalidSeparatorIndexError(0), }, { name: "no separator", encoded: "pzry9x0s0muk", err: InvalidSeparatorIndexError(-1), }, { name: "too long by one char", encoded: "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", err: InvalidLengthError(91), }, { name: "invalid due to mixed case in hrp", encoded: "aBcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", err: MixedCaseError{}, }, { name: "invalid due to mixed case in data part", encoded: "abcdef1Qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", err: MixedCaseError{}, }} for _, tt := range tests { // Ensure the decode either produces an error or not as expected. str := tt.encoded gotHRP, gotData, err := DecodeToBase256(str) if !errors.Is(tt.err, err) { t.Errorf("%q: unexpected decode error -- got %v, want %v", tt.name, err, tt.err) continue } if err != nil { // End test case here if a decoding error was expected. continue } // Ensure the expected HRP and original data are as expected. if gotHRP != tt.hrp { t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", tt.name, gotHRP, tt.hrp) continue } data, err := hex.DecodeString(tt.data) if err != nil { t.Errorf("%q: invalid hex %q: %v", tt.name, tt.data, err) continue } if !bytes.Equal(gotData, data) { t.Errorf("%q: mismatched data -- got %x, want %x", tt.name, gotData, data) continue } // Encode the same data with the HRP converted to all uppercase and // ensure the result is the lowercase version of the original encoded // bech32 string. gotEncoded, err := EncodeFromBase256(strings.ToUpper(tt.hrp), data) if err != nil { t.Errorf("%q: unexpected uppercase HRP encode error: %v", tt.name, err) } wantEncoded := strings.ToLower(str) if gotEncoded != wantEncoded { t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, wantEncoded) } // Encode the same data with the HRP converted to all lowercase and // ensure the result is the lowercase version of the original encoded // bech32 string. gotEncoded, err = EncodeFromBase256(strings.ToLower(tt.hrp), data) if err != nil { t.Errorf("%q: unexpected lowercase HRP encode error: %v", tt.name, err) } if gotEncoded != wantEncoded { t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, wantEncoded) } // Encode the same data with the HRP converted to mixed upper and // lowercase and ensure the result is the lowercase version of the // original encoded bech32 string. var mixedHRPBuilder strings.Builder for index, chr := range tt.hrp { if index%2 == 0 { mixedHRPBuilder.WriteString(strings.ToUpper(string(chr))) continue } mixedHRPBuilder.WriteRune(chr) } gotEncoded, err = EncodeFromBase256(mixedHRPBuilder.String(), data) if err != nil { t.Errorf("%q: unexpected lowercase HRP encode error: %v", tt.name, err) } if gotEncoded != wantEncoded { t.Errorf("%q: mismatched encoding -- got %q, want %q", tt.name, gotEncoded, wantEncoded) } // Ensure a bit flip in the string is caught. pos := strings.LastIndexAny(tt.encoded, "1") flipped := str[:pos+1] + string((str[pos+1] ^ 1)) + str[pos+2:] _, _, err = DecodeToBase256(flipped) if err == nil { t.Error("expected decoding to fail") } } } // BenchmarkEncodeDecodeCycle performs a benchmark for a full encode/decode // cycle of a bech32 string. It also reports the allocation count, which we // expect to be 2 for a fully optimized cycle. func BenchmarkEncodeDecodeCycle(b *testing.B) { // Use a fixed, 49-byte raw data for testing. inputData, err := hex.DecodeString( "cbe6365ddbcda9a9915422c3f091c13f8c7b2f263b8d34067bd12c274408473fa764871c9dd51b1bb34873b3473b633ed1") if err != nil { b.Fatalf("failed to initialize input data: %v", err) } // Convert this into a 79-byte, base 32 byte slice. base32Input, err := ConvertBits(inputData, 8, 5, true) if err != nil { b.Fatalf("failed to convert input to 32 bits-per-element: %v", err) } // Use a fixed hrp for the tests. This should generate an encoded bech32 // string of size 90 (the maximum allowed by BIP-173). hrp := "bc" // Begin the benchmark. Given that we test one roundtrip per iteration // (that is, one Encode() and one Decode() operation), we expect at most // 2 allocations per reported test op. b.ReportAllocs() for b.Loop() { str, err := Encode(hrp, base32Input) if err != nil { b.Fatalf("failed to encode input: %v", err) } _, _, err = Decode(str) if err != nil { b.Fatalf("failed to decode string: %v", err) } } } // TestConvertBits tests whether base conversion works using TestConvertBits(). func TestConvertBits(t *testing.T) { tests := []struct { input string output string fromBits uint8 toBits uint8 pad bool }{ // Trivial empty conversions. {"", "", 8, 5, false}, {"", "", 8, 5, true}, {"", "", 5, 8, false}, {"", "", 5, 8, true}, // Conversions of 0 value with/without padding. {"00", "00", 8, 5, false}, {"00", "0000", 8, 5, true}, {"0000", "00", 5, 8, false}, {"0000", "0000", 5, 8, true}, // Testing when conversion ends exactly at the byte edge. This makes // both padded and unpadded versions the same. {"0000000000", "0000000000000000", 8, 5, false}, {"0000000000", "0000000000000000", 8, 5, true}, {"0000000000000000", "0000000000", 5, 8, false}, {"0000000000000000", "0000000000", 5, 8, true}, // Conversions of full byte sequences. {"ffffff", "1f1f1f1f1e", 8, 5, true}, {"1f1f1f1f1e", "ffffff", 5, 8, false}, {"1f1f1f1f1e", "ffffff00", 5, 8, true}, // Sample random conversions. {"c9ca", "190705", 8, 5, false}, {"c9ca", "19070500", 8, 5, true}, {"19070500", "c9ca", 5, 8, false}, {"19070500", "c9ca00", 5, 8, true}, // Test cases tested on TestConvertBitsFailures with their corresponding // fixes. {"ff", "1f1c", 8, 5, true}, {"1f1c10", "ff20", 5, 8, true}, // Large conversions. { "cbe6365ddbcda9a9915422c3f091c13f8c7b2f263b8d34067bd12c274408473fa764871c9dd51b1bb34873b3473b633ed1", "190f13030c170e1b1916141a13040a14040b011f01040e01071e0607160b1906070e06130801131" + "b1a0416020e110008081c1f1a0e19040703120e1d0a06181b160d0407070c1a07070d11131d1408", 8, 5, true, }, { "190f13030c170e1b1916141a13040a14040b011f01040e01071e0607160b1906070e06130801131" + "b1a0416020e110008081c1f1a0e19040703120e1d0a06181b160d0407070c1a07070d11131d1408", "cbe6365ddbcda9a9915422c3f091c13f8c7b2f263b8d34067bd12c274408473fa764871c9dd51b1bb34873b3473b633ed100", 5, 8, true, }, } for no, tt := range tests { input, err := hex.DecodeString(tt.input) if err != nil { t.Fatalf("invalid test input data: %v", err) } expected, err := hex.DecodeString(tt.output) if err != nil { t.Fatalf("invalid test output data: %v", err) } actual, err := ConvertBits(input, tt.fromBits, tt.toBits, tt.pad) if err != nil { t.Fatalf("test case %d failed: %v", no, err) } if !bytes.Equal(actual, expected) { t.Fatalf("test case %d has wrong output; expected=%x actual=%x", no, expected, actual) } } } // TestConvertBitsFailures tests for the expected conversion failures of // ConvertBits(). func TestConvertBitsFailures(t *testing.T) { tests := []struct { input string fromBits uint8 toBits uint8 pad bool err error }{ // Not enough output bytes when not using padding. {"ff", 8, 5, false, InvalidIncompleteGroupError{}}, {"1f1c10", 5, 8, false, InvalidIncompleteGroupError{}}, // Unsupported bit conversions. {"", 0, 5, false, InvalidBitGroupsError{}}, {"", 10, 5, false, InvalidBitGroupsError{}}, {"", 5, 0, false, InvalidBitGroupsError{}}, {"", 5, 10, false, InvalidBitGroupsError{}}, } for no, tt := range tests { input, err := hex.DecodeString(tt.input) if err != nil { t.Fatalf("invalid test input data: %v", err) } _, err = ConvertBits(input, tt.fromBits, tt.toBits, tt.pad) if !errors.Is(err, tt.err) { t.Fatalf("test case %d failure: expected '%v' got '%v'", no, tt.err, err) } } } // BenchmarkConvertBitsDown benchmarks the speed and memory allocation behavior // of ConvertBits when converting from a higher base into a lower base (e.g. 8 // => 5). // // Only a single allocation is expected, which is used for the output array. func BenchmarkConvertBitsDown(b *testing.B) { // Use a fixed, 49-byte raw data for testing. inputData, err := hex.DecodeString( "cbe6365ddbcda9a9915422c3f091c13f8c7b2f263b8d34067bd12c274408473fa764871c9dd51b1bb34873b3473b633ed1") if err != nil { b.Fatalf("failed to initialize input data: %v", err) } b.ReportAllocs() for b.Loop() { _, err := ConvertBits(inputData, 8, 5, true) if err != nil { b.Fatalf("error converting bits: %v", err) } } } // BenchmarkConvertBitsUp benchmarks the speed and memory allocation behavior // of ConvertBits when converting from a lower base into a higher base (e.g. 5 // => 8). // // Only a single allocation is expected, which is used for the output array. func BenchmarkConvertBitsUp(b *testing.B) { // Use a fixed, 79-byte raw data for testing. inputData, err := hex.DecodeString( "190f13030c170e1b1916141a13040a14040b011f01040e01071e0607160b1906070e06130801131" + "b1a0416020e110008081c1f1a0e19040703120e1d0a06181b160d0407070c1a07070d11131d1408") if err != nil { b.Fatalf("failed to initialize input data: %v", err) } b.ReportAllocs() for b.Loop() { _, err := ConvertBits(inputData, 8, 5, true) if err != nil { b.Fatalf("error converting bits: %v", err) } } } // TestEncodeFromBase256WithType tests for the expected behavior of // EncodeFromBase256WithType function. func TestEncodeFromBase256WithType(t *testing.T) { tests := []struct { hrp string typ byte input string expectedBech string expectedError error }{ {"A", 0, "", "a1qy52hkn", nil}, {"AbC", 1, "1234", "abc1pzg6qgtt0h8", nil}, {"", 1, "abcd", "1p40xsjtqww4", nil}, {"", 32, "1", "", InvalidDataByteError(32)}, } for no, tt := range tests { data, _ := hex.DecodeString(tt.input) enc, err := EncodeFromBase256WithType(tt.hrp, tt.typ, data) if !errors.Is(err, tt.expectedError) { t.Errorf("%d: (%v) expected encoding error "+ "instead got %v", no, tt.expectedError, err) continue } if enc != tt.expectedBech { t.Errorf("%d: mismatched encoding -- got %q, want %q", no, enc, tt.expectedBech) } } } // TestDecodeToBase256WithTypeNoLimit tests for the expected behavior of // DecodeToBase256WithTypeNoLimit function. func TestDecodeToBase256WithTypeNoLimit(t *testing.T) { tests := []struct { bech string expectedHRP string expectedTyp byte expectedData string expectedError error }{ {"a1qy52hkn", "a", 0, "", nil}, {"abc1pzg6qgtt0h8", "abc", 1, "1234", nil}, {"1p40xsjtqww4", "", 0, "", InvalidSeparatorIndexError(0)}, {"a1lqfn3a", "", 0, "", InvalidLengthError(0)}, } for no, tt := range tests { hrp, typ, data, err := DecodeToBase256WithTypeNoLimit(tt.bech) if !errors.Is(err, tt.expectedError) { t.Errorf("%d: (%v) expected encoding error "+ "instead got %v", no, tt.expectedError, err) continue } if hrp != tt.expectedHRP { t.Errorf("%d: mismatched HRP -- got %q, want %q", no, hrp, tt.expectedHRP) } if typ != tt.expectedTyp { t.Errorf("%d: mismatched Type -- got %q, want %q", no, typ, tt.expectedTyp) } expectedData, _ := hex.DecodeString(tt.expectedData) if !bytes.Equal(expectedData, data) { t.Errorf("%d: mismatched HRP -- got \"%x\", want %q", no, data, tt.expectedData) } } } ================================================ FILE: util/bech32m/error.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package bech32m import ( "fmt" ) // MixedCaseError is returned when the bech32 string has both lower and uppercase // characters. type MixedCaseError struct{} func (MixedCaseError) Error() string { return "string not all lowercase or all uppercase" } // InvalidBitGroupsError is returned when conversion is attempted between byte // slices using bit-per-element of unsupported value. type InvalidBitGroupsError struct{} func (InvalidBitGroupsError) Error() string { return "only bit groups between 1 and 8 allowed" } // InvalidIncompleteGroupError is returned when then byte slice used as input has // data of wrong length. type InvalidIncompleteGroupError struct{} func (InvalidIncompleteGroupError) Error() string { return "invalid incomplete group" } // InvalidLengthError is returned when the bech32 string has an invalid length // given the BIP-173 defined restrictions. type InvalidLengthError int func (e InvalidLengthError) Error() string { return fmt.Sprintf("invalid bech32 string length %d", int(e)) } // InvalidCharacterError is returned when the bech32 string has a character // outside the range of the supported charset. type InvalidCharacterError rune func (e InvalidCharacterError) Error() string { return fmt.Sprintf("invalid character in string: '%c'", rune(e)) } // InvalidSeparatorIndexError is returned when the separator character '1' is // in an invalid position in the bech32 string. type InvalidSeparatorIndexError int func (e InvalidSeparatorIndexError) Error() string { return fmt.Sprintf("invalid separator index %d", int(e)) } // NonCharsetCharError is returned when a character outside the specific // bech32 charset is used in the string. type NonCharsetCharError rune func (e NonCharsetCharError) Error() string { return fmt.Sprintf("invalid character not part of charset: %v", int(e)) } // InvalidChecksumError is returned when the extracted checksum of the string // is different than what was expected. type InvalidChecksumError struct { Expected string Actual string } func (e InvalidChecksumError) Error() string { return fmt.Sprintf("invalid checksum (expected %v got %v)", e.Expected, e.Actual) } // InvalidDataByteError is returned when a byte outside the range required for // conversion into a string was found. type InvalidDataByteError byte func (e InvalidDataByteError) Error() string { return fmt.Sprintf("invalid data byte: %v", byte(e)) } ================================================ FILE: util/bip39/README.md ================================================ # go-bip39 A golang implementation of the BIP0039 spec for mnemonic seeds ## Example ```go package main import ( "github.com/pactus-project/pactus/util/bip39" "fmt" ) func main(){ // Generate a mnemonic for memorization or user-friendly seeds entropy, _ := bip39.NewEntropy(256) mnemonic, _ := bip39.NewMnemonic(entropy) // Generate a seed from the mnemonic seed := bip39.NewSeed(mnemonic, "Secret Passphrase") // Display mnemonic and seed fmt.Println("Mnemonic: ", mnemonic) fmt.Println("Seed: ", seed) } ``` ## Credits Wordlists are from the [bip39 spec](https://github.com/bitcoin/bips/tree/master/bip-0039). Test vectors are from the standard Python BIP0039 implementation from the Trezor team: [https://github.com/trezor/python-mnemonic](https://github.com/trezor/python-mnemonic) ================================================ FILE: util/bip39/bip39.go ================================================ // Package bip39 is the Golang implementation of the BIP39 spec. // // The official BIP39 spec can be found at // https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki package bip39 import ( "crypto/rand" "crypto/sha256" "crypto/sha512" "encoding/binary" "errors" "fmt" "math/big" "slices" "strings" "github.com/pactus-project/pactus/util/bip39/wordlists" "golang.org/x/crypto/pbkdf2" ) var ( // Some bitwise operands for working with big.Ints. last11BitsMask = big.NewInt(2047) shift11BitsMask = big.NewInt(2048) bigOne = big.NewInt(1) bigTwo = big.NewInt(2) // used to isolate the checksum bits from the entropy+checksum byte array. wordLengthChecksumMasksMapping = map[int]*big.Int{ 12: big.NewInt(15), 15: big.NewInt(31), 18: big.NewInt(63), 21: big.NewInt(127), 24: big.NewInt(255), } // used to use only the desired x of 8 available checksum bits. // 256 bit (word length 24) requires all 8 bits of the checksum, // and thus no shifting is needed for it (we would get a divByZero crash if we did). wordLengthChecksumShiftMapping = map[int]*big.Int{ 12: big.NewInt(16), 15: big.NewInt(8), 18: big.NewInt(4), 21: big.NewInt(2), } // wordList is the set of words to use. wordList []string // wordMap is a reverse lookup map for wordList. wordMap map[string]int ) var ( // ErrInvalidMnemonic is returned when trying to use a malformed mnemonic. ErrInvalidMnemonic = errors.New("invalid mnenomic") // ErrEntropyLengthInvalid is returned when trying to use an entropy set with // an invalid size. ErrEntropyLengthInvalid = errors.New("entropy length must be [128, 256] and a multiple of 32") // ErrValidatedSeedLengthMismatch is returned when a validated seed is not the // same size as the given seed. This should never happen is present only as a // sanity assertion. ErrValidatedSeedLengthMismatch = errors.New("seed length does not match validated seed length") // ErrChecksumIncorrect is returned when entropy has the incorrect checksum. ErrChecksumIncorrect = errors.New("checksum incorrect") ) func init() { SetWordList(wordlists.English) } // SetWordList sets the list of words to use for mnemonics. Currently the list // that is set is used package-wide. func SetWordList(list []string) { wordList = list wordMap = map[string]int{} for i, v := range wordList { wordMap[v] = i } } // GetWordList gets the list of words to use for mnemonics. func GetWordList() []string { return wordList } // GetWordIndex gets word index in wordMap. func GetWordIndex(word string) (int, bool) { idx, ok := wordMap[word] return idx, ok } // NewEntropy will create random entropy bytes // so long as the requested size bitSize is an appropriate size. // // bitSize has to be a multiple 32 and be within the inclusive range of {128, 256}. func NewEntropy(bitSize int) ([]byte, error) { err := validateEntropyBitSize(bitSize) if err != nil { return nil, err } entropy := make([]byte, bitSize/8) _, err = rand.Read(entropy) return entropy, err } // EntropyFromMnemonic takes a mnemonic generated by this library, // and returns the input entropy used to generate the given mnemonic. // An error is returned if the given mnemonic is invalid. func EntropyFromMnemonic(mnemonic string) ([]byte, error) { mnemonicSlice, isValid := splitMnemonicWords(mnemonic) if !isValid { return nil, ErrInvalidMnemonic } // Decode the words into a big.Int. bigInt := big.NewInt(0) for _, v := range mnemonicSlice { index, found := wordMap[v] if !found { return nil, fmt.Errorf("word `%v` not found in reverse map", v) } var wordBytes [2]byte binary.BigEndian.PutUint16(wordBytes[:], uint16(index)) bigInt = bigInt.Mul(bigInt, shift11BitsMask) bigInt = bigInt.Or(bigInt, big.NewInt(0).SetBytes(wordBytes[:])) } // Build and add the checksum to the big.Int. checksum := big.NewInt(0) checksumMask := wordLengthChecksumMasksMapping[len(mnemonicSlice)] checksum = checksum.And(bigInt, checksumMask) bigInt.Div(bigInt, big.NewInt(0).Add(checksumMask, bigOne)) // The entropy is the underlying bytes of the big.Int. Any upper bytes of // all 0's are not returned so we pad the beginning of the slice with empty // bytes if necessary. entropy := bigInt.Bytes() entropy = padByteSlice(entropy, len(mnemonicSlice)/3*4) // Generate the checksum and compare with the one we got from the mneomnic. entropyChecksumBytes := computeChecksum(entropy) entropyChecksum := big.NewInt(int64(entropyChecksumBytes[0])) if l := len(mnemonicSlice); l != 24 { checksumShift := wordLengthChecksumShiftMapping[l] entropyChecksum.Div(entropyChecksum, checksumShift) } if checksum.Cmp(entropyChecksum) != 0 { return nil, ErrChecksumIncorrect } return entropy, nil } // NewMnemonic will return a string consisting of the mnemonic words for // the given entropy. // If the provide entropy is invalid, an error will be returned. func NewMnemonic(entropy []byte) (string, error) { // Compute some lengths for convenience. entropyBitLength := len(entropy) * 8 checksumBitLength := entropyBitLength / 32 sentenceLength := (entropyBitLength + checksumBitLength) / 11 // Validate that the requested size is supported. err := validateEntropyBitSize(entropyBitLength) if err != nil { return "", err } // Add checksum to entropy. entropy = addChecksum(entropy) // Break entropy up into sentenceLength chunks of 11 bits. // For each word AND mask the rightmost 11 bits and find the word at that index. // Then bitshift entropy 11 bits right and repeat. // Add to the last empty slot so we can work with LSBs instead of MSB. // Entropy as an int so we can bitmask without worrying about bytes slices. entropyInt := new(big.Int).SetBytes(entropy) // Slice to hold words in. words := make([]string, sentenceLength) // Throw away big.Int for AND masking. word := big.NewInt(0) for i := sentenceLength - 1; i >= 0; i-- { // Get 11 right most bits and bitshift 11 to the right for next time. word.And(entropyInt, last11BitsMask) entropyInt.Div(entropyInt, shift11BitsMask) // Get the bytes representing the 11 bits as a 2 byte slice. wordBytes := padByteSlice(word.Bytes(), 2) // Convert bytes to an index and add that word to the list. words[i] = wordList[binary.BigEndian.Uint16(wordBytes)] } return strings.Join(words, " "), nil } // MnemonicToByteArray takes a mnemonic string and turns it into a byte array // suitable for creating another mnemonic. // An error is returned if the mnemonic is invalid. func MnemonicToByteArray(mnemonic string, raw ...bool) ([]byte, error) { var ( mnemonicSlice = strings.Split(mnemonic, " ") entropyBitSize = len(mnemonicSlice) * 11 checksumBitSize = entropyBitSize % 32 fullByteSize = (entropyBitSize-checksumBitSize)/8 + 1 checksumByteSize = fullByteSize - (fullByteSize % 4) ) // Pre validate that the mnemonic is well formed and only contains words that // are present in the word list. if !IsMnemonicValid(mnemonic) { return nil, ErrInvalidMnemonic } // Convert word indices to a big.Int representing the entropy. checksummedEntropy := big.NewInt(0) modulo := big.NewInt(2048) for _, v := range mnemonicSlice { index := big.NewInt(int64(wordMap[v])) checksummedEntropy.Mul(checksummedEntropy, modulo) checksummedEntropy.Add(checksummedEntropy, index) } // Calculate the unchecksummed entropy so we can validate that the checksum is // correct. checksumModulo := big.NewInt(0).Exp(bigTwo, big.NewInt(int64(checksumBitSize)), nil) rawEntropy := big.NewInt(0).Div(checksummedEntropy, checksumModulo) // Convert big.Ints to byte padded byte slices. rawEntropyBytes := padByteSlice(rawEntropy.Bytes(), checksumByteSize) checksummedEntropyBytes := padByteSlice(checksummedEntropy.Bytes(), fullByteSize) // Validate that the checksum is correct. newChecksummedEntropyBytes := padByteSlice(addChecksum(rawEntropyBytes), fullByteSize) if !compareByteSlices(checksummedEntropyBytes, newChecksummedEntropyBytes) { return nil, ErrChecksumIncorrect } if len(raw) > 0 && raw[0] { return rawEntropyBytes, nil } return checksummedEntropyBytes, nil } // NewSeedWithErrorChecking creates a hashed seed output given the mnemonic string and a password. // An error is returned if the mnemonic is not convertible to a byte array. func NewSeedWithErrorChecking(mnemonic, password string) ([]byte, error) { _, err := MnemonicToByteArray(mnemonic) if err != nil { return nil, err } return NewSeed(mnemonic, password), nil } // NewSeed creates a hashed seed output given a provided string and password. // No checking is performed to validate that the string provided is a valid mnemonic. func NewSeed(mnemonic, password string) []byte { return pbkdf2.Key([]byte(mnemonic), []byte("mnemonic"+password), 2048, 64, sha512.New) } // IsMnemonicValid attempts to verify that the provided mnemonic is valid. // Validity is determined by both the number of words being appropriate, // and that all the words in the mnemonic are present in the word list. func IsMnemonicValid(mnemonic string) bool { _, err := EntropyFromMnemonic(mnemonic) return err == nil } // Appends to data the first (len(data) / 32)bits of the result of sha256(data). // Currently only supports data up to 32 bytes. func addChecksum(data []byte) []byte { // Get first byte of sha256 hash := computeChecksum(data) firstChecksumByte := hash[0] // len() is in bytes so we divide by 4 checksumBitLength := uint(len(data) / 4) // For each bit of check sum we want we shift the data one the left // and then set the (new) right most bit equal to checksum bit at that index // staring from the left dataBigInt := new(big.Int).SetBytes(data) for i := uint(0); i < checksumBitLength; i++ { // Bitshift 1 left dataBigInt.Mul(dataBigInt, bigTwo) // Set rightmost bit if leftmost checksum bit is set if firstChecksumByte&(1<<(7-i)) > 0 { dataBigInt.Or(dataBigInt, bigOne) } } return dataBigInt.Bytes() } func computeChecksum(data []byte) []byte { hasher := sha256.New() _, _ = hasher.Write(data) return hasher.Sum(nil) } // validateEntropyBitSize ensures that entropy is the correct size for being a // mnemonic. func validateEntropyBitSize(bitSize int) error { if (bitSize%32) != 0 || bitSize < 128 || bitSize > 256 { return ErrEntropyLengthInvalid } return nil } // padByteSlice returns a byte slice of the given size with contents of the // given slice left padded and any empty spaces filled with 0's. func padByteSlice(slice []byte, length int) []byte { offset := length - len(slice) if offset <= 0 { return slice } newSlice := make([]byte, length) copy(newSlice[offset:], slice) return newSlice } // compareByteSlices returns true of the byte slices have equal contents and // returns false otherwise. func compareByteSlices(a, b []byte) bool { return slices.Equal(a, b) } func splitMnemonicWords(mnemonic string) ([]string, bool) { // Create a list of all the words in the mnemonic sentence words := strings.Fields(mnemonic) // Get num of words numOfWords := len(words) // The number of words should be 12, 15, 18, 21 or 24 if numOfWords%3 != 0 || numOfWords < 12 || numOfWords > 24 { return nil, false } return words, true } ================================================ FILE: util/bip39/bip39_test.go ================================================ //nolint:dupword,lll // BIP39 test data contains repeated words and long cryptographic strings package bip39 import ( "crypto/rand" "encoding/hex" "testing" "github.com/pactus-project/pactus/util/bip39/wordlists" ) type vector struct { entropy string mnemonic string seed string } func TestGetWordList(t *testing.T) { assertEqualStringSlices(t, wordlists.English, GetWordList()) } func TestGetWordIndex(t *testing.T) { for expectedIdx, word := range wordList { actualIdx, ok := GetWordIndex(word) assertTrue(t, ok) assertEqual(t, actualIdx, expectedIdx) } for _, word := range []string{"a", "set", "of", "invalid", "words"} { actualIdx, ok := GetWordIndex(word) assertFalse(t, ok) assertEqual(t, actualIdx, 0) } } func TestNewMnemonic(t *testing.T) { for _, vector := range testVectors() { entropy, err := hex.DecodeString(vector.entropy) assertNil(t, err) mnemonic, err := NewMnemonic(entropy) assertNil(t, err) assertEqualString(t, vector.mnemonic, mnemonic) _, err = NewSeedWithErrorChecking(mnemonic, "TREZOR") assertNil(t, err) seed := NewSeed(mnemonic, "TREZOR") assertEqualString(t, vector.seed, hex.EncodeToString(seed)) } } func TestNewMnemonicInvalidEntropy(t *testing.T) { _, err := NewMnemonic([]byte{}) assertNotNil(t, err) } func TestNewSeedWithErrorCheckingInvalidMnemonics(t *testing.T) { for _, vector := range badMnemonicSentences() { _, err := NewSeedWithErrorChecking(vector.mnemonic, "TREZOR") assertNotNil(t, err) } } func TestIsMnemonicValid(t *testing.T) { for _, vector := range badMnemonicSentences() { assertFalse(t, IsMnemonicValid(vector.mnemonic)) } for _, vector := range testVectors() { assertTrue(t, IsMnemonicValid(vector.mnemonic)) } } func TestMnemonicToByteArrayInvalidMnemonic(t *testing.T) { for _, vector := range badMnemonicSentences() { _, err := MnemonicToByteArray(vector.mnemonic) assertNotNil(t, err) } _, err := MnemonicToByteArray("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon yellow") assertNotNil(t, err) assertEqual(t, err, ErrInvalidMnemonic) } func TestNewEntropy(t *testing.T) { // Good tests. for i := 128; i <= 256; i += 32 { _, err := NewEntropy(i) assertNil(t, err) } // Bad Values for i := 0; i <= 256; i++ { if i%8 != 0 { _, err := NewEntropy(i) assertNotNil(t, err) } } } func TestMnemonicToByteArrayForDifferentArrayLangths(t *testing.T) { max := 1000 for i := 0; i < max; i++ { // 16, 20, 24, 28, 32 length := 16 + (i%5)*4 seed := make([]byte, length) if n, err := rand.Read(seed); err != nil { t.Errorf("%v", err) } else if n != length { t.Errorf("Wrong number of bytes read: %d", n) } mnemonic, err := NewMnemonic(seed) if err != nil { t.Errorf("%v", err) } _, err = MnemonicToByteArray(mnemonic) if err != nil { t.Errorf("Failed for %x - %v", seed, mnemonic) } } } func TestPadByteSlice(t *testing.T) { assertEqualByteSlices(t, []byte{0}, padByteSlice([]byte{}, 1)) assertEqualByteSlices(t, []byte{0, 1}, padByteSlice([]byte{1}, 2)) assertEqualByteSlices(t, []byte{1, 1}, padByteSlice([]byte{1, 1}, 2)) assertEqualByteSlices(t, []byte{1, 1, 1}, padByteSlice([]byte{1, 1, 1}, 2)) } func TestCompareByteSlices(t *testing.T) { assertTrue(t, compareByteSlices([]byte{}, []byte{})) assertTrue(t, compareByteSlices([]byte{1}, []byte{1})) assertFalse(t, compareByteSlices([]byte{1}, []byte{0})) assertFalse(t, compareByteSlices([]byte{1}, []byte{})) assertFalse(t, compareByteSlices([]byte{1}, nil)) } func TestMnemonicToByteArrayForZeroLeadingSeeds(t *testing.T) { mnemonics := []string{ "00000000000000000000000000000000", "00a84c51041d49acca66e6160c1fa999", "00ca45df1673c76537a2020bfed1dafd", "0019d5871c7b81fd83d474ef1c1e1dae", "00dcb021afb35ffcdd1d032d2056fc86", "0062be7bd09a27288b6cf0eb565ec739", "00dc705b5efa0adf25b9734226ba60d4", "0017747418d54c6003fa64fade83374b", "000d44d3ee7c3dfa45e608c65384431b", "008241c1ef976b0323061affe5bf24b9", "00a6aec77e4d16bea80b50a34991aaba", "0011527b8c6ddecb9d0c20beccdeb58d", "001c938c503c8f5a2bba2248ff621546", "0002f90aaf7a8327698f0031b6317c36", "00bff43071ed7e07f77b14f615993bac", "00da143e00ef17fc63b6fb22dcc2c326", "00ffc6764fb32a354cab1a3ddefb015d", "0062ef47e0985e8953f24760b7598cdd", "003bf9765064f71d304908d906c065f5", "00993851503471439d154b3613947474", "007ad0ffe9eae753a483a76af06dfa67", "00091824db9ec19e663bee51d64c83cc", "00f48ac621f7e3cb39b2012ac3121543", "0072917415cdca24dfa66c4a92c885b4", "0027ced2b279ea8a91d29364487cdbf4", "00b9c0d37fb10ba272e55842ad812583", "004b3d0d2b9285946c687a5350479c8c", "00c7c12a37d3a7f8c1532b17c89b724c", "00f400c5545f06ae17ad00f3041e4e26", "001e290be10df4d209f247ac5878662b", "00bf0f74568e582a7dd1ee64f792ec8b", "00d2e43ecde6b72b847db1539ed89e23", "00cecba6678505bb7bfec8ed307251f6", "000aeed1a9edcbb4bc88f610d3ce84eb", "00d06206aadfc25c2b21805d283f15ae", "00a31789a2ab2d54f8fadd5331010287", "003493c5f520e8d5c0483e895a121dc9", "004706112800b76001ece2e268bc830e", "00ab31e28bb5305be56e38337dbfa486", "006872fe85df6b0fa945248e6f9379d1", "00717e5e375da6934e3cfdf57edaf3bd", "007f1b46e7b9c4c76e77c434b9bccd6b", "00dc93735aa35def3b9a2ff676560205", "002cd5dcd881a49c7b87714c6a570a76", "0013b5af9e13fac87e0c505686cfb6bf", "007ab1ec9526b0bc04b64ae65fd42631", "00abb4e11d8385c1cca905a6a65e9144", "00574fc62a0501ad8afada2e246708c3", "005207e0a815bb2da6b4c35ec1f2bf52", "00f3460f136fb9700080099cbd62bc18", "007a591f204c03ca7b93981237112526", "00cfe0befd428f8e5f83a5bfc801472e", "00987551ac7a879bf0c09b8bc474d9af", "00cadd3ce3d78e49fbc933a85682df3f", "00bfbf2e346c855ccc360d03281455a1", "004cdf55d429d028f715544ce22d4f31", "0075c84a7d15e0ac85e1e41025eed23b", "00807dddd61f71725d336cab844d2cb5", "00422f21b77fe20e367467ed98c18410", "00b44d0ac622907119c626c850a462fd", "00363f5e7f22fc49f3cd662a28956563", "000fe5837e68397bbf58db9f221bdc4e", "0056af33835c888ef0c22599686445d3", "00790a8647fd3dfb38b7e2b6f578f2c6", "00da8d9009675cb7beec930e263014fb", "00d4b384540a5bb54aa760edaa4fb2fe", "00be9b1479ed680fdd5d91a41eb926d0", "009182347502af97077c40a6e74b4b5c", "00f5c90ee1c67fa77fd821f8e9fab4f1", "005568f9a2dd6b0c0cc2f5ba3d9cac38", "008b481f8678577d9cf6aa3f6cd6056b", "00c4323ece5e4fe3b6cd4c5c932931af", "009791f7550c3798c5a214cb2d0ea773", "008a7baab22481f0ad8167dd9f90d55c", "00f0e601519aafdc8ff94975e64c946d", "0083b61e0daa9219df59d697c270cd31", } for _, m := range mnemonics { seed, _ := hex.DecodeString(m) mnemonic, err := NewMnemonic(seed) if err != nil { t.Errorf("%v", err) } _, err = MnemonicToByteArray(mnemonic) if err != nil { t.Errorf("Failed for %x - %v", seed, mnemonic) } } } func TestEntropyFromMnemonic128(t *testing.T) { testEntropyFromMnemonic(t, 128) } func TestEntropyFromMnemonic160(t *testing.T) { testEntropyFromMnemonic(t, 160) } func TestEntropyFromMnemonic192(t *testing.T) { testEntropyFromMnemonic(t, 192) } func TestEntropyFromMnemonic224(t *testing.T) { testEntropyFromMnemonic(t, 224) } func TestEntropyFromMnemonic256(t *testing.T) { testEntropyFromMnemonic(t, 256) } func TestEntropyFromMnemonicInvalidChecksum(t *testing.T) { _, err := EntropyFromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon yellow") assertEqual(t, ErrChecksumIncorrect, err) } func TestEntropyFromMnemonicInvalidMnemonicSize(t *testing.T) { for _, mnemonic := range []string{ "a a a a a a a a a a a a a a a a a a a a a a a a a", // Too many words "a", // Too few "a a a a a a a a a a a a a a", // Not multiple of 3 } { _, err := EntropyFromMnemonic(mnemonic) assertEqual(t, ErrInvalidMnemonic, err) } } func testEntropyFromMnemonic(t *testing.T, bitSize int) { t.Helper() for i := 0; i < 512; i++ { expectedEntropy, err := NewEntropy(bitSize) assertNil(t, err) assertTrue(t, expectedEntropy != nil) mnemonic, err := NewMnemonic(expectedEntropy) assertNil(t, err) assertTrue(t, mnemonic != "") actualEntropy, err := EntropyFromMnemonic(mnemonic) assertNil(t, err) assertEqualByteSlices(t, expectedEntropy, actualEntropy) } } func testVectors() []vector { return []vector{ { entropy: "00000000000000000000000000000000", mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", seed: "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04", }, { entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow", seed: "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607", }, { entropy: "80808080808080808080808080808080", mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", seed: "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8", }, { entropy: "ffffffffffffffffffffffffffffffff", mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", seed: "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069", }, { entropy: "000000000000000000000000000000000000000000000000", mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent", seed: "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa", }, { entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", mnemonic: "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will", seed: "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd", }, { entropy: "808080808080808080808080808080808080808080808080", mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always", seed: "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65", }, { entropy: "ffffffffffffffffffffffffffffffffffffffffffffffff", mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when", seed: "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528", }, { entropy: "0000000000000000000000000000000000000000000000000000000000000000", mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", seed: "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8", }, { entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", mnemonic: "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", seed: "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87", }, { entropy: "8080808080808080808080808080808080808080808080808080808080808080", mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", seed: "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f", }, { entropy: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", seed: "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad", }, { entropy: "77c2b00716cec7213839159e404db50d", mnemonic: "jelly better achieve collect unaware mountain thought cargo oxygen act hood bridge", seed: "b5b6d0127db1a9d2226af0c3346031d77af31e918dba64287a1b44b8ebf63cdd52676f672a290aae502472cf2d602c051f3e6f18055e84e4c43897fc4e51a6ff", }, { entropy: "b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b", mnemonic: "renew stay biology evidence goat welcome casual join adapt armor shuffle fault little machine walk stumble urge swap", seed: "9248d83e06f4cd98debf5b6f010542760df925ce46cf38a1bdb4e4de7d21f5c39366941c69e1bdbf2966e0f6e6dbece898a0e2f0a4c2b3e640953dfe8b7bbdc5", }, { entropy: "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982", mnemonic: "dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic", seed: "ff7f3184df8696d8bef94b6c03114dbee0ef89ff938712301d27ed8336ca89ef9635da20af07d4175f2bf5f3de130f39c9d9e8dd0472489c19b1a020a940da67", }, { entropy: "0460ef47585604c5660618db2e6a7e7f", mnemonic: "afford alter spike radar gate glance object seek swamp infant panel yellow", seed: "65f93a9f36b6c85cbe634ffc1f99f2b82cbb10b31edc7f087b4f6cb9e976e9faf76ff41f8f27c99afdf38f7a303ba1136ee48a4c1e7fcd3dba7aa876113a36e4", }, { entropy: "72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f", mnemonic: "indicate race push merry suffer human cruise dwarf pole review arch keep canvas theme poem divorce alter left", seed: "3bbf9daa0dfad8229786ace5ddb4e00fa98a044ae4c4975ffd5e094dba9e0bb289349dbe2091761f30f382d4e35c4a670ee8ab50758d2c55881be69e327117ba", }, { entropy: "2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416", mnemonic: "clutch control vehicle tonight unusual clog visa ice plunge glimpse recipe series open hour vintage deposit universe tip job dress radar refuse motion taste", seed: "fe908f96f46668b2d5b37d82f558c77ed0d69dd0e7e043a5b0511c48c2f1064694a956f86360c93dd04052a8899497ce9e985ebe0c8c52b955e6ae86d4ff4449", }, { entropy: "eaebabb2383351fd31d703840b32e9e2", mnemonic: "turtle front uncle idea crush write shrug there lottery flower risk shell", seed: "bdfb76a0759f301b0b899a1e3985227e53b3f51e67e3f2a65363caedf3e32fde42a66c404f18d7b05818c95ef3ca1e5146646856c461c073169467511680876c", }, { entropy: "7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78", mnemonic: "kiss carry display unusual confirm curtain upgrade antique rotate hello void custom frequent obey nut hole price segment", seed: "ed56ff6c833c07982eb7119a8f48fd363c4a9b1601cd2de736b01045c5eb8ab4f57b079403485d1c4924f0790dc10a971763337cb9f9c62226f64fff26397c79", }, { entropy: "4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef", mnemonic: "exile ask congress lamp submit jacket era scheme attend cousin alcohol catch course end lucky hurt sentence oven short ball bird grab wing top", seed: "095ee6f817b4c2cb30a5a797360a81a40ab0f9a4e25ecd672a3f58a0b5ba0687c096a6b14d2c0deb3bdefce4f61d01ae07417d502429352e27695163f7447a8c", }, { entropy: "18ab19a9f54a9274f03e5209a2ac8a91", mnemonic: "board flee heavy tunnel powder denial science ski answer betray cargo cat", seed: "6eff1bb21562918509c73cb990260db07c0ce34ff0e3cc4a8cb3276129fbcb300bddfe005831350efd633909f476c45c88253276d9fd0df6ef48609e8bb7dca8", }, { entropy: "18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4", mnemonic: "board blade invite damage undo sun mimic interest slam gaze truly inherit resist great inject rocket museum chief", seed: "f84521c777a13b61564234bf8f8b62b3afce27fc4062b51bb5e62bdfecb23864ee6ecf07c1d5a97c0834307c5c852d8ceb88e7c97923c0a3b496bedd4e5f88a9", }, { entropy: "15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419", mnemonic: "beyond stage sleep clip because twist token leaf atom beauty genius food business side grid unable middle armed observe pair crouch tonight away coconut", seed: "b15509eaa2d09d3efd3e006ef42151b30367dc6e3aa5e44caba3fe4d3e352e65101fbdb86a96776b91946ff06f8eac594dc6ee1d3e82a42dfe1b40fef6bcc3fd", }, } } func badMnemonicSentences() []vector { return []vector{ {mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"}, {mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow yellow"}, {mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice caged above"}, {mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo, wrong"}, {mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"}, {mnemonic: "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will will will"}, {mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always."}, {mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo why"}, {mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art art"}, {mnemonic: "legal winner thank year wave sausage worth useful legal winner thanks year wave worth useful legal winner thank year wave sausage worth title"}, {mnemonic: "letter advice cage absurd amount doctor acoustic avoid letters advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless"}, {mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo voted"}, {mnemonic: "jello better achieve collect unaware mountain thought cargo oxygen act hood bridge"}, {mnemonic: "renew, stay, biology, evidence, goat, welcome, casual, join, adapt, armor, shuffle, fault, little, machine, walk, stumble, urge, swap"}, {mnemonic: "dignity pass list indicate nasty"}, // From issue 32 {mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon letter"}, } } func assertNil(t *testing.T, object any) { t.Helper() if object != nil { t.Errorf("Expected nil, got %v", object) } } func assertNotNil(t *testing.T, object any) { t.Helper() if object == nil { t.Error("Expected not nil") } } func assertTrue(t *testing.T, a bool) { t.Helper() if !a { t.Error("Expected true, got false") } } func assertFalse(t *testing.T, a bool) { t.Helper() if a { t.Error("Expected false, got true") } } func assertEqual(t *testing.T, expected, actual any) { t.Helper() if expected != actual { t.Errorf("Objects not equal, expected `%s` and got `%s`", expected, actual) } } func assertEqualString(t *testing.T, expected, actual string) { t.Helper() if expected != actual { t.Errorf("Strings not equal, expected `%s` and got `%s`", expected, actual) } } func assertEqualStringSlices(t *testing.T, expected, actual []string) { t.Helper() if len(expected) != len(actual) { t.Errorf("String slices not equal, expected %v and got %v", expected, actual) return } for i := range expected { if expected[i] != actual[i] { t.Errorf("String slices not equal, expected %v and got %v", expected, actual) return } } } func assertEqualByteSlices(t *testing.T, expected, actual []byte) { t.Helper() if len(expected) != len(actual) { t.Errorf("Byte slices not equal, expected %v and got %v", expected, actual) return } for i := range expected { if expected[i] != actual[i] { t.Errorf("Byte slices not equal, expected %v and got %v", expected, actual) return } } } ================================================ FILE: util/bip39/example_test.go ================================================ //nolint:lll // long hex strings in test output package bip39_test import ( "encoding/hex" "fmt" "github.com/pactus-project/pactus/util/bip39" ) func ExampleNewMnemonic() { // the entropy can be any byte slice, generated how pleased, // as long its bit size is a multiple of 32 and is within // the inclusive range of {128,256} entropy, _ := hex.DecodeString("066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad") // generate a mnemomic mnemomic, _ := bip39.NewMnemonic(entropy) fmt.Println(mnemomic) // output: // all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform } func ExampleNewSeed() { seed := bip39.NewSeed("all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform", "TREZOR") fmt.Println(hex.EncodeToString(seed)) // output: // 26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d } ================================================ FILE: util/bip39/wordlists/chinese_simplified.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/chinese_simplified.txt // $ crc32 chinese_simplified.txt // e3721bbf checksum := crc32.ChecksumIEEE([]byte(chineseSimplified)) if fmt.Sprintf("%x", checksum) != "e3721bbf" { panic("chineseSimplified checksum invalid") } } // ChineseSimplified is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/chinese_simplified.txt var ( ChineseSimplified = strings.Split(strings.TrimSpace(chineseSimplified), "\n") chineseSimplified = `的 一 是 在 不 了 有 和 人 这 中 大 为 上 个 国 我 以 要 他 时 来 用 们 生 到 作 地 于 出 就 分 对 成 会 可 主 发 年 动 同 工 也 能 下 过 子 说 产 种 面 而 方 后 多 定 行 学 法 所 民 得 经 十 三 之 进 着 等 部 度 家 电 力 里 如 水 化 高 自 二 理 起 小 物 现 实 加 量 都 两 体 制 机 当 使 点 从 业 本 去 把 性 好 应 开 它 合 还 因 由 其 些 然 前 外 天 政 四 日 那 社 义 事 平 形 相 全 表 间 样 与 关 各 重 新 线 内 数 正 心 反 你 明 看 原 又 么 利 比 或 但 质 气 第 向 道 命 此 变 条 只 没 结 解 问 意 建 月 公 无 系 军 很 情 者 最 立 代 想 已 通 并 提 直 题 党 程 展 五 果 料 象 员 革 位 入 常 文 总 次 品 式 活 设 及 管 特 件 长 求 老 头 基 资 边 流 路 级 少 图 山 统 接 知 较 将 组 见 计 别 她 手 角 期 根 论 运 农 指 几 九 区 强 放 决 西 被 干 做 必 战 先 回 则 任 取 据 处 队 南 给 色 光 门 即 保 治 北 造 百 规 热 领 七 海 口 东 导 器 压 志 世 金 增 争 济 阶 油 思 术 极 交 受 联 什 认 六 共 权 收 证 改 清 美 再 采 转 更 单 风 切 打 白 教 速 花 带 安 场 身 车 例 真 务 具 万 每 目 至 达 走 积 示 议 声 报 斗 完 类 八 离 华 名 确 才 科 张 信 马 节 话 米 整 空 元 况 今 集 温 传 土 许 步 群 广 石 记 需 段 研 界 拉 林 律 叫 且 究 观 越 织 装 影 算 低 持 音 众 书 布 复 容 儿 须 际 商 非 验 连 断 深 难 近 矿 千 周 委 素 技 备 半 办 青 省 列 习 响 约 支 般 史 感 劳 便 团 往 酸 历 市 克 何 除 消 构 府 称 太 准 精 值 号 率 族 维 划 选 标 写 存 候 毛 亲 快 效 斯 院 查 江 型 眼 王 按 格 养 易 置 派 层 片 始 却 专 状 育 厂 京 识 适 属 圆 包 火 住 调 满 县 局 照 参 红 细 引 听 该 铁 价 严 首 底 液 官 德 随 病 苏 失 尔 死 讲 配 女 黄 推 显 谈 罪 神 艺 呢 席 含 企 望 密 批 营 项 防 举 球 英 氧 势 告 李 台 落 木 帮 轮 破 亚 师 围 注 远 字 材 排 供 河 态 封 另 施 减 树 溶 怎 止 案 言 士 均 武 固 叶 鱼 波 视 仅 费 紧 爱 左 章 早 朝 害 续 轻 服 试 食 充 兵 源 判 护 司 足 某 练 差 致 板 田 降 黑 犯 负 击 范 继 兴 似 余 坚 曲 输 修 故 城 夫 够 送 笔 船 占 右 财 吃 富 春 职 觉 汉 画 功 巴 跟 虽 杂 飞 检 吸 助 升 阳 互 初 创 抗 考 投 坏 策 古 径 换 未 跑 留 钢 曾 端 责 站 简 述 钱 副 尽 帝 射 草 冲 承 独 令 限 阿 宣 环 双 请 超 微 让 控 州 良 轴 找 否 纪 益 依 优 顶 础 载 倒 房 突 坐 粉 敌 略 客 袁 冷 胜 绝 析 块 剂 测 丝 协 诉 念 陈 仍 罗 盐 友 洋 错 苦 夜 刑 移 频 逐 靠 混 母 短 皮 终 聚 汽 村 云 哪 既 距 卫 停 烈 央 察 烧 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 游 久 菜 味 旧 模 湖 货 损 预 阻 毫 普 稳 乙 妈 植 息 扩 银 语 挥 酒 守 拿 序 纸 医 缺 雨 吗 针 刘 啊 急 唱 误 训 愿 审 附 获 茶 鲜 粮 斤 孩 脱 硫 肥 善 龙 演 父 渐 血 欢 械 掌 歌 沙 刚 攻 谓 盾 讨 晚 粒 乱 燃 矛 乎 杀 药 宁 鲁 贵 钟 煤 读 班 伯 香 介 迫 句 丰 培 握 兰 担 弦 蛋 沉 假 穿 执 答 乐 谁 顺 烟 缩 征 脸 喜 松 脚 困 异 免 背 星 福 买 染 井 概 慢 怕 磁 倍 祖 皇 促 静 补 评 翻 肉 践 尼 衣 宽 扬 棉 希 伤 操 垂 秋 宜 氢 套 督 振 架 亮 末 宪 庆 编 牛 触 映 雷 销 诗 座 居 抓 裂 胞 呼 娘 景 威 绿 晶 厚 盟 衡 鸡 孙 延 危 胶 屋 乡 临 陆 顾 掉 呀 灯 岁 措 束 耐 剧 玉 赵 跳 哥 季 课 凯 胡 额 款 绍 卷 齐 伟 蒸 殖 永 宗 苗 川 炉 岩 弱 零 杨 奏 沿 露 杆 探 滑 镇 饭 浓 航 怀 赶 库 夺 伊 灵 税 途 灭 赛 归 召 鼓 播 盘 裁 险 康 唯 录 菌 纯 借 糖 盖 横 符 私 努 堂 域 枪 润 幅 哈 竟 熟 虫 泽 脑 壤 碳 欧 遍 侧 寨 敢 彻 虑 斜 薄 庭 纳 弹 饲 伸 折 麦 湿 暗 荷 瓦 塞 床 筑 恶 户 访 塔 奇 透 梁 刀 旋 迹 卡 氯 遇 份 毒 泥 退 洗 摆 灰 彩 卖 耗 夏 择 忙 铜 献 硬 予 繁 圈 雪 函 亦 抽 篇 阵 阴 丁 尺 追 堆 雄 迎 泛 爸 楼 避 谋 吨 野 猪 旗 累 偏 典 馆 索 秦 脂 潮 爷 豆 忽 托 惊 塑 遗 愈 朱 替 纤 粗 倾 尚 痛 楚 谢 奋 购 磨 君 池 旁 碎 骨 监 捕 弟 暴 割 贯 殊 释 词 亡 壁 顿 宝 午 尘 闻 揭 炮 残 冬 桥 妇 警 综 招 吴 付 浮 遭 徐 您 摇 谷 赞 箱 隔 订 男 吹 园 纷 唐 败 宋 玻 巨 耕 坦 荣 闭 湾 键 凡 驻 锅 救 恩 剥 凝 碱 齿 截 炼 麻 纺 禁 废 盛 版 缓 净 睛 昌 婚 涉 筒 嘴 插 岸 朗 庄 街 藏 姑 贸 腐 奴 啦 惯 乘 伙 恢 匀 纱 扎 辩 耳 彪 臣 亿 璃 抵 脉 秀 萨 俄 网 舞 店 喷 纵 寸 汗 挂 洪 贺 闪 柬 爆 烯 津 稻 墙 软 勇 像 滚 厘 蒙 芳 肯 坡 柱 荡 腿 仪 旅 尾 轧 冰 贡 登 黎 削 钻 勒 逃 障 氨 郭 峰 币 港 伏 轨 亩 毕 擦 莫 刺 浪 秘 援 株 健 售 股 岛 甘 泡 睡 童 铸 汤 阀 休 汇 舍 牧 绕 炸 哲 磷 绩 朋 淡 尖 启 陷 柴 呈 徒 颜 泪 稍 忘 泵 蓝 拖 洞 授 镜 辛 壮 锋 贫 虚 弯 摩 泰 幼 廷 尊 窗 纲 弄 隶 疑 氏 宫 姐 震 瑞 怪 尤 琴 循 描 膜 违 夹 腰 缘 珠 穷 森 枝 竹 沟 催 绳 忆 邦 剩 幸 浆 栏 拥 牙 贮 礼 滤 钠 纹 罢 拍 咱 喊 袖 埃 勤 罚 焦 潜 伍 墨 欲 缝 姓 刊 饱 仿 奖 铝 鬼 丽 跨 默 挖 链 扫 喝 袋 炭 污 幕 诸 弧 励 梅 奶 洁 灾 舟 鉴 苯 讼 抱 毁 懂 寒 智 埔 寄 届 跃 渡 挑 丹 艰 贝 碰 拔 爹 戴 码 梦 芽 熔 赤 渔 哭 敬 颗 奔 铅 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 仓 魏 锐 晓 氮 兼 隐 碍 赫 拨 忠 肃 缸 牵 抢 博 巧 壳 兄 杜 讯 诚 碧 祥 柯 页 巡 矩 悲 灌 龄 伦 票 寻 桂 铺 圣 恐 恰 郑 趣 抬 荒 腾 贴 柔 滴 猛 阔 辆 妻 填 撤 储 签 闹 扰 紫 砂 递 戏 吊 陶 伐 喂 疗 瓶 婆 抚 臂 摸 忍 虾 蜡 邻 胸 巩 挤 偶 弃 槽 劲 乳 邓 吉 仁 烂 砖 租 乌 舰 伴 瓜 浅 丙 暂 燥 橡 柳 迷 暖 牌 秧 胆 详 簧 踏 瓷 谱 呆 宾 糊 洛 辉 愤 竞 隙 怒 粘 乃 绪 肩 籍 敏 涂 熙 皆 侦 悬 掘 享 纠 醒 狂 锁 淀 恨 牲 霸 爬 赏 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鸭 趋 凤 晨 畜 辈 秩 卵 署 梯 炎 滩 棋 驱 筛 峡 冒 啥 寿 译 浸 泉 帽 迟 硅 疆 贷 漏 稿 冠 嫩 胁 芯 牢 叛 蚀 奥 鸣 岭 羊 凭 串 塘 绘 酵 融 盆 锡 庙 筹 冻 辅 摄 袭 筋 拒 僚 旱 钾 鸟 漆 沈 眉 疏 添 棒 穗 硝 韩 逼 扭 侨 凉 挺 碗 栽 炒 杯 患 馏 劝 豪 辽 勃 鸿 旦 吏 拜 狗 埋 辊 掩 饮 搬 骂 辞 勾 扣 估 蒋 绒 雾 丈 朵 姆 拟 宇 辑 陕 雕 偿 蓄 崇 剪 倡 厅 咬 驶 薯 刷 斥 番 赋 奉 佛 浇 漫 曼 扇 钙 桃 扶 仔 返 俗 亏 腔 鞋 棱 覆 框 悄 叔 撞 骗 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 胀 谐 抛 霉 桑 岗 嘛 衰 盗 渗 脏 赖 涌 甜 曹 阅 肌 哩 厉 烃 纬 毅 昨 伪 症 煮 叹 钉 搭 茎 笼 酷 偷 弓 锥 恒 杰 坑 鼻 翼 纶 叙 狱 逮 罐 络 棚 抑 膨 蔬 寺 骤 穆 冶 枯 册 尸 凸 绅 坯 牺 焰 轰 欣 晋 瘦 御 锭 锦 丧 旬 锻 垄 搜 扑 邀 亭 酯 迈 舒 脆 酶 闲 忧 酚 顽 羽 涨 卸 仗 陪 辟 惩 杭 姚 肚 捉 飘 漂 昆 欺 吾 郎 烷 汁 呵 饰 萧 雅 邮 迁 燕 撒 姻 赴 宴 烦 债 帐 斑 铃 旨 醇 董 饼 雏 姿 拌 傅 腹 妥 揉 贤 拆 歪 葡 胺 丢 浩 徽 昂 垫 挡 览 贪 慰 缴 汪 慌 冯 诺 姜 谊 凶 劣 诬 耀 昏 躺 盈 骑 乔 溪 丛 卢 抹 闷 咨 刮 驾 缆 悟 摘 铒 掷 颇 幻 柄 惠 惨 佳 仇 腊 窝 涤 剑 瞧 堡 泼 葱 罩 霍 捞 胎 苍 滨 俩 捅 湘 砍 霞 邵 萄 疯 淮 遂 熊 粪 烘 宿 档 戈 驳 嫂 裕 徙 箭 捐 肠 撑 晒 辨 殿 莲 摊 搅 酱 屏 疫 哀 蔡 堵 沫 皱 畅 叠 阁 莱 敲 辖 钩 痕 坝 巷 饿 祸 丘 玄 溜 曰 逻 彭 尝 卿 妨 艇 吞 韦 怨 矮 歇 ` ) ================================================ FILE: util/bip39/wordlists/chinese_traditional.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/chinese_traditional.txt // $ crc32 chinese_traditional.txt // 3c20b443 checksum := crc32.ChecksumIEEE([]byte(chineseTraditional)) if fmt.Sprintf("%x", checksum) != "3c20b443" { panic("chineseTraditional checksum invalid") } } // ChineseTraditional is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/chinese_traditional.txt var ( ChineseTraditional = strings.Split(strings.TrimSpace(chineseTraditional), "\n") chineseTraditional = `的 一 是 在 不 了 有 和 人 這 中 大 為 上 個 國 我 以 要 他 時 來 用 們 生 到 作 地 於 出 就 分 對 成 會 可 主 發 年 動 同 工 也 能 下 過 子 說 產 種 面 而 方 後 多 定 行 學 法 所 民 得 經 十 三 之 進 著 等 部 度 家 電 力 裡 如 水 化 高 自 二 理 起 小 物 現 實 加 量 都 兩 體 制 機 當 使 點 從 業 本 去 把 性 好 應 開 它 合 還 因 由 其 些 然 前 外 天 政 四 日 那 社 義 事 平 形 相 全 表 間 樣 與 關 各 重 新 線 內 數 正 心 反 你 明 看 原 又 麼 利 比 或 但 質 氣 第 向 道 命 此 變 條 只 沒 結 解 問 意 建 月 公 無 系 軍 很 情 者 最 立 代 想 已 通 並 提 直 題 黨 程 展 五 果 料 象 員 革 位 入 常 文 總 次 品 式 活 設 及 管 特 件 長 求 老 頭 基 資 邊 流 路 級 少 圖 山 統 接 知 較 將 組 見 計 別 她 手 角 期 根 論 運 農 指 幾 九 區 強 放 決 西 被 幹 做 必 戰 先 回 則 任 取 據 處 隊 南 給 色 光 門 即 保 治 北 造 百 規 熱 領 七 海 口 東 導 器 壓 志 世 金 增 爭 濟 階 油 思 術 極 交 受 聯 什 認 六 共 權 收 證 改 清 美 再 採 轉 更 單 風 切 打 白 教 速 花 帶 安 場 身 車 例 真 務 具 萬 每 目 至 達 走 積 示 議 聲 報 鬥 完 類 八 離 華 名 確 才 科 張 信 馬 節 話 米 整 空 元 況 今 集 溫 傳 土 許 步 群 廣 石 記 需 段 研 界 拉 林 律 叫 且 究 觀 越 織 裝 影 算 低 持 音 眾 書 布 复 容 兒 須 際 商 非 驗 連 斷 深 難 近 礦 千 週 委 素 技 備 半 辦 青 省 列 習 響 約 支 般 史 感 勞 便 團 往 酸 歷 市 克 何 除 消 構 府 稱 太 準 精 值 號 率 族 維 劃 選 標 寫 存 候 毛 親 快 效 斯 院 查 江 型 眼 王 按 格 養 易 置 派 層 片 始 卻 專 狀 育 廠 京 識 適 屬 圓 包 火 住 調 滿 縣 局 照 參 紅 細 引 聽 該 鐵 價 嚴 首 底 液 官 德 隨 病 蘇 失 爾 死 講 配 女 黃 推 顯 談 罪 神 藝 呢 席 含 企 望 密 批 營 項 防 舉 球 英 氧 勢 告 李 台 落 木 幫 輪 破 亞 師 圍 注 遠 字 材 排 供 河 態 封 另 施 減 樹 溶 怎 止 案 言 士 均 武 固 葉 魚 波 視 僅 費 緊 愛 左 章 早 朝 害 續 輕 服 試 食 充 兵 源 判 護 司 足 某 練 差 致 板 田 降 黑 犯 負 擊 范 繼 興 似 餘 堅 曲 輸 修 故 城 夫 夠 送 筆 船 佔 右 財 吃 富 春 職 覺 漢 畫 功 巴 跟 雖 雜 飛 檢 吸 助 昇 陽 互 初 創 抗 考 投 壞 策 古 徑 換 未 跑 留 鋼 曾 端 責 站 簡 述 錢 副 盡 帝 射 草 衝 承 獨 令 限 阿 宣 環 雙 請 超 微 讓 控 州 良 軸 找 否 紀 益 依 優 頂 礎 載 倒 房 突 坐 粉 敵 略 客 袁 冷 勝 絕 析 塊 劑 測 絲 協 訴 念 陳 仍 羅 鹽 友 洋 錯 苦 夜 刑 移 頻 逐 靠 混 母 短 皮 終 聚 汽 村 雲 哪 既 距 衛 停 烈 央 察 燒 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 遊 久 菜 味 舊 模 湖 貨 損 預 阻 毫 普 穩 乙 媽 植 息 擴 銀 語 揮 酒 守 拿 序 紙 醫 缺 雨 嗎 針 劉 啊 急 唱 誤 訓 願 審 附 獲 茶 鮮 糧 斤 孩 脫 硫 肥 善 龍 演 父 漸 血 歡 械 掌 歌 沙 剛 攻 謂 盾 討 晚 粒 亂 燃 矛 乎 殺 藥 寧 魯 貴 鐘 煤 讀 班 伯 香 介 迫 句 豐 培 握 蘭 擔 弦 蛋 沉 假 穿 執 答 樂 誰 順 煙 縮 徵 臉 喜 松 腳 困 異 免 背 星 福 買 染 井 概 慢 怕 磁 倍 祖 皇 促 靜 補 評 翻 肉 踐 尼 衣 寬 揚 棉 希 傷 操 垂 秋 宜 氫 套 督 振 架 亮 末 憲 慶 編 牛 觸 映 雷 銷 詩 座 居 抓 裂 胞 呼 娘 景 威 綠 晶 厚 盟 衡 雞 孫 延 危 膠 屋 鄉 臨 陸 顧 掉 呀 燈 歲 措 束 耐 劇 玉 趙 跳 哥 季 課 凱 胡 額 款 紹 卷 齊 偉 蒸 殖 永 宗 苗 川 爐 岩 弱 零 楊 奏 沿 露 桿 探 滑 鎮 飯 濃 航 懷 趕 庫 奪 伊 靈 稅 途 滅 賽 歸 召 鼓 播 盤 裁 險 康 唯 錄 菌 純 借 糖 蓋 橫 符 私 努 堂 域 槍 潤 幅 哈 竟 熟 蟲 澤 腦 壤 碳 歐 遍 側 寨 敢 徹 慮 斜 薄 庭 納 彈 飼 伸 折 麥 濕 暗 荷 瓦 塞 床 築 惡 戶 訪 塔 奇 透 梁 刀 旋 跡 卡 氯 遇 份 毒 泥 退 洗 擺 灰 彩 賣 耗 夏 擇 忙 銅 獻 硬 予 繁 圈 雪 函 亦 抽 篇 陣 陰 丁 尺 追 堆 雄 迎 泛 爸 樓 避 謀 噸 野 豬 旗 累 偏 典 館 索 秦 脂 潮 爺 豆 忽 托 驚 塑 遺 愈 朱 替 纖 粗 傾 尚 痛 楚 謝 奮 購 磨 君 池 旁 碎 骨 監 捕 弟 暴 割 貫 殊 釋 詞 亡 壁 頓 寶 午 塵 聞 揭 炮 殘 冬 橋 婦 警 綜 招 吳 付 浮 遭 徐 您 搖 谷 贊 箱 隔 訂 男 吹 園 紛 唐 敗 宋 玻 巨 耕 坦 榮 閉 灣 鍵 凡 駐 鍋 救 恩 剝 凝 鹼 齒 截 煉 麻 紡 禁 廢 盛 版 緩 淨 睛 昌 婚 涉 筒 嘴 插 岸 朗 莊 街 藏 姑 貿 腐 奴 啦 慣 乘 夥 恢 勻 紗 扎 辯 耳 彪 臣 億 璃 抵 脈 秀 薩 俄 網 舞 店 噴 縱 寸 汗 掛 洪 賀 閃 柬 爆 烯 津 稻 牆 軟 勇 像 滾 厘 蒙 芳 肯 坡 柱 盪 腿 儀 旅 尾 軋 冰 貢 登 黎 削 鑽 勒 逃 障 氨 郭 峰 幣 港 伏 軌 畝 畢 擦 莫 刺 浪 秘 援 株 健 售 股 島 甘 泡 睡 童 鑄 湯 閥 休 匯 舍 牧 繞 炸 哲 磷 績 朋 淡 尖 啟 陷 柴 呈 徒 顏 淚 稍 忘 泵 藍 拖 洞 授 鏡 辛 壯 鋒 貧 虛 彎 摩 泰 幼 廷 尊 窗 綱 弄 隸 疑 氏 宮 姐 震 瑞 怪 尤 琴 循 描 膜 違 夾 腰 緣 珠 窮 森 枝 竹 溝 催 繩 憶 邦 剩 幸 漿 欄 擁 牙 貯 禮 濾 鈉 紋 罷 拍 咱 喊 袖 埃 勤 罰 焦 潛 伍 墨 欲 縫 姓 刊 飽 仿 獎 鋁 鬼 麗 跨 默 挖 鏈 掃 喝 袋 炭 污 幕 諸 弧 勵 梅 奶 潔 災 舟 鑑 苯 訟 抱 毀 懂 寒 智 埔 寄 屆 躍 渡 挑 丹 艱 貝 碰 拔 爹 戴 碼 夢 芽 熔 赤 漁 哭 敬 顆 奔 鉛 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 倉 魏 銳 曉 氮 兼 隱 礙 赫 撥 忠 肅 缸 牽 搶 博 巧 殼 兄 杜 訊 誠 碧 祥 柯 頁 巡 矩 悲 灌 齡 倫 票 尋 桂 鋪 聖 恐 恰 鄭 趣 抬 荒 騰 貼 柔 滴 猛 闊 輛 妻 填 撤 儲 簽 鬧 擾 紫 砂 遞 戲 吊 陶 伐 餵 療 瓶 婆 撫 臂 摸 忍 蝦 蠟 鄰 胸 鞏 擠 偶 棄 槽 勁 乳 鄧 吉 仁 爛 磚 租 烏 艦 伴 瓜 淺 丙 暫 燥 橡 柳 迷 暖 牌 秧 膽 詳 簧 踏 瓷 譜 呆 賓 糊 洛 輝 憤 競 隙 怒 粘 乃 緒 肩 籍 敏 塗 熙 皆 偵 懸 掘 享 糾 醒 狂 鎖 淀 恨 牲 霸 爬 賞 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鴨 趨 鳳 晨 畜 輩 秩 卵 署 梯 炎 灘 棋 驅 篩 峽 冒 啥 壽 譯 浸 泉 帽 遲 矽 疆 貸 漏 稿 冠 嫩 脅 芯 牢 叛 蝕 奧 鳴 嶺 羊 憑 串 塘 繪 酵 融 盆 錫 廟 籌 凍 輔 攝 襲 筋 拒 僚 旱 鉀 鳥 漆 沈 眉 疏 添 棒 穗 硝 韓 逼 扭 僑 涼 挺 碗 栽 炒 杯 患 餾 勸 豪 遼 勃 鴻 旦 吏 拜 狗 埋 輥 掩 飲 搬 罵 辭 勾 扣 估 蔣 絨 霧 丈 朵 姆 擬 宇 輯 陝 雕 償 蓄 崇 剪 倡 廳 咬 駛 薯 刷 斥 番 賦 奉 佛 澆 漫 曼 扇 鈣 桃 扶 仔 返 俗 虧 腔 鞋 棱 覆 框 悄 叔 撞 騙 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 脹 諧 拋 黴 桑 崗 嘛 衰 盜 滲 臟 賴 湧 甜 曹 閱 肌 哩 厲 烴 緯 毅 昨 偽 症 煮 嘆 釘 搭 莖 籠 酷 偷 弓 錐 恆 傑 坑 鼻 翼 綸 敘 獄 逮 罐 絡 棚 抑 膨 蔬 寺 驟 穆 冶 枯 冊 屍 凸 紳 坯 犧 焰 轟 欣 晉 瘦 禦 錠 錦 喪 旬 鍛 壟 搜 撲 邀 亭 酯 邁 舒 脆 酶 閒 憂 酚 頑 羽 漲 卸 仗 陪 闢 懲 杭 姚 肚 捉 飄 漂 昆 欺 吾 郎 烷 汁 呵 飾 蕭 雅 郵 遷 燕 撒 姻 赴 宴 煩 債 帳 斑 鈴 旨 醇 董 餅 雛 姿 拌 傅 腹 妥 揉 賢 拆 歪 葡 胺 丟 浩 徽 昂 墊 擋 覽 貪 慰 繳 汪 慌 馮 諾 姜 誼 兇 劣 誣 耀 昏 躺 盈 騎 喬 溪 叢 盧 抹 悶 諮 刮 駕 纜 悟 摘 鉺 擲 頗 幻 柄 惠 慘 佳 仇 臘 窩 滌 劍 瞧 堡 潑 蔥 罩 霍 撈 胎 蒼 濱 倆 捅 湘 砍 霞 邵 萄 瘋 淮 遂 熊 糞 烘 宿 檔 戈 駁 嫂 裕 徙 箭 捐 腸 撐 曬 辨 殿 蓮 攤 攪 醬 屏 疫 哀 蔡 堵 沫 皺 暢 疊 閣 萊 敲 轄 鉤 痕 壩 巷 餓 禍 丘 玄 溜 曰 邏 彭 嘗 卿 妨 艇 吞 韋 怨 矮 歇 ` ) ================================================ FILE: util/bip39/wordlists/czech.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/czech.txt // $ crc32 czech.txt // d1b5fda0 checksum := crc32.ChecksumIEEE([]byte(czech)) if fmt.Sprintf("%x", checksum) != "d1b5fda0" { panic("czech checksum invalid") } } // Czech is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/czech.txt var ( Czech = strings.Split(strings.TrimSpace(czech), "\n") czech = `abdikace abeceda adresa agrese akce aktovka alej alkohol amputace ananas andulka anekdota anketa antika anulovat archa arogance asfalt asistent aspirace astma astronom atlas atletika atol autobus azyl babka bachor bacil baculka badatel bageta bagr bahno bakterie balada baletka balkon balonek balvan balza bambus bankomat barbar baret barman baroko barva baterka batoh bavlna bazalka bazilika bazuka bedna beran beseda bestie beton bezinka bezmoc beztak bicykl bidlo biftek bikiny bilance biograf biolog bitva bizon blahobyt blatouch blecha bledule blesk blikat blizna blokovat bloudit blud bobek bobr bodlina bodnout bohatost bojkot bojovat bokorys bolest borec borovice bota boubel bouchat bouda boule bourat boxer bradavka brambora branka bratr brepta briketa brko brloh bronz broskev brunetka brusinka brzda brzy bublina bubnovat buchta buditel budka budova bufet bujarost bukvice buldok bulva bunda bunkr burza butik buvol buzola bydlet bylina bytovka bzukot capart carevna cedr cedule cejch cejn cela celer celkem celnice cenina cennost cenovka centrum cenzor cestopis cetka chalupa chapadlo charita chata chechtat chemie chichot chirurg chlad chleba chlubit chmel chmura chobot chochol chodba cholera chomout chopit choroba chov chrapot chrlit chrt chrup chtivost chudina chutnat chvat chvilka chvost chyba chystat chytit cibule cigareta cihelna cihla cinkot cirkus cisterna citace citrus cizinec cizost clona cokoliv couvat ctitel ctnost cudnost cuketa cukr cupot cvaknout cval cvik cvrkot cyklista daleko dareba datel datum dcera debata dechovka decibel deficit deflace dekl dekret demokrat deprese derby deska detektiv dikobraz diktovat dioda diplom disk displej divadlo divoch dlaha dlouho dluhopis dnes dobro dobytek docent dochutit dodnes dohled dohoda dohra dojem dojnice doklad dokola doktor dokument dolar doleva dolina doma dominant domluvit domov donutit dopad dopis doplnit doposud doprovod dopustit dorazit dorost dort dosah doslov dostatek dosud dosyta dotaz dotek dotknout doufat doutnat dovozce dozadu doznat dozorce drahota drak dramatik dravec draze drdol drobnost drogerie drozd drsnost drtit drzost duben duchovno dudek duha duhovka dusit dusno dutost dvojice dvorec dynamit ekolog ekonomie elektron elipsa email emise emoce empatie epizoda epocha epopej epos esej esence eskorta eskymo etiketa euforie evoluce exekuce exkurze expedice exploze export extrakt facka fajfka fakulta fanatik fantazie farmacie favorit fazole federace fejeton fenka fialka figurant filozof filtr finance finta fixace fjord flanel flirt flotila fond fosfor fotbal fotka foton frakce freska fronta fukar funkce fyzika galeje garant genetika geolog gilotina glazura glejt golem golfista gotika graf gramofon granule grep gril grog groteska guma hadice hadr hala halenka hanba hanopis harfa harpuna havran hebkost hejkal hejno hejtman hektar helma hematom herec herna heslo hezky historik hladovka hlasivky hlava hledat hlen hlodavec hloh hloupost hltat hlubina hluchota hmat hmota hmyz hnis hnojivo hnout hoblina hoboj hoch hodiny hodlat hodnota hodovat hojnost hokej holinka holka holub homole honitba honorace horal horda horizont horko horlivec hormon hornina horoskop horstvo hospoda hostina hotovost houba houf houpat houska hovor hradba hranice hravost hrazda hrbolek hrdina hrdlo hrdost hrnek hrobka hromada hrot hrouda hrozen hrstka hrubost hryzat hubenost hubnout hudba hukot humr husita hustota hvozd hybnost hydrant hygiena hymna hysterik idylka ihned ikona iluze imunita infekce inflace inkaso inovace inspekce internet invalida investor inzerce ironie jablko jachta jahoda jakmile jakost jalovec jantar jarmark jaro jasan jasno jatka javor jazyk jedinec jedle jednatel jehlan jekot jelen jelito jemnost jenom jepice jeseter jevit jezdec jezero jinak jindy jinoch jiskra jistota jitrnice jizva jmenovat jogurt jurta kabaret kabel kabinet kachna kadet kadidlo kahan kajak kajuta kakao kaktus kalamita kalhoty kalibr kalnost kamera kamkoliv kamna kanibal kanoe kantor kapalina kapela kapitola kapka kaple kapota kapr kapusta kapybara karamel karotka karton kasa katalog katedra kauce kauza kavalec kazajka kazeta kazivost kdekoliv kdesi kedluben kemp keramika kino klacek kladivo klam klapot klasika klaun klec klenba klepat klesnout klid klima klisna klobouk klokan klopa kloub klubovna klusat kluzkost kmen kmitat kmotr kniha knot koalice koberec kobka kobliha kobyla kocour kohout kojenec kokos koktejl kolaps koleda kolize kolo komando kometa komik komnata komora kompas komunita konat koncept kondice konec konfese kongres konina konkurs kontakt konzerva kopanec kopie kopnout koprovka korbel korektor kormidlo koroptev korpus koruna koryto korzet kosatec kostka kotel kotleta kotoul koukat koupelna kousek kouzlo kovboj koza kozoroh krabice krach krajina kralovat krasopis kravata kredit krejcar kresba kreveta kriket kritik krize krkavec krmelec krmivo krocan krok kronika kropit kroupa krovka krtek kruhadlo krupice krutost krvinka krychle krypta krystal kryt kudlanka kufr kujnost kukla kulajda kulich kulka kulomet kultura kuna kupodivu kurt kurzor kutil kvalita kvasinka kvestor kynolog kyselina kytara kytice kytka kytovec kyvadlo labrador lachtan ladnost laik lakomec lamela lampa lanovka lasice laso lastura latinka lavina lebka leckdy leden lednice ledovka ledvina legenda legie legrace lehce lehkost lehnout lektvar lenochod lentilka lepenka lepidlo letadlo letec letmo letokruh levhart levitace levobok libra lichotka lidojed lidskost lihovina lijavec lilek limetka linie linka linoleum listopad litina litovat lobista lodivod logika logoped lokalita loket lomcovat lopata lopuch lord losos lotr loudal louh louka louskat lovec lstivost lucerna lucifer lump lusk lustrace lvice lyra lyrika lysina madam madlo magistr mahagon majetek majitel majorita makak makovice makrela malba malina malovat malvice maminka mandle manko marnost masakr maskot masopust matice matrika maturita mazanec mazivo mazlit mazurka mdloba mechanik meditace medovina melasa meloun mentolka metla metoda metr mezera migrace mihnout mihule mikina mikrofon milenec milimetr milost mimika mincovna minibar minomet minulost miska mistr mixovat mladost mlha mlhovina mlok mlsat mluvit mnich mnohem mobil mocnost modelka modlitba mohyla mokro molekula momentka monarcha monokl monstrum montovat monzun mosaz moskyt most motivace motorka motyka moucha moudrost mozaika mozek mozol mramor mravenec mrkev mrtvola mrzet mrzutost mstitel mudrc muflon mulat mumie munice muset mutace muzeum muzikant myslivec mzda nabourat nachytat nadace nadbytek nadhoz nadobro nadpis nahlas nahnat nahodile nahradit naivita najednou najisto najmout naklonit nakonec nakrmit nalevo namazat namluvit nanometr naoko naopak naostro napadat napevno naplnit napnout naposled naprosto narodit naruby narychlo nasadit nasekat naslepo nastat natolik navenek navrch navzdory nazvat nebe nechat necky nedaleko nedbat neduh negace nehet nehoda nejen nejprve neklid nelibost nemilost nemoc neochota neonka nepokoj nerost nerv nesmysl nesoulad netvor neuron nevina nezvykle nicota nijak nikam nikdy nikl nikterak nitro nocleh nohavice nominace nora norek nositel nosnost nouze noviny novota nozdra nuda nudle nuget nutit nutnost nutrie nymfa obal obarvit obava obdiv obec obehnat obejmout obezita obhajoba obilnice objasnit objekt obklopit oblast oblek obliba obloha obluda obnos obohatit obojek obout obrazec obrna obruba obrys obsah obsluha obstarat obuv obvaz obvinit obvod obvykle obyvatel obzor ocas ocel ocenit ochladit ochota ochrana ocitnout odboj odbyt odchod odcizit odebrat odeslat odevzdat odezva odhadce odhodit odjet odjinud odkaz odkoupit odliv odluka odmlka odolnost odpad odpis odplout odpor odpustit odpykat odrazka odsoudit odstup odsun odtok odtud odvaha odveta odvolat odvracet odznak ofina ofsajd ohlas ohnisko ohrada ohrozit ohryzek okap okenice oklika okno okouzlit okovy okrasa okres okrsek okruh okupant okurka okusit olejnina olizovat omak omeleta omezit omladina omlouvat omluva omyl onehdy opakovat opasek operace opice opilost opisovat opora opozice opravdu oproti orbital orchestr orgie orlice orloj ortel osada oschnout osika osivo oslava oslepit oslnit oslovit osnova osoba osolit ospalec osten ostraha ostuda ostych osvojit oteplit otisk otop otrhat otrlost otrok otruby otvor ovanout ovar oves ovlivnit ovoce oxid ozdoba pachatel pacient padouch pahorek pakt palanda palec palivo paluba pamflet pamlsek panenka panika panna panovat panstvo pantofle paprika parketa parodie parta paruka paryba paseka pasivita pastelka patent patrona pavouk pazneht pazourek pecka pedagog pejsek peklo peloton penalta pendrek penze periskop pero pestrost petarda petice petrolej pevnina pexeso pianista piha pijavice pikle piknik pilina pilnost pilulka pinzeta pipeta pisatel pistole pitevna pivnice pivovar placenta plakat plamen planeta plastika platit plavidlo plaz plech plemeno plenta ples pletivo plevel plivat plnit plno plocha plodina plomba plout pluk plyn pobavit pobyt pochod pocit poctivec podat podcenit podepsat podhled podivit podklad podmanit podnik podoba podpora podraz podstata podvod podzim poezie pohanka pohnutka pohovor pohroma pohyb pointa pojistka pojmout pokazit pokles pokoj pokrok pokuta pokyn poledne polibek polknout poloha polynom pomalu pominout pomlka pomoc pomsta pomyslet ponechat ponorka ponurost popadat popel popisek poplach poprosit popsat popud poradce porce porod porucha poryv posadit posed posila poskok poslanec posoudit pospolu postava posudek posyp potah potkan potlesk potomek potrava potupa potvora poukaz pouto pouzdro povaha povidla povlak povoz povrch povstat povyk povzdech pozdrav pozemek poznatek pozor pozvat pracovat prahory praktika prales praotec praporek prase pravda princip prkno probudit procento prodej profese prohra projekt prolomit promile pronikat propad prorok prosba proton proutek provaz prskavka prsten prudkost prut prvek prvohory psanec psovod pstruh ptactvo puberta puch pudl pukavec puklina pukrle pult pumpa punc pupen pusa pusinka pustina putovat putyka pyramida pysk pytel racek rachot radiace radnice radon raft ragby raketa rakovina rameno rampouch rande rarach rarita rasovna rastr ratolest razance razidlo reagovat reakce recept redaktor referent reflex rejnok reklama rekord rekrut rektor reputace revize revma revolver rezerva riskovat riziko robotika rodokmen rohovka rokle rokoko romaneto ropovod ropucha rorejs rosol rostlina rotmistr rotoped rotunda roubenka roucho roup roura rovina rovnice rozbor rozchod rozdat rozeznat rozhodce rozinka rozjezd rozkaz rozloha rozmar rozpad rozruch rozsah roztok rozum rozvod rubrika ruchadlo rukavice rukopis ryba rybolov rychlost rydlo rypadlo rytina ryzost sadista sahat sako samec samizdat samota sanitka sardinka sasanka satelit sazba sazenice sbor schovat sebranka secese sedadlo sediment sedlo sehnat sejmout sekera sekta sekunda sekvoje semeno seno servis sesadit seshora seskok seslat sestra sesuv sesypat setba setina setkat setnout setrvat sever seznam shoda shrnout sifon silnice sirka sirotek sirup situace skafandr skalisko skanzen skaut skeptik skica skladba sklenice sklo skluz skoba skokan skoro skripta skrz skupina skvost skvrna slabika sladidlo slanina slast slavnost sledovat slepec sleva slezina slib slina sliznice slon sloupek slovo sluch sluha slunce slupka slza smaragd smetana smilstvo smlouva smog smrad smrk smrtka smutek smysl snad snaha snob sobota socha sodovka sokol sopka sotva souboj soucit soudce souhlas soulad soumrak souprava soused soutok souviset spalovna spasitel spis splav spodek spojenec spolu sponzor spornost spousta sprcha spustit sranda sraz srdce srna srnec srovnat srpen srst srub stanice starosta statika stavba stehno stezka stodola stolek stopa storno stoupat strach stres strhnout strom struna studna stupnice stvol styk subjekt subtropy suchar sudost sukno sundat sunout surikata surovina svah svalstvo svetr svatba svazek svisle svitek svoboda svodidlo svorka svrab sykavka sykot synek synovec sypat sypkost syrovost sysel sytost tabletka tabule tahoun tajemno tajfun tajga tajit tajnost taktika tamhle tampon tancovat tanec tanker tapeta tavenina tazatel technika tehdy tekutina telefon temnota tendence tenista tenor teplota tepna teprve terapie termoska textil ticho tiskopis titulek tkadlec tkanina tlapka tleskat tlukot tlupa tmel toaleta topinka topol torzo touha toulec tradice traktor tramp trasa traverza trefit trest trezor trhavina trhlina trochu trojice troska trouba trpce trpitel trpkost trubec truchlit truhlice trus trvat tudy tuhnout tuhost tundra turista turnaj tuzemsko tvaroh tvorba tvrdost tvrz tygr tykev ubohost uboze ubrat ubrousek ubrus ubytovna ucho uctivost udivit uhradit ujednat ujistit ujmout ukazatel uklidnit uklonit ukotvit ukrojit ulice ulita ulovit umyvadlo unavit uniforma uniknout upadnout uplatnit uplynout upoutat upravit uran urazit usednout usilovat usmrtit usnadnit usnout usoudit ustlat ustrnout utahovat utkat utlumit utonout utopenec utrousit uvalit uvolnit uvozovka uzdravit uzel uzenina uzlina uznat vagon valcha valoun vana vandal vanilka varan varhany varovat vcelku vchod vdova vedro vegetace vejce velbloud veletrh velitel velmoc velryba venkov veranda verze veselka veskrze vesnice vespodu vesta veterina veverka vibrace vichr videohra vidina vidle vila vinice viset vitalita vize vizitka vjezd vklad vkus vlajka vlak vlasec vlevo vlhkost vliv vlnovka vloupat vnucovat vnuk voda vodivost vodoznak vodstvo vojensky vojna vojsko volant volba volit volno voskovka vozidlo vozovna vpravo vrabec vracet vrah vrata vrba vrcholek vrhat vrstva vrtule vsadit vstoupit vstup vtip vybavit vybrat vychovat vydat vydra vyfotit vyhledat vyhnout vyhodit vyhradit vyhubit vyjasnit vyjet vyjmout vyklopit vykonat vylekat vymazat vymezit vymizet vymyslet vynechat vynikat vynutit vypadat vyplatit vypravit vypustit vyrazit vyrovnat vyrvat vyslovit vysoko vystavit vysunout vysypat vytasit vytesat vytratit vyvinout vyvolat vyvrhel vyzdobit vyznat vzadu vzbudit vzchopit vzdor vzduch vzdychat vzestup vzhledem vzkaz vzlykat vznik vzorek vzpoura vztah vztek xylofon zabrat zabydlet zachovat zadarmo zadusit zafoukat zahltit zahodit zahrada zahynout zajatec zajet zajistit zaklepat zakoupit zalepit zamezit zamotat zamyslet zanechat zanikat zaplatit zapojit zapsat zarazit zastavit zasunout zatajit zatemnit zatknout zaujmout zavalit zavelet zavinit zavolat zavrtat zazvonit zbavit zbrusu zbudovat zbytek zdaleka zdarma zdatnost zdivo zdobit zdroj zdvih zdymadlo zelenina zeman zemina zeptat zezadu zezdola zhatit zhltnout zhluboka zhotovit zhruba zima zimnice zjemnit zklamat zkoumat zkratka zkumavka zlato zlehka zloba zlom zlost zlozvyk zmapovat zmar zmatek zmije zmizet zmocnit zmodrat zmrzlina zmutovat znak znalost znamenat znovu zobrazit zotavit zoubek zoufale zplodit zpomalit zprava zprostit zprudka zprvu zrada zranit zrcadlo zrnitost zrno zrovna zrychlit zrzavost zticha ztratit zubovina zubr zvednout zvenku zvesela zvon zvrat zvukovod zvyk ` ) ================================================ FILE: util/bip39/wordlists/english.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/english.txt // $ crc32 english.txt // c1dbd296 checksum := crc32.ChecksumIEEE([]byte(english)) if fmt.Sprintf("%x", checksum) != "c1dbd296" { panic("english checksum invalid") } } // English is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/english.txt var ( English = strings.Split(strings.TrimSpace(english), "\n") english = `abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo ` ) ================================================ FILE: util/bip39/wordlists/french.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/french.txt // $ crc32 french.txt // 3e56b216 checksum := crc32.ChecksumIEEE([]byte(french)) if fmt.Sprintf("%x", checksum) != "3e56b216" { panic("french checksum invalid") } } // French is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/french.txt var ( French = strings.Split(strings.TrimSpace(french), "\n") french = `abaisser abandon abdiquer abeille abolir aborder aboutir aboyer abrasif abreuver abriter abroger abrupt absence absolu absurde abusif abyssal académie acajou acarien accabler accepter acclamer accolade accroche accuser acerbe achat acheter aciduler acier acompte acquérir acronyme acteur actif actuel adepte adéquat adhésif adjectif adjuger admettre admirer adopter adorer adoucir adresse adroit adulte adverbe aérer aéronef affaire affecter affiche affreux affubler agacer agencer agile agiter agrafer agréable agrume aider aiguille ailier aimable aisance ajouter ajuster alarmer alchimie alerte algèbre algue aliéner aliment alléger alliage allouer allumer alourdir alpaga altesse alvéole amateur ambigu ambre aménager amertume amidon amiral amorcer amour amovible amphibie ampleur amusant analyse anaphore anarchie anatomie ancien anéantir angle angoisse anguleux animal annexer annonce annuel anodin anomalie anonyme anormal antenne antidote anxieux apaiser apéritif aplanir apologie appareil appeler apporter appuyer aquarium aqueduc arbitre arbuste ardeur ardoise argent arlequin armature armement armoire armure arpenter arracher arriver arroser arsenic artériel article aspect asphalte aspirer assaut asservir assiette associer assurer asticot astre astuce atelier atome atrium atroce attaque attentif attirer attraper aubaine auberge audace audible augurer aurore automne autruche avaler avancer avarice avenir averse aveugle aviateur avide avion aviser avoine avouer avril axial axiome badge bafouer bagage baguette baignade balancer balcon baleine balisage bambin bancaire bandage banlieue bannière banquier barbier baril baron barque barrage bassin bastion bataille bateau batterie baudrier bavarder belette bélier belote bénéfice berceau berger berline bermuda besace besogne bétail beurre biberon bicycle bidule bijou bilan bilingue billard binaire biologie biopsie biotype biscuit bison bistouri bitume bizarre blafard blague blanchir blessant blinder blond bloquer blouson bobard bobine boire boiser bolide bonbon bondir bonheur bonifier bonus bordure borne botte boucle boueux bougie boulon bouquin bourse boussole boutique boxeur branche brasier brave brebis brèche breuvage bricoler brigade brillant brioche brique brochure broder bronzer brousse broyeur brume brusque brutal bruyant buffle buisson bulletin bureau burin bustier butiner butoir buvable buvette cabanon cabine cachette cadeau cadre caféine caillou caisson calculer calepin calibre calmer calomnie calvaire camarade caméra camion campagne canal caneton canon cantine canular capable caporal caprice capsule capter capuche carabine carbone caresser caribou carnage carotte carreau carton cascade casier casque cassure causer caution cavalier caverne caviar cédille ceinture céleste cellule cendrier censurer central cercle cérébral cerise cerner cerveau cesser chagrin chaise chaleur chambre chance chapitre charbon chasseur chaton chausson chavirer chemise chenille chéquier chercher cheval chien chiffre chignon chimère chiot chlorure chocolat choisir chose chouette chrome chute cigare cigogne cimenter cinéma cintrer circuler cirer cirque citerne citoyen citron civil clairon clameur claquer classe clavier client cligner climat clivage cloche clonage cloporte cobalt cobra cocasse cocotier coder codifier coffre cogner cohésion coiffer coincer colère colibri colline colmater colonel combat comédie commande compact concert conduire confier congeler connoter consonne contact convexe copain copie corail corbeau cordage corniche corpus correct cortège cosmique costume coton coude coupure courage couteau couvrir coyote crabe crainte cravate crayon créature créditer crémeux creuser crevette cribler crier cristal critère croire croquer crotale crucial cruel crypter cubique cueillir cuillère cuisine cuivre culminer cultiver cumuler cupide curatif curseur cyanure cycle cylindre cynique daigner damier danger danseur dauphin débattre débiter déborder débrider débutant décaler décembre déchirer décider déclarer décorer décrire décupler dédale déductif déesse défensif défiler défrayer dégager dégivrer déglutir dégrafer déjeuner délice déloger demander demeurer démolir dénicher dénouer dentelle dénuder départ dépenser déphaser déplacer déposer déranger dérober désastre descente désert désigner désobéir dessiner destrier détacher détester détourer détresse devancer devenir deviner devoir diable dialogue diamant dicter différer digérer digital digne diluer dimanche diminuer dioxyde directif diriger discuter disposer dissiper distance divertir diviser docile docteur dogme doigt domaine domicile dompter donateur donjon donner dopamine dortoir dorure dosage doseur dossier dotation douanier double douceur douter doyen dragon draper dresser dribbler droiture duperie duplexe durable durcir dynastie éblouir écarter écharpe échelle éclairer éclipse éclore écluse école économie écorce écouter écraser écrémer écrivain écrou écume écureuil édifier éduquer effacer effectif effigie effort effrayer effusion égaliser égarer éjecter élaborer élargir électron élégant éléphant élève éligible élitisme éloge élucider éluder emballer embellir embryon émeraude émission emmener émotion émouvoir empereur employer emporter emprise émulsion encadrer enchère enclave encoche endiguer endosser endroit enduire énergie enfance enfermer enfouir engager engin englober énigme enjamber enjeu enlever ennemi ennuyeux enrichir enrobage enseigne entasser entendre entier entourer entraver énumérer envahir enviable envoyer enzyme éolien épaissir épargne épatant épaule épicerie épidémie épier épilogue épine épisode épitaphe époque épreuve éprouver épuisant équerre équipe ériger érosion erreur éruption escalier espadon espèce espiègle espoir esprit esquiver essayer essence essieu essorer estime estomac estrade étagère étaler étanche étatique éteindre étendoir éternel éthanol éthique ethnie étirer étoffer étoile étonnant étourdir étrange étroit étude euphorie évaluer évasion éventail évidence éviter évolutif évoquer exact exagérer exaucer exceller excitant exclusif excuse exécuter exemple exercer exhaler exhorter exigence exiler exister exotique expédier explorer exposer exprimer exquis extensif extraire exulter fable fabuleux facette facile facture faiblir falaise fameux famille farceur farfelu farine farouche fasciner fatal fatigue faucon fautif faveur favori fébrile féconder fédérer félin femme fémur fendoir féodal fermer féroce ferveur festival feuille feutre février fiasco ficeler fictif fidèle figure filature filetage filière filleul filmer filou filtrer financer finir fiole firme fissure fixer flairer flamme flasque flatteur fléau flèche fleur flexion flocon flore fluctuer fluide fluvial folie fonderie fongible fontaine forcer forgeron formuler fortune fossile foudre fougère fouiller foulure fourmi fragile fraise franchir frapper frayeur frégate freiner frelon frémir frénésie frère friable friction frisson frivole froid fromage frontal frotter fruit fugitif fuite fureur furieux furtif fusion futur gagner galaxie galerie gambader garantir gardien garnir garrigue gazelle gazon géant gélatine gélule gendarme général génie genou gentil géologie géomètre géranium germe gestuel geyser gibier gicler girafe givre glace glaive glisser globe gloire glorieux golfeur gomme gonfler gorge gorille goudron gouffre goulot goupille gourmand goutte graduel graffiti graine grand grappin gratuit gravir grenat griffure griller grimper grogner gronder grotte groupe gruger grutier gruyère guépard guerrier guide guimauve guitare gustatif gymnaste gyrostat habitude hachoir halte hameau hangar hanneton haricot harmonie harpon hasard hélium hématome herbe hérisson hermine héron hésiter heureux hiberner hibou hilarant histoire hiver homard hommage homogène honneur honorer honteux horde horizon horloge hormone horrible houleux housse hublot huileux humain humble humide humour hurler hydromel hygiène hymne hypnose idylle ignorer iguane illicite illusion image imbiber imiter immense immobile immuable impact impérial implorer imposer imprimer imputer incarner incendie incident incliner incolore indexer indice inductif inédit ineptie inexact infini infliger informer infusion ingérer inhaler inhiber injecter injure innocent inoculer inonder inscrire insecte insigne insolite inspirer instinct insulter intact intense intime intrigue intuitif inutile invasion inventer inviter invoquer ironique irradier irréel irriter isoler ivoire ivresse jaguar jaillir jambe janvier jardin jauger jaune javelot jetable jeton jeudi jeunesse joindre joncher jongler joueur jouissif journal jovial joyau joyeux jubiler jugement junior jupon juriste justice juteux juvénile kayak kimono kiosque label labial labourer lacérer lactose lagune laine laisser laitier lambeau lamelle lampe lanceur langage lanterne lapin largeur larme laurier lavabo lavoir lecture légal léger légume lessive lettre levier lexique lézard liasse libérer libre licence licorne liège lièvre ligature ligoter ligue limer limite limonade limpide linéaire lingot lionceau liquide lisière lister lithium litige littoral livreur logique lointain loisir lombric loterie louer lourd loutre louve loyal lubie lucide lucratif lueur lugubre luisant lumière lunaire lundi luron lutter luxueux machine magasin magenta magique maigre maillon maintien mairie maison majorer malaxer maléfice malheur malice mallette mammouth mandater maniable manquant manteau manuel marathon marbre marchand mardi maritime marqueur marron marteler mascotte massif matériel matière matraque maudire maussade mauve maximal méchant méconnu médaille médecin méditer méduse meilleur mélange mélodie membre mémoire menacer mener menhir mensonge mentor mercredi mérite merle messager mesure métal météore méthode métier meuble miauler microbe miette mignon migrer milieu million mimique mince minéral minimal minorer minute miracle miroiter missile mixte mobile moderne moelleux mondial moniteur monnaie monotone monstre montagne monument moqueur morceau morsure mortier moteur motif mouche moufle moulin mousson mouton mouvant multiple munition muraille murène murmure muscle muséum musicien mutation muter mutuel myriade myrtille mystère mythique nageur nappe narquois narrer natation nation nature naufrage nautique navire nébuleux nectar néfaste négation négliger négocier neige nerveux nettoyer neurone neutron neveu niche nickel nitrate niveau noble nocif nocturne noirceur noisette nomade nombreux nommer normatif notable notifier notoire nourrir nouveau novateur novembre novice nuage nuancer nuire nuisible numéro nuptial nuque nutritif obéir objectif obliger obscur observer obstacle obtenir obturer occasion occuper océan octobre octroyer octupler oculaire odeur odorant offenser officier offrir ogive oiseau oisillon olfactif olivier ombrage omettre onctueux onduler onéreux onirique opale opaque opérer opinion opportun opprimer opter optique orageux orange orbite ordonner oreille organe orgueil orifice ornement orque ortie osciller osmose ossature otarie ouragan ourson outil outrager ouvrage ovation oxyde oxygène ozone paisible palace palmarès palourde palper panache panda pangolin paniquer panneau panorama pantalon papaye papier papoter papyrus paradoxe parcelle paresse parfumer parler parole parrain parsemer partager parure parvenir passion pastèque paternel patience patron pavillon pavoiser payer paysage peigne peintre pelage pélican pelle pelouse peluche pendule pénétrer pénible pensif pénurie pépite péplum perdrix perforer période permuter perplexe persil perte peser pétale petit pétrir peuple pharaon phobie phoque photon phrase physique piano pictural pièce pierre pieuvre pilote pinceau pipette piquer pirogue piscine piston pivoter pixel pizza placard plafond plaisir planer plaque plastron plateau pleurer plexus pliage plomb plonger pluie plumage pochette poésie poète pointe poirier poisson poivre polaire policier pollen polygone pommade pompier ponctuel pondérer poney portique position posséder posture potager poteau potion pouce poulain poumon pourpre poussin pouvoir prairie pratique précieux prédire préfixe prélude prénom présence prétexte prévoir primitif prince prison priver problème procéder prodige profond progrès proie projeter prologue promener propre prospère protéger prouesse proverbe prudence pruneau psychose public puceron puiser pulpe pulsar punaise punitif pupitre purifier puzzle pyramide quasar querelle question quiétude quitter quotient racine raconter radieux ragondin raideur raisin ralentir rallonge ramasser rapide rasage ratisser ravager ravin rayonner réactif réagir réaliser réanimer recevoir réciter réclamer récolter recruter reculer recycler rédiger redouter refaire réflexe réformer refrain refuge régalien région réglage régulier réitérer rejeter rejouer relatif relever relief remarque remède remise remonter remplir remuer renard renfort renifler renoncer rentrer renvoi replier reporter reprise reptile requin réserve résineux résoudre respect rester résultat rétablir retenir réticule retomber retracer réunion réussir revanche revivre révolte révulsif richesse rideau rieur rigide rigoler rincer riposter risible risque rituel rival rivière rocheux romance rompre ronce rondin roseau rosier rotatif rotor rotule rouge rouille rouleau routine royaume ruban rubis ruche ruelle rugueux ruiner ruisseau ruser rustique rythme sabler saboter sabre sacoche safari sagesse saisir salade salive salon saluer samedi sanction sanglier sarcasme sardine saturer saugrenu saumon sauter sauvage savant savonner scalpel scandale scélérat scénario sceptre schéma science scinder score scrutin sculpter séance sécable sécher secouer sécréter sédatif séduire seigneur séjour sélectif semaine sembler semence séminal sénateur sensible sentence séparer séquence serein sergent sérieux serrure sérum service sésame sévir sevrage sextuple sidéral siècle siéger siffler sigle signal silence silicium simple sincère sinistre siphon sirop sismique situer skier social socle sodium soigneux soldat soleil solitude soluble sombre sommeil somnoler sonde songeur sonnette sonore sorcier sortir sosie sottise soucieux soudure souffle soulever soupape source soutirer souvenir spacieux spatial spécial sphère spiral stable station sternum stimulus stipuler strict studieux stupeur styliste sublime substrat subtil subvenir succès sucre suffixe suggérer suiveur sulfate superbe supplier surface suricate surmener surprise sursaut survie suspect syllabe symbole symétrie synapse syntaxe système tabac tablier tactile tailler talent talisman talonner tambour tamiser tangible tapis taquiner tarder tarif tartine tasse tatami tatouage taupe taureau taxer témoin temporel tenaille tendre teneur tenir tension terminer terne terrible tétine texte thème théorie thérapie thorax tibia tiède timide tirelire tiroir tissu titane titre tituber toboggan tolérant tomate tonique tonneau toponyme torche tordre tornade torpille torrent torse tortue totem toucher tournage tousser toxine traction trafic tragique trahir train trancher travail trèfle tremper trésor treuil triage tribunal tricoter trilogie triomphe tripler triturer trivial trombone tronc tropical troupeau tuile tulipe tumulte tunnel turbine tuteur tutoyer tuyau tympan typhon typique tyran ubuesque ultime ultrason unanime unifier union unique unitaire univers uranium urbain urticant usage usine usuel usure utile utopie vacarme vaccin vagabond vague vaillant vaincre vaisseau valable valise vallon valve vampire vanille vapeur varier vaseux vassal vaste vecteur vedette végétal véhicule veinard véloce vendredi vénérer venger venimeux ventouse verdure vérin vernir verrou verser vertu veston vétéran vétuste vexant vexer viaduc viande victoire vidange vidéo vignette vigueur vilain village vinaigre violon vipère virement virtuose virus visage viseur vision visqueux visuel vital vitesse viticole vitrine vivace vivipare vocation voguer voile voisin voiture volaille volcan voltiger volume vorace vortex voter vouloir voyage voyelle wagon xénon yacht zèbre zénith zeste zoologie ` ) ================================================ FILE: util/bip39/wordlists/italian.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/italian.txt // $ crc32 italian.txt // 2fc7d07e checksum := crc32.ChecksumIEEE([]byte(italian)) if fmt.Sprintf("%x", checksum) != "2fc7d07e" { panic("italian checksum invalid") } } // Italian is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/italian.txt var ( Italian = strings.Split(strings.TrimSpace(italian), "\n") italian = `abaco abbaglio abbinato abete abisso abolire abrasivo abrogato accadere accenno accusato acetone achille acido acqua acre acrilico acrobata acuto adagio addebito addome adeguato aderire adipe adottare adulare affabile affetto affisso affranto aforisma afoso africano agave agente agevole aggancio agire agitare agonismo agricolo agrumeto aguzzo alabarda alato albatro alberato albo albume alce alcolico alettone alfa algebra aliante alibi alimento allagato allegro allievo allodola allusivo almeno alogeno alpaca alpestre altalena alterno alticcio altrove alunno alveolo alzare amalgama amanita amarena ambito ambrato ameba america ametista amico ammasso ammenda ammirare ammonito amore ampio ampliare amuleto anacardo anagrafe analista anarchia anatra anca ancella ancora andare andrea anello angelo angolare angusto anima annegare annidato anno annuncio anonimo anticipo anzi apatico apertura apode apparire appetito appoggio approdo appunto aprile arabica arachide aragosta araldica arancio aratura arazzo arbitro archivio ardito arenile argento argine arguto aria armonia arnese arredato arringa arrosto arsenico arso artefice arzillo asciutto ascolto asepsi asettico asfalto asino asola aspirato aspro assaggio asse assoluto assurdo asta astenuto astice astratto atavico ateismo atomico atono attesa attivare attorno attrito attuale ausilio austria autista autonomo autunno avanzato avere avvenire avviso avvolgere azione azoto azzimo azzurro babele baccano bacino baco badessa badilata bagnato baita balcone baldo balena ballata balzano bambino bandire baraonda barbaro barca baritono barlume barocco basilico basso batosta battuto baule bava bavosa becco beffa belgio belva benda benevole benigno benzina bere berlina beta bibita bici bidone bifido biga bilancia bimbo binocolo biologo bipede bipolare birbante birra biscotto bisesto bisnonno bisonte bisturi bizzarro blando blatta bollito bonifico bordo bosco botanico bottino bozzolo braccio bradipo brama branca bravura bretella brevetto brezza briglia brillante brindare broccolo brodo bronzina brullo bruno bubbone buca budino buffone buio bulbo buono burlone burrasca bussola busta cadetto caduco calamaro calcolo calesse calibro calmo caloria cambusa camerata camicia cammino camola campale canapa candela cane canino canotto cantina capace capello capitolo capogiro cappero capra capsula carapace carcassa cardo carisma carovana carretto cartolina casaccio cascata caserma caso cassone castello casuale catasta catena catrame cauto cavillo cedibile cedrata cefalo celebre cellulare cena cenone centesimo ceramica cercare certo cerume cervello cesoia cespo ceto chela chiaro chicca chiedere chimera china chirurgo chitarra ciao ciclismo cifrare cigno cilindro ciottolo circa cirrosi citrico cittadino ciuffo civetta civile classico clinica cloro cocco codardo codice coerente cognome collare colmato colore colposo coltivato colza coma cometa commando comodo computer comune conciso condurre conferma congelare coniuge connesso conoscere consumo continuo convegno coperto copione coppia copricapo corazza cordata coricato cornice corolla corpo corredo corsia cortese cosmico costante cottura covato cratere cravatta creato credere cremoso crescita creta criceto crinale crisi critico croce cronaca crostata cruciale crusca cucire cuculo cugino cullato cupola curatore cursore curvo cuscino custode dado daino dalmata damerino daniela dannoso danzare datato davanti davvero debutto decennio deciso declino decollo decreto dedicato definito deforme degno delegare delfino delirio delta demenza denotato dentro deposito derapata derivare deroga descritto deserto desiderio desumere detersivo devoto diametro dicembre diedro difeso diffuso digerire digitale diluvio dinamico dinnanzi dipinto diploma dipolo diradare dire dirotto dirupo disagio discreto disfare disgelo disposto distanza disumano dito divano divelto dividere divorato doblone docente doganale dogma dolce domato domenica dominare dondolo dono dormire dote dottore dovuto dozzina drago druido dubbio dubitare ducale duna duomo duplice duraturo ebano eccesso ecco eclissi economia edera edicola edile editoria educare egemonia egli egoismo egregio elaborato elargire elegante elencato eletto elevare elfico elica elmo elsa eluso emanato emblema emesso emiro emotivo emozione empirico emulo endemico enduro energia enfasi enoteca entrare enzima epatite epilogo episodio epocale eppure equatore erario erba erboso erede eremita erigere ermetico eroe erosivo errante esagono esame esanime esaudire esca esempio esercito esibito esigente esistere esito esofago esortato esoso espanso espresso essenza esso esteso estimare estonia estroso esultare etilico etnico etrusco etto euclideo europa evaso evidenza evitato evoluto evviva fabbrica faccenda fachiro falco famiglia fanale fanfara fango fantasma fare farfalla farinoso farmaco fascia fastoso fasullo faticare fato favoloso febbre fecola fede fegato felpa feltro femmina fendere fenomeno fermento ferro fertile fessura festivo fetta feudo fiaba fiducia fifa figurato filo finanza finestra finire fiore fiscale fisico fiume flacone flamenco flebo flemma florido fluente fluoro fobico focaccia focoso foderato foglio folata folclore folgore fondente fonetico fonia fontana forbito forchetta foresta formica fornaio foro fortezza forzare fosfato fosso fracasso frana frassino fratello freccetta frenata fresco frigo frollino fronde frugale frutta fucilata fucsia fuggente fulmine fulvo fumante fumetto fumoso fune funzione fuoco furbo furgone furore fuso futile gabbiano gaffe galateo gallina galoppo gambero gamma garanzia garbo garofano garzone gasdotto gasolio gastrico gatto gaudio gazebo gazzella geco gelatina gelso gemello gemmato gene genitore gennaio genotipo gergo ghepardo ghiaccio ghisa giallo gilda ginepro giocare gioiello giorno giove girato girone gittata giudizio giurato giusto globulo glutine gnomo gobba golf gomito gommone gonfio gonna governo gracile grado grafico grammo grande grattare gravoso grazia greca gregge grifone grigio grinza grotta gruppo guadagno guaio guanto guardare gufo guidare ibernato icona identico idillio idolo idra idrico idrogeno igiene ignaro ignorato ilare illeso illogico illudere imballo imbevuto imbocco imbuto immane immerso immolato impacco impeto impiego importo impronta inalare inarcare inattivo incanto incendio inchino incisivo incluso incontro incrocio incubo indagine india indole inedito infatti infilare inflitto ingaggio ingegno inglese ingordo ingrosso innesco inodore inoltrare inondato insano insetto insieme insonnia insulina intasato intero intonaco intuito inumidire invalido invece invito iperbole ipnotico ipotesi ippica iride irlanda ironico irrigato irrorare isolato isotopo isterico istituto istrice italia iterare labbro labirinto lacca lacerato lacrima lacuna laddove lago lampo lancetta lanterna lardoso larga laringe lastra latenza latino lattuga lavagna lavoro legale leggero lembo lentezza lenza leone lepre lesivo lessato lesto letterale leva levigato libero lido lievito lilla limatura limitare limpido lineare lingua liquido lira lirica lisca lite litigio livrea locanda lode logica lombare londra longevo loquace lorenzo loto lotteria luce lucidato lumaca luminoso lungo lupo luppolo lusinga lusso lutto macabro macchina macero macinato madama magico maglia magnete magro maiolica malafede malgrado malinteso malsano malto malumore mana mancia mandorla mangiare manifesto mannaro manovra mansarda mantide manubrio mappa maratona marcire maretta marmo marsupio maschera massaia mastino materasso matricola mattone maturo mazurca meandro meccanico mecenate medesimo meditare mega melassa melis melodia meninge meno mensola mercurio merenda merlo meschino mese messere mestolo metallo metodo mettere miagolare mica micelio michele microbo midollo miele migliore milano milite mimosa minerale mini minore mirino mirtillo miscela missiva misto misurare mitezza mitigare mitra mittente mnemonico modello modifica modulo mogano mogio mole molosso monastero monco mondina monetario monile monotono monsone montato monviso mora mordere morsicato mostro motivato motosega motto movenza movimento mozzo mucca mucosa muffa mughetto mugnaio mulatto mulinello multiplo mummia munto muovere murale musa muscolo musica mutevole muto nababbo nafta nanometro narciso narice narrato nascere nastrare naturale nautica naviglio nebulosa necrosi negativo negozio nemmeno neofita neretto nervo nessuno nettuno neutrale neve nevrotico nicchia ninfa nitido nobile nocivo nodo nome nomina nordico normale norvegese nostrano notare notizia notturno novella nucleo nulla numero nuovo nutrire nuvola nuziale oasi obbedire obbligo obelisco oblio obolo obsoleto occasione occhio occidente occorrere occultare ocra oculato odierno odorare offerta offrire offuscato oggetto oggi ognuno olandese olfatto oliato oliva ologramma oltre omaggio ombelico ombra omega omissione ondoso onere onice onnivoro onorevole onta operato opinione opposto oracolo orafo ordine orecchino orefice orfano organico origine orizzonte orma ormeggio ornativo orologio orrendo orribile ortensia ortica orzata orzo osare oscurare osmosi ospedale ospite ossa ossidare ostacolo oste otite otre ottagono ottimo ottobre ovale ovest ovino oviparo ovocito ovunque ovviare ozio pacchetto pace pacifico padella padrone paese paga pagina palazzina palesare pallido palo palude pandoro pannello paolo paonazzo paprica parabola parcella parere pargolo pari parlato parola partire parvenza parziale passivo pasticca patacca patologia pattume pavone peccato pedalare pedonale peggio peloso penare pendice penisola pennuto penombra pensare pentola pepe pepita perbene percorso perdonato perforare pergamena periodo permesso perno perplesso persuaso pertugio pervaso pesatore pesista peso pestifero petalo pettine petulante pezzo piacere pianta piattino piccino picozza piega pietra piffero pigiama pigolio pigro pila pilifero pillola pilota pimpante pineta pinna pinolo pioggia piombo piramide piretico pirite pirolisi pitone pizzico placebo planare plasma platano plenario pochezza poderoso podismo poesia poggiare polenta poligono pollice polmonite polpetta polso poltrona polvere pomice pomodoro ponte popoloso porfido poroso porpora porre portata posa positivo possesso postulato potassio potere pranzo prassi pratica precluso predica prefisso pregiato prelievo premere prenotare preparato presenza pretesto prevalso prima principe privato problema procura produrre profumo progetto prolunga promessa pronome proposta proroga proteso prova prudente prugna prurito psiche pubblico pudica pugilato pugno pulce pulito pulsante puntare pupazzo pupilla puro quadro qualcosa quasi querela quota raccolto raddoppio radicale radunato raffica ragazzo ragione ragno ramarro ramingo ramo randagio rantolare rapato rapina rappreso rasatura raschiato rasente rassegna rastrello rata ravveduto reale recepire recinto recluta recondito recupero reddito redimere regalato registro regola regresso relazione remare remoto renna replica reprimere reputare resa residente responso restauro rete retina retorica rettifica revocato riassunto ribadire ribelle ribrezzo ricarica ricco ricevere riciclato ricordo ricreduto ridicolo ridurre rifasare riflesso riforma rifugio rigare rigettato righello rilassato rilevato rimanere rimbalzo rimedio rimorchio rinascita rincaro rinforzo rinnovo rinomato rinsavito rintocco rinuncia rinvenire riparato ripetuto ripieno riportare ripresa ripulire risata rischio riserva risibile riso rispetto ristoro risultato risvolto ritardo ritegno ritmico ritrovo riunione riva riverso rivincita rivolto rizoma roba robotico robusto roccia roco rodaggio rodere roditore rogito rollio romantico rompere ronzio rosolare rospo rotante rotondo rotula rovescio rubizzo rubrica ruga rullino rumine rumoroso ruolo rupe russare rustico sabato sabbiare sabotato sagoma salasso saldatura salgemma salivare salmone salone saltare saluto salvo sapere sapido saporito saraceno sarcasmo sarto sassoso satellite satira satollo saturno savana savio saziato sbadiglio sbalzo sbancato sbarra sbattere sbavare sbendare sbirciare sbloccato sbocciato sbrinare sbruffone sbuffare scabroso scadenza scala scambiare scandalo scapola scarso scatenare scavato scelto scenico scettro scheda schiena sciarpa scienza scindere scippo sciroppo scivolo sclerare scodella scolpito scomparto sconforto scoprire scorta scossone scozzese scriba scrollare scrutinio scuderia scultore scuola scuro scusare sdebitare sdoganare seccatura secondo sedano seggiola segnalato segregato seguito selciato selettivo sella selvaggio semaforo sembrare seme seminato sempre senso sentire sepolto sequenza serata serbato sereno serio serpente serraglio servire sestina setola settimana sfacelo sfaldare sfamato sfarzoso sfaticato sfera sfida sfilato sfinge sfocato sfoderare sfogo sfoltire sforzato sfratto sfruttato sfuggito sfumare sfuso sgabello sgarbato sgonfiare sgorbio sgrassato sguardo sibilo siccome sierra sigla signore silenzio sillaba simbolo simpatico simulato sinfonia singolo sinistro sino sintesi sinusoide sipario sisma sistole situato slitta slogatura sloveno smarrito smemorato smentito smeraldo smilzo smontare smottato smussato snellire snervato snodo sobbalzo sobrio soccorso sociale sodale soffitto sogno soldato solenne solido sollazzo solo solubile solvente somatico somma sonda sonetto sonnifero sopire soppeso sopra sorgere sorpasso sorriso sorso sorteggio sorvolato sospiro sosta sottile spada spalla spargere spatola spavento spazzola specie spedire spegnere spelatura speranza spessore spettrale spezzato spia spigoloso spillato spinoso spirale splendido sportivo sposo spranga sprecare spronato spruzzo spuntino squillo sradicare srotolato stabile stacco staffa stagnare stampato stantio starnuto stasera statuto stelo steppa sterzo stiletto stima stirpe stivale stizzoso stonato storico strappo stregato stridulo strozzare strutto stuccare stufo stupendo subentro succoso sudore suggerito sugo sultano suonare superbo supporto surgelato surrogato sussurro sutura svagare svedese sveglio svelare svenuto svezia sviluppo svista svizzera svolta svuotare tabacco tabulato tacciare taciturno tale talismano tampone tannino tara tardivo targato tariffa tarpare tartaruga tasto tattico taverna tavolata tazza teca tecnico telefono temerario tempo temuto tendone tenero tensione tentacolo teorema terme terrazzo terzetto tesi tesserato testato tetro tettoia tifare tigella timbro tinto tipico tipografo tiraggio tiro titanio titolo titubante tizio tizzone toccare tollerare tolto tombola tomo tonfo tonsilla topazio topologia toppa torba tornare torrone tortora toscano tossire tostatura totano trabocco trachea trafila tragedia tralcio tramonto transito trapano trarre trasloco trattato trave treccia tremolio trespolo tributo tricheco trifoglio trillo trincea trio tristezza triturato trivella tromba trono troppo trottola trovare truccato tubatura tuffato tulipano tumulto tunisia turbare turchino tuta tutela ubicato uccello uccisore udire uditivo uffa ufficio uguale ulisse ultimato umano umile umorismo uncinetto ungere ungherese unicorno unificato unisono unitario unte uovo upupa uragano urgenza urlo usanza usato uscito usignolo usuraio utensile utilizzo utopia vacante vaccinato vagabondo vagliato valanga valgo valico valletta valoroso valutare valvola vampata vangare vanitoso vano vantaggio vanvera vapore varano varcato variante vasca vedetta vedova veduto vegetale veicolo velcro velina velluto veloce venato vendemmia vento verace verbale vergogna verifica vero verruca verticale vescica vessillo vestale veterano vetrina vetusto viandante vibrante vicenda vichingo vicinanza vidimare vigilia vigneto vigore vile villano vimini vincitore viola vipera virgola virologo virulento viscoso visione vispo vissuto visura vita vitello vittima vivanda vivido viziare voce voga volatile volere volpe voragine vulcano zampogna zanna zappato zattera zavorra zefiro zelante zelo zenzero zerbino zibetto zinco zircone zitto zolla zotico zucchero zufolo zulu zuppa ` ) ================================================ FILE: util/bip39/wordlists/japanese.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/japanese.txt // $ crc32 japanese.txt // 0acc1419 checksum := crc32.ChecksumIEEE([]byte(japanese)) if fmt.Sprintf("%x", checksum) != "acc1419" { panic(fmt.Sprintf("japanese checksum invalid: %x", checksum)) } } // Japanese is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/japanese.txt var ( Japanese = strings.Split(strings.TrimSpace(japanese), "\n") japanese = `あいこくしん あいさつ あいだ あおぞら あかちゃん あきる あけがた あける あこがれる あさい あさひ あしあと あじわう あずかる あずき あそぶ あたえる あたためる あたりまえ あたる あつい あつかう あっしゅく あつまり あつめる あてな あてはまる あひる あぶら あぶる あふれる あまい あまど あまやかす あまり あみもの あめりか あやまる あゆむ あらいぐま あらし あらすじ あらためる あらゆる あらわす ありがとう あわせる あわてる あんい あんがい あんこ あんぜん あんてい あんない あんまり いいだす いおん いがい いがく いきおい いきなり いきもの いきる いくじ いくぶん いけばな いけん いこう いこく いこつ いさましい いさん いしき いじゅう いじょう いじわる いずみ いずれ いせい いせえび いせかい いせき いぜん いそうろう いそがしい いだい いだく いたずら いたみ いたりあ いちおう いちじ いちど いちば いちぶ いちりゅう いつか いっしゅん いっせい いっそう いったん いっち いってい いっぽう いてざ いてん いどう いとこ いない いなか いねむり いのち いのる いはつ いばる いはん いびき いひん いふく いへん いほう いみん いもうと いもたれ いもり いやがる いやす いよかん いよく いらい いらすと いりぐち いりょう いれい いれもの いれる いろえんぴつ いわい いわう いわかん いわば いわゆる いんげんまめ いんさつ いんしょう いんよう うえき うえる うおざ うがい うかぶ うかべる うきわ うくらいな うくれれ うけたまわる うけつけ うけとる うけもつ うける うごかす うごく うこん うさぎ うしなう うしろがみ うすい うすぎ うすぐらい うすめる うせつ うちあわせ うちがわ うちき うちゅう うっかり うつくしい うったえる うつる うどん うなぎ うなじ うなずく うなる うねる うのう うぶげ うぶごえ うまれる うめる うもう うやまう うよく うらがえす うらぐち うらない うりあげ うりきれ うるさい うれしい うれゆき うれる うろこ うわき うわさ うんこう うんちん うんてん うんどう えいえん えいが えいきょう えいご えいせい えいぶん えいよう えいわ えおり えがお えがく えきたい えくせる えしゃく えすて えつらん えのぐ えほうまき えほん えまき えもじ えもの えらい えらぶ えりあ えんえん えんかい えんぎ えんげき えんしゅう えんぜつ えんそく えんちょう えんとつ おいかける おいこす おいしい おいつく おうえん おうさま おうじ おうせつ おうたい おうふく おうべい おうよう おえる おおい おおう おおどおり おおや おおよそ おかえり おかず おがむ おかわり おぎなう おきる おくさま おくじょう おくりがな おくる おくれる おこす おこなう おこる おさえる おさない おさめる おしいれ おしえる おじぎ おじさん おしゃれ おそらく おそわる おたがい おたく おだやか おちつく おっと おつり おでかけ おとしもの おとなしい おどり おどろかす おばさん おまいり おめでとう おもいで おもう おもたい おもちゃ おやつ おやゆび およぼす おらんだ おろす おんがく おんけい おんしゃ おんせん おんだん おんちゅう おんどけい かあつ かいが がいき がいけん がいこう かいさつ かいしゃ かいすいよく かいぜん かいぞうど かいつう かいてん かいとう かいふく がいへき かいほう かいよう がいらい かいわ かえる かおり かかえる かがく かがし かがみ かくご かくとく かざる がぞう かたい かたち がちょう がっきゅう がっこう がっさん がっしょう かなざわし かのう がはく かぶか かほう かほご かまう かまぼこ かめれおん かゆい かようび からい かるい かろう かわく かわら がんか かんけい かんこう かんしゃ かんそう かんたん かんち がんばる きあい きあつ きいろ ぎいん きうい きうん きえる きおう きおく きおち きおん きかい きかく きかんしゃ ききて きくばり きくらげ きけんせい きこう きこえる きこく きさい きさく きさま きさらぎ ぎじかがく ぎしき ぎじたいけん ぎじにってい ぎじゅつしゃ きすう きせい きせき きせつ きそう きぞく きぞん きたえる きちょう きつえん ぎっちり きつつき きつね きてい きどう きどく きない きなが きなこ きぬごし きねん きのう きのした きはく きびしい きひん きふく きぶん きぼう きほん きまる きみつ きむずかしい きめる きもだめし きもち きもの きゃく きやく ぎゅうにく きよう きょうりゅう きらい きらく きりん きれい きれつ きろく ぎろん きわめる ぎんいろ きんかくじ きんじょ きんようび ぐあい くいず くうかん くうき くうぐん くうこう ぐうせい くうそう ぐうたら くうふく くうぼ くかん くきょう くげん ぐこう くさい くさき くさばな くさる くしゃみ くしょう くすのき くすりゆび くせげ くせん ぐたいてき くださる くたびれる くちこみ くちさき くつした ぐっすり くつろぐ くとうてん くどく くなん くねくね くのう くふう くみあわせ くみたてる くめる くやくしょ くらす くらべる くるま くれる くろう くわしい ぐんかん ぐんしょく ぐんたい ぐんて けあな けいかく けいけん けいこ けいさつ げいじゅつ けいたい げいのうじん けいれき けいろ けおとす けおりもの げきか げきげん げきだん げきちん げきとつ げきは げきやく げこう げこくじょう げざい けさき げざん けしき けしごむ けしょう げすと けたば けちゃっぷ けちらす けつあつ けつい けつえき けっこん けつじょ けっせき けってい けつまつ げつようび げつれい けつろん げどく けとばす けとる けなげ けなす けなみ けぬき げねつ けねん けはい げひん けぶかい げぼく けまり けみかる けむし けむり けもの けらい けろけろ けわしい けんい けんえつ けんお けんか げんき けんげん けんこう けんさく けんしゅう けんすう げんそう けんちく けんてい けんとう けんない けんにん げんぶつ けんま けんみん けんめい けんらん けんり こあくま こいぬ こいびと ごうい こうえん こうおん こうかん ごうきゅう ごうけい こうこう こうさい こうじ こうすい ごうせい こうそく こうたい こうちゃ こうつう こうてい こうどう こうない こうはい ごうほう ごうまん こうもく こうりつ こえる こおり ごかい ごがつ ごかん こくご こくさい こくとう こくない こくはく こぐま こけい こける ここのか こころ こさめ こしつ こすう こせい こせき こぜん こそだて こたい こたえる こたつ こちょう こっか こつこつ こつばん こつぶ こてい こてん ことがら ことし ことば ことり こなごな こねこね このまま このみ このよ ごはん こひつじ こふう こふん こぼれる ごまあぶら こまかい ごますり こまつな こまる こむぎこ こもじ こもち こもの こもん こやく こやま こゆう こゆび こよい こよう こりる これくしょん ころっけ こわもて こわれる こんいん こんかい こんき こんしゅう こんすい こんだて こんとん こんなん こんびに こんぽん こんまけ こんや こんれい こんわく ざいえき さいかい さいきん ざいげん ざいこ さいしょ さいせい ざいたく ざいちゅう さいてき ざいりょう さうな さかいし さがす さかな さかみち さがる さぎょう さくし さくひん さくら さこく さこつ さずかる ざせき さたん さつえい ざつおん ざっか ざつがく さっきょく ざっし さつじん ざっそう さつたば さつまいも さてい さといも さとう さとおや さとし さとる さのう さばく さびしい さべつ さほう さほど さます さみしい さみだれ さむけ さめる さやえんどう さゆう さよう さよく さらだ ざるそば さわやか さわる さんいん さんか さんきゃく さんこう さんさい ざんしょ さんすう さんせい さんそ さんち さんま さんみ さんらん しあい しあげ しあさって しあわせ しいく しいん しうち しえい しおけ しかい しかく じかん しごと しすう じだい したうけ したぎ したて したみ しちょう しちりん しっかり しつじ しつもん してい してき してつ じてん じどう しなぎれ しなもの しなん しねま しねん しのぐ しのぶ しはい しばかり しはつ しはらい しはん しひょう しふく じぶん しへい しほう しほん しまう しまる しみん しむける じむしょ しめい しめる しもん しゃいん しゃうん しゃおん じゃがいも しやくしょ しゃくほう しゃけん しゃこ しゃざい しゃしん しゃせん しゃそう しゃたい しゃちょう しゃっきん じゃま しゃりん しゃれい じゆう じゅうしょ しゅくはく じゅしん しゅっせき しゅみ しゅらば じゅんばん しょうかい しょくたく しょっけん しょどう しょもつ しらせる しらべる しんか しんこう じんじゃ しんせいじ しんちく しんりん すあげ すあし すあな ずあん すいえい すいか すいとう ずいぶん すいようび すうがく すうじつ すうせん すおどり すきま すくう すくない すける すごい すこし ずさん すずしい すすむ すすめる すっかり ずっしり ずっと すてき すてる すねる すのこ すはだ すばらしい ずひょう ずぶぬれ すぶり すふれ すべて すべる ずほう すぼん すまい すめし すもう すやき すらすら するめ すれちがう すろっと すわる すんぜん すんぽう せあぶら せいかつ せいげん せいじ せいよう せおう せかいかん せきにん せきむ せきゆ せきらんうん せけん せこう せすじ せたい せたけ せっかく せっきゃく ぜっく せっけん せっこつ せっさたくま せつぞく せつだん せつでん せっぱん せつび せつぶん せつめい せつりつ せなか せのび せはば せびろ せぼね せまい せまる せめる せもたれ せりふ ぜんあく せんい せんえい せんか せんきょ せんく せんげん ぜんご せんさい せんしゅ せんすい せんせい せんぞ せんたく せんちょう せんてい せんとう せんぬき せんねん せんぱい ぜんぶ ぜんぽう せんむ せんめんじょ せんもん せんやく せんゆう せんよう ぜんら ぜんりゃく せんれい せんろ そあく そいとげる そいね そうがんきょう そうき そうご そうしん そうだん そうなん そうび そうめん そうり そえもの そえん そがい そげき そこう そこそこ そざい そしな そせい そせん そそぐ そだてる そつう そつえん そっかん そつぎょう そっけつ そっこう そっせん そっと そとがわ そとづら そなえる そなた そふぼ そぼく そぼろ そまつ そまる そむく そむりえ そめる そもそも そよかぜ そらまめ そろう そんかい そんけい そんざい そんしつ そんぞく そんちょう ぞんび ぞんぶん そんみん たあい たいいん たいうん たいえき たいおう だいがく たいき たいぐう たいけん たいこ たいざい だいじょうぶ だいすき たいせつ たいそう だいたい たいちょう たいてい だいどころ たいない たいねつ たいのう たいはん だいひょう たいふう たいへん たいほ たいまつばな たいみんぐ たいむ たいめん たいやき たいよう たいら たいりょく たいる たいわん たうえ たえる たおす たおる たおれる たかい たかね たきび たくさん たこく たこやき たさい たしざん だじゃれ たすける たずさわる たそがれ たたかう たたく ただしい たたみ たちばな だっかい だっきゃく だっこ だっしゅつ だったい たてる たとえる たなばた たにん たぬき たのしみ たはつ たぶん たべる たぼう たまご たまる だむる ためいき ためす ためる たもつ たやすい たよる たらす たりきほんがん たりょう たりる たると たれる たれんと たろっと たわむれる だんあつ たんい たんおん たんか たんき たんけん たんご たんさん たんじょうび だんせい たんそく たんたい だんち たんてい たんとう だんな たんにん だんねつ たんのう たんぴん だんぼう たんまつ たんめい だんれつ だんろ だんわ ちあい ちあん ちいき ちいさい ちえん ちかい ちから ちきゅう ちきん ちけいず ちけん ちこく ちさい ちしき ちしりょう ちせい ちそう ちたい ちたん ちちおや ちつじょ ちてき ちてん ちぬき ちぬり ちのう ちひょう ちへいせん ちほう ちまた ちみつ ちみどろ ちめいど ちゃんこなべ ちゅうい ちゆりょく ちょうし ちょさくけん ちらし ちらみ ちりがみ ちりょう ちるど ちわわ ちんたい ちんもく ついか ついたち つうか つうじょう つうはん つうわ つかう つかれる つくね つくる つけね つける つごう つたえる つづく つつじ つつむ つとめる つながる つなみ つねづね つのる つぶす つまらない つまる つみき つめたい つもり つもる つよい つるぼ つるみく つわもの つわり てあし てあて てあみ ていおん ていか ていき ていけい ていこく ていさつ ていし ていせい ていたい ていど ていねい ていひょう ていへん ていぼう てうち ておくれ てきとう てくび でこぼこ てさぎょう てさげ てすり てそう てちがい てちょう てつがく てつづき でっぱ てつぼう てつや でぬかえ てぬき てぬぐい てのひら てはい てぶくろ てふだ てほどき てほん てまえ てまきずし てみじか てみやげ てらす てれび てわけ てわたし でんあつ てんいん てんかい てんき てんぐ てんけん てんごく てんさい てんし てんすう でんち てんてき てんとう てんない てんぷら てんぼうだい てんめつ てんらんかい でんりょく でんわ どあい といれ どうかん とうきゅう どうぐ とうし とうむぎ とおい とおか とおく とおす とおる とかい とかす ときおり ときどき とくい とくしゅう とくてん とくに とくべつ とけい とける とこや とさか としょかん とそう とたん とちゅう とっきゅう とっくん とつぜん とつにゅう とどける ととのえる とない となえる となり とのさま とばす どぶがわ とほう とまる とめる ともだち ともる どようび とらえる とんかつ どんぶり ないかく ないこう ないしょ ないす ないせん ないそう なおす ながい なくす なげる なこうど なさけ なたでここ なっとう なつやすみ ななおし なにごと なにもの なにわ なのか なふだ なまいき なまえ なまみ なみだ なめらか なめる なやむ ならう ならび ならぶ なれる なわとび なわばり にあう にいがた にうけ におい にかい にがて にきび にくしみ にくまん にげる にさんかたんそ にしき にせもの にちじょう にちようび にっか にっき にっけい にっこう にっさん にっしょく にっすう にっせき にってい になう にほん にまめ にもつ にやり にゅういん にりんしゃ にわとり にんい にんか にんき にんげん にんしき にんずう にんそう にんたい にんち にんてい にんにく にんぷ にんまり にんむ にんめい にんよう ぬいくぎ ぬかす ぬぐいとる ぬぐう ぬくもり ぬすむ ぬまえび ぬめり ぬらす ぬんちゃく ねあげ ねいき ねいる ねいろ ねぐせ ねくたい ねくら ねこぜ ねこむ ねさげ ねすごす ねそべる ねだん ねつい ねっしん ねつぞう ねったいぎょ ねぶそく ねふだ ねぼう ねほりはほり ねまき ねまわし ねみみ ねむい ねむたい ねもと ねらう ねわざ ねんいり ねんおし ねんかん ねんきん ねんぐ ねんざ ねんし ねんちゃく ねんど ねんぴ ねんぶつ ねんまつ ねんりょう ねんれい のいず のおづま のがす のきなみ のこぎり のこす のこる のせる のぞく のぞむ のたまう のちほど のっく のばす のはら のべる のぼる のみもの のやま のらいぬ のらねこ のりもの のりゆき のれん のんき ばあい はあく ばあさん ばいか ばいく はいけん はいご はいしん はいすい はいせん はいそう はいち ばいばい はいれつ はえる はおる はかい ばかり はかる はくしゅ はけん はこぶ はさみ はさん はしご ばしょ はしる はせる ぱそこん はそん はたん はちみつ はつおん はっかく はづき はっきり はっくつ はっけん はっこう はっさん はっしん はったつ はっちゅう はってん はっぴょう はっぽう はなす はなび はにかむ はぶらし はみがき はむかう はめつ はやい はやし はらう はろうぃん はわい はんい はんえい はんおん はんかく はんきょう ばんぐみ はんこ はんしゃ はんすう はんだん ぱんち ぱんつ はんてい はんとし はんのう はんぱ はんぶん はんぺん はんぼうき はんめい はんらん はんろん ひいき ひうん ひえる ひかく ひかり ひかる ひかん ひくい ひけつ ひこうき ひこく ひさい ひさしぶり ひさん びじゅつかん ひしょ ひそか ひそむ ひたむき ひだり ひたる ひつぎ ひっこし ひっし ひつじゅひん ひっす ひつぜん ぴったり ぴっちり ひつよう ひてい ひとごみ ひなまつり ひなん ひねる ひはん ひびく ひひょう ひほう ひまわり ひまん ひみつ ひめい ひめじし ひやけ ひやす ひよう びょうき ひらがな ひらく ひりつ ひりょう ひるま ひるやすみ ひれい ひろい ひろう ひろき ひろゆき ひんかく ひんけつ ひんこん ひんしゅ ひんそう ぴんち ひんぱん びんぼう ふあん ふいうち ふうけい ふうせん ぷうたろう ふうとう ふうふ ふえる ふおん ふかい ふきん ふくざつ ふくぶくろ ふこう ふさい ふしぎ ふじみ ふすま ふせい ふせぐ ふそく ぶたにく ふたん ふちょう ふつう ふつか ふっかつ ふっき ふっこく ぶどう ふとる ふとん ふのう ふはい ふひょう ふへん ふまん ふみん ふめつ ふめん ふよう ふりこ ふりる ふるい ふんいき ぶんがく ぶんぐ ふんしつ ぶんせき ふんそう ぶんぽう へいあん へいおん へいがい へいき へいげん へいこう へいさ へいしゃ へいせつ へいそ へいたく へいてん へいねつ へいわ へきが へこむ べにいろ べにしょうが へらす へんかん べんきょう べんごし へんさい へんたい べんり ほあん ほいく ぼうぎょ ほうこく ほうそう ほうほう ほうもん ほうりつ ほえる ほおん ほかん ほきょう ぼきん ほくろ ほけつ ほけん ほこう ほこる ほしい ほしつ ほしゅ ほしょう ほせい ほそい ほそく ほたて ほたる ぽちぶくろ ほっきょく ほっさ ほったん ほとんど ほめる ほんい ほんき ほんけ ほんしつ ほんやく まいにち まかい まかせる まがる まける まこと まさつ まじめ ますく まぜる まつり まとめ まなぶ まぬけ まねく まほう まもる まゆげ まよう まろやか まわす まわり まわる まんが まんきつ まんぞく まんなか みいら みうち みえる みがく みかた みかん みけん みこん みじかい みすい みすえる みせる みっか みつかる みつける みてい みとめる みなと みなみかさい みねらる みのう みのがす みほん みもと みやげ みらい みりょく みわく みんか みんぞく むいか むえき むえん むかい むかう むかえ むかし むぎちゃ むける むげん むさぼる むしあつい むしば むじゅん むしろ むすう むすこ むすぶ むすめ むせる むせん むちゅう むなしい むのう むやみ むよう むらさき むりょう むろん めいあん めいうん めいえん めいかく めいきょく めいさい めいし めいそう めいぶつ めいれい めいわく めぐまれる めざす めした めずらしい めだつ めまい めやす めんきょ めんせき めんどう もうしあげる もうどうけん もえる もくし もくてき もくようび もちろん もどる もらう もんく もんだい やおや やける やさい やさしい やすい やすたろう やすみ やせる やそう やたい やちん やっと やっぱり やぶる やめる ややこしい やよい やわらかい ゆうき ゆうびんきょく ゆうべ ゆうめい ゆけつ ゆしゅつ ゆせん ゆそう ゆたか ゆちゃく ゆでる ゆにゅう ゆびわ ゆらい ゆれる ようい ようか ようきゅう ようじ ようす ようちえん よかぜ よかん よきん よくせい よくぼう よけい よごれる よさん よしゅう よそう よそく よっか よてい よどがわく よねつ よやく よゆう よろこぶ よろしい らいう らくがき らくご らくさつ らくだ らしんばん らせん らぞく らたい らっか られつ りえき りかい りきさく りきせつ りくぐん りくつ りけん りこう りせい りそう りそく りてん りねん りゆう りゅうがく りよう りょうり りょかん りょくちゃ りょこう りりく りれき りろん りんご るいけい るいさい るいじ るいせき るすばん るりがわら れいかん れいぎ れいせい れいぞうこ れいとう れいぼう れきし れきだい れんあい れんけい れんこん れんさい れんしゅう れんぞく れんらく ろうか ろうご ろうじん ろうそく ろくが ろこつ ろじうら ろしゅつ ろせん ろてん ろめん ろれつ ろんぎ ろんぱ ろんぶん ろんり わかす わかめ わかやま わかれる わしつ わじまし わすれもの わらう われる ` ) ================================================ FILE: util/bip39/wordlists/korean.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/korean.txt // $ crc32 korean.txt // 4ef461eb checksum := crc32.ChecksumIEEE([]byte(korean)) if fmt.Sprintf("%x", checksum) != "4ef461eb" { panic("korean checksum invalid") } } // Korean is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/korean.txt var ( Korean = strings.Split(strings.TrimSpace(korean), "\n") korean = `가격 가끔 가난 가능 가득 가르침 가뭄 가방 가상 가슴 가운데 가을 가이드 가입 가장 가정 가족 가죽 각오 각자 간격 간부 간섭 간장 간접 간판 갈등 갈비 갈색 갈증 감각 감기 감소 감수성 감자 감정 갑자기 강남 강당 강도 강력히 강변 강북 강사 강수량 강아지 강원도 강의 강제 강조 같이 개구리 개나리 개방 개별 개선 개성 개인 객관적 거실 거액 거울 거짓 거품 걱정 건강 건물 건설 건조 건축 걸음 검사 검토 게시판 게임 겨울 견해 결과 결국 결론 결석 결승 결심 결정 결혼 경계 경고 경기 경력 경복궁 경비 경상도 경영 경우 경쟁 경제 경주 경찰 경치 경향 경험 계곡 계단 계란 계산 계속 계약 계절 계층 계획 고객 고구려 고궁 고급 고등학생 고무신 고민 고양이 고장 고전 고집 고춧가루 고통 고향 곡식 골목 골짜기 골프 공간 공개 공격 공군 공급 공기 공동 공무원 공부 공사 공식 공업 공연 공원 공장 공짜 공책 공통 공포 공항 공휴일 과목 과일 과장 과정 과학 관객 관계 관광 관념 관람 관련 관리 관습 관심 관점 관찰 광경 광고 광장 광주 괴로움 굉장히 교과서 교문 교복 교실 교양 교육 교장 교직 교통 교환 교훈 구경 구름 구멍 구별 구분 구석 구성 구속 구역 구입 구청 구체적 국가 국기 국내 국립 국물 국민 국수 국어 국왕 국적 국제 국회 군대 군사 군인 궁극적 권리 권위 권투 귀국 귀신 규정 규칙 균형 그날 그냥 그늘 그러나 그룹 그릇 그림 그제서야 그토록 극복 극히 근거 근교 근래 근로 근무 근본 근원 근육 근처 글씨 글자 금강산 금고 금년 금메달 금액 금연 금요일 금지 긍정적 기간 기관 기념 기능 기독교 기둥 기록 기름 기법 기본 기분 기쁨 기숙사 기술 기억 기업 기온 기운 기원 기적 기준 기침 기혼 기획 긴급 긴장 길이 김밥 김치 김포공항 깍두기 깜빡 깨달음 깨소금 껍질 꼭대기 꽃잎 나들이 나란히 나머지 나물 나침반 나흘 낙엽 난방 날개 날씨 날짜 남녀 남대문 남매 남산 남자 남편 남학생 낭비 낱말 내년 내용 내일 냄비 냄새 냇물 냉동 냉면 냉방 냉장고 넥타이 넷째 노동 노란색 노력 노인 녹음 녹차 녹화 논리 논문 논쟁 놀이 농구 농담 농민 농부 농업 농장 농촌 높이 눈동자 눈물 눈썹 뉴욕 느낌 늑대 능동적 능력 다방 다양성 다음 다이어트 다행 단계 단골 단독 단맛 단순 단어 단위 단점 단체 단추 단편 단풍 달걀 달러 달력 달리 닭고기 담당 담배 담요 담임 답변 답장 당근 당분간 당연히 당장 대규모 대낮 대단히 대답 대도시 대략 대량 대륙 대문 대부분 대신 대응 대장 대전 대접 대중 대책 대출 대충 대통령 대학 대한민국 대합실 대형 덩어리 데이트 도대체 도덕 도둑 도망 도서관 도심 도움 도입 도자기 도저히 도전 도중 도착 독감 독립 독서 독일 독창적 동화책 뒷모습 뒷산 딸아이 마누라 마늘 마당 마라톤 마련 마무리 마사지 마약 마요네즈 마을 마음 마이크 마중 마지막 마찬가지 마찰 마흔 막걸리 막내 막상 만남 만두 만세 만약 만일 만점 만족 만화 많이 말기 말씀 말투 맘대로 망원경 매년 매달 매력 매번 매스컴 매일 매장 맥주 먹이 먼저 먼지 멀리 메일 며느리 며칠 면담 멸치 명단 명령 명예 명의 명절 명칭 명함 모금 모니터 모델 모든 모범 모습 모양 모임 모조리 모집 모퉁이 목걸이 목록 목사 목소리 목숨 목적 목표 몰래 몸매 몸무게 몸살 몸속 몸짓 몸통 몹시 무관심 무궁화 무더위 무덤 무릎 무슨 무엇 무역 무용 무조건 무지개 무척 문구 문득 문법 문서 문제 문학 문화 물가 물건 물결 물고기 물론 물리학 물음 물질 물체 미국 미디어 미사일 미술 미역 미용실 미움 미인 미팅 미혼 민간 민족 민주 믿음 밀가루 밀리미터 밑바닥 바가지 바구니 바나나 바늘 바닥 바닷가 바람 바이러스 바탕 박물관 박사 박수 반대 반드시 반말 반발 반성 반응 반장 반죽 반지 반찬 받침 발가락 발걸음 발견 발달 발레 발목 발바닥 발생 발음 발자국 발전 발톱 발표 밤하늘 밥그릇 밥맛 밥상 밥솥 방금 방면 방문 방바닥 방법 방송 방식 방안 방울 방지 방학 방해 방향 배경 배꼽 배달 배드민턴 백두산 백색 백성 백인 백제 백화점 버릇 버섯 버튼 번개 번역 번지 번호 벌금 벌레 벌써 범위 범인 범죄 법률 법원 법적 법칙 베이징 벨트 변경 변동 변명 변신 변호사 변화 별도 별명 별일 병실 병아리 병원 보관 보너스 보라색 보람 보름 보상 보안 보자기 보장 보전 보존 보통 보편적 보험 복도 복사 복숭아 복습 볶음 본격적 본래 본부 본사 본성 본인 본질 볼펜 봉사 봉지 봉투 부근 부끄러움 부담 부동산 부문 부분 부산 부상 부엌 부인 부작용 부장 부정 부족 부지런히 부친 부탁 부품 부회장 북부 북한 분노 분량 분리 분명 분석 분야 분위기 분필 분홍색 불고기 불과 불교 불꽃 불만 불법 불빛 불안 불이익 불행 브랜드 비극 비난 비닐 비둘기 비디오 비로소 비만 비명 비밀 비바람 비빔밥 비상 비용 비율 비중 비타민 비판 빌딩 빗물 빗방울 빗줄기 빛깔 빨간색 빨래 빨리 사건 사계절 사나이 사냥 사람 사랑 사립 사모님 사물 사방 사상 사생활 사설 사슴 사실 사업 사용 사월 사장 사전 사진 사촌 사춘기 사탕 사투리 사흘 산길 산부인과 산업 산책 살림 살인 살짝 삼계탕 삼국 삼십 삼월 삼촌 상관 상금 상대 상류 상반기 상상 상식 상업 상인 상자 상점 상처 상추 상태 상표 상품 상황 새벽 색깔 색연필 생각 생명 생물 생방송 생산 생선 생신 생일 생활 서랍 서른 서명 서민 서비스 서양 서울 서적 서점 서쪽 서클 석사 석유 선거 선물 선배 선생 선수 선원 선장 선전 선택 선풍기 설거지 설날 설렁탕 설명 설문 설사 설악산 설치 설탕 섭씨 성공 성당 성명 성별 성인 성장 성적 성질 성함 세금 세미나 세상 세월 세종대왕 세탁 센터 센티미터 셋째 소규모 소극적 소금 소나기 소년 소득 소망 소문 소설 소속 소아과 소용 소원 소음 소중히 소지품 소질 소풍 소형 속담 속도 속옷 손가락 손길 손녀 손님 손등 손목 손뼉 손실 손질 손톱 손해 솔직히 솜씨 송아지 송이 송편 쇠고기 쇼핑 수건 수년 수단 수돗물 수동적 수면 수명 수박 수상 수석 수술 수시로 수업 수염 수영 수입 수준 수집 수출 수컷 수필 수학 수험생 수화기 숙녀 숙소 숙제 순간 순서 순수 순식간 순위 숟가락 술병 술집 숫자 스님 스물 스스로 스승 스웨터 스위치 스케이트 스튜디오 스트레스 스포츠 슬쩍 슬픔 습관 습기 승객 승리 승부 승용차 승진 시각 시간 시골 시금치 시나리오 시댁 시리즈 시멘트 시민 시부모 시선 시설 시스템 시아버지 시어머니 시월 시인 시일 시작 시장 시절 시점 시중 시즌 시집 시청 시합 시험 식구 식기 식당 식량 식료품 식물 식빵 식사 식생활 식초 식탁 식품 신고 신규 신념 신문 신발 신비 신사 신세 신용 신제품 신청 신체 신화 실감 실내 실력 실례 실망 실수 실습 실시 실장 실정 실질적 실천 실체 실컷 실태 실패 실험 실현 심리 심부름 심사 심장 심정 심판 쌍둥이 씨름 씨앗 아가씨 아나운서 아드님 아들 아쉬움 아스팔트 아시아 아울러 아저씨 아줌마 아직 아침 아파트 아프리카 아픔 아홉 아흔 악기 악몽 악수 안개 안경 안과 안내 안녕 안동 안방 안부 안주 알루미늄 알코올 암시 암컷 압력 앞날 앞문 애인 애정 액수 앨범 야간 야단 야옹 약간 약국 약속 약수 약점 약품 약혼녀 양념 양력 양말 양배추 양주 양파 어둠 어려움 어른 어젯밤 어쨌든 어쩌다가 어쩐지 언니 언덕 언론 언어 얼굴 얼른 얼음 얼핏 엄마 업무 업종 업체 엉덩이 엉망 엉터리 엊그제 에너지 에어컨 엔진 여건 여고생 여관 여군 여권 여대생 여덟 여동생 여든 여론 여름 여섯 여성 여왕 여인 여전히 여직원 여학생 여행 역사 역시 역할 연결 연구 연극 연기 연락 연설 연세 연속 연습 연애 연예인 연인 연장 연주 연출 연필 연합 연휴 열기 열매 열쇠 열심히 열정 열차 열흘 염려 엽서 영국 영남 영상 영양 영역 영웅 영원히 영하 영향 영혼 영화 옆구리 옆방 옆집 예감 예금 예방 예산 예상 예선 예술 예습 예식장 예약 예전 예절 예정 예컨대 옛날 오늘 오락 오랫동안 오렌지 오로지 오른발 오븐 오십 오염 오월 오전 오직 오징어 오페라 오피스텔 오히려 옥상 옥수수 온갖 온라인 온몸 온종일 온통 올가을 올림픽 올해 옷차림 와이셔츠 와인 완성 완전 왕비 왕자 왜냐하면 왠지 외갓집 외국 외로움 외삼촌 외출 외침 외할머니 왼발 왼손 왼쪽 요금 요일 요즘 요청 용기 용서 용어 우산 우선 우승 우연히 우정 우체국 우편 운동 운명 운반 운전 운행 울산 울음 움직임 웃어른 웃음 워낙 원고 원래 원서 원숭이 원인 원장 원피스 월급 월드컵 월세 월요일 웨이터 위반 위법 위성 위원 위험 위협 윗사람 유난히 유럽 유명 유물 유산 유적 유치원 유학 유행 유형 육군 육상 육십 육체 은행 음력 음료 음반 음성 음식 음악 음주 의견 의논 의문 의복 의식 의심 의외로 의욕 의원 의학 이것 이곳 이념 이놈 이달 이대로 이동 이렇게 이력서 이론적 이름 이민 이발소 이별 이불 이빨 이상 이성 이슬 이야기 이용 이웃 이월 이윽고 이익 이전 이중 이튿날 이틀 이혼 인간 인격 인공 인구 인근 인기 인도 인류 인물 인생 인쇄 인연 인원 인재 인종 인천 인체 인터넷 인하 인형 일곱 일기 일단 일대 일등 일반 일본 일부 일상 일생 일손 일요일 일월 일정 일종 일주일 일찍 일체 일치 일행 일회용 임금 임무 입대 입력 입맛 입사 입술 입시 입원 입장 입학 자가용 자격 자극 자동 자랑 자부심 자식 자신 자연 자원 자율 자전거 자정 자존심 자판 작가 작년 작성 작업 작용 작은딸 작품 잔디 잔뜩 잔치 잘못 잠깐 잠수함 잠시 잠옷 잠자리 잡지 장관 장군 장기간 장래 장례 장르 장마 장면 장모 장미 장비 장사 장소 장식 장애인 장인 장점 장차 장학금 재능 재빨리 재산 재생 재작년 재정 재채기 재판 재학 재활용 저것 저고리 저곳 저녁 저런 저렇게 저번 저울 저절로 저축 적극 적당히 적성 적용 적응 전개 전공 전기 전달 전라도 전망 전문 전반 전부 전세 전시 전용 전자 전쟁 전주 전철 전체 전통 전혀 전후 절대 절망 절반 절약 절차 점검 점수 점심 점원 점점 점차 접근 접시 접촉 젓가락 정거장 정도 정류장 정리 정말 정면 정문 정반대 정보 정부 정비 정상 정성 정오 정원 정장 정지 정치 정확히 제공 제과점 제대로 제목 제발 제법 제삿날 제안 제일 제작 제주도 제출 제품 제한 조각 조건 조금 조깅 조명 조미료 조상 조선 조용히 조절 조정 조직 존댓말 존재 졸업 졸음 종교 종로 종류 종소리 종업원 종종 종합 좌석 죄인 주관적 주름 주말 주머니 주먹 주문 주민 주방 주변 주식 주인 주일 주장 주전자 주택 준비 줄거리 줄기 줄무늬 중간 중계방송 중국 중년 중단 중독 중반 중부 중세 중소기업 중순 중앙 중요 중학교 즉석 즉시 즐거움 증가 증거 증권 증상 증세 지각 지갑 지경 지극히 지금 지급 지능 지름길 지리산 지방 지붕 지식 지역 지우개 지원 지적 지점 지진 지출 직선 직업 직원 직장 진급 진동 진로 진료 진리 진짜 진찰 진출 진통 진행 질문 질병 질서 짐작 집단 집안 집중 짜증 찌꺼기 차남 차라리 차량 차림 차별 차선 차츰 착각 찬물 찬성 참가 참기름 참새 참석 참여 참외 참조 찻잔 창가 창고 창구 창문 창밖 창작 창조 채널 채점 책가방 책방 책상 책임 챔피언 처벌 처음 천국 천둥 천장 천재 천천히 철도 철저히 철학 첫날 첫째 청년 청바지 청소 청춘 체계 체력 체온 체육 체중 체험 초등학생 초반 초밥 초상화 초순 초여름 초원 초저녁 초점 초청 초콜릿 촛불 총각 총리 총장 촬영 최근 최상 최선 최신 최악 최종 추석 추억 추진 추천 추측 축구 축소 축제 축하 출근 출발 출산 출신 출연 출입 출장 출판 충격 충고 충돌 충분히 충청도 취업 취직 취향 치약 친구 친척 칠십 칠월 칠판 침대 침묵 침실 칫솔 칭찬 카메라 카운터 칼국수 캐릭터 캠퍼스 캠페인 커튼 컨디션 컬러 컴퓨터 코끼리 코미디 콘서트 콜라 콤플렉스 콩나물 쾌감 쿠데타 크림 큰길 큰딸 큰소리 큰아들 큰어머니 큰일 큰절 클래식 클럽 킬로 타입 타자기 탁구 탁자 탄생 태권도 태양 태풍 택시 탤런트 터널 터미널 테니스 테스트 테이블 텔레비전 토론 토마토 토요일 통계 통과 통로 통신 통역 통일 통장 통제 통증 통합 통화 퇴근 퇴원 퇴직금 튀김 트럭 특급 특별 특성 특수 특징 특히 튼튼히 티셔츠 파란색 파일 파출소 판결 판단 판매 판사 팔십 팔월 팝송 패션 팩스 팩시밀리 팬티 퍼센트 페인트 편견 편의 편지 편히 평가 평균 평생 평소 평양 평일 평화 포스터 포인트 포장 포함 표면 표정 표준 표현 품목 품질 풍경 풍속 풍습 프랑스 프린터 플라스틱 피곤 피망 피아노 필름 필수 필요 필자 필통 핑계 하느님 하늘 하드웨어 하룻밤 하반기 하숙집 하순 하여튼 하지만 하천 하품 하필 학과 학교 학급 학기 학년 학력 학번 학부모 학비 학생 학술 학습 학용품 학원 학위 학자 학점 한계 한글 한꺼번에 한낮 한눈 한동안 한때 한라산 한마디 한문 한번 한복 한식 한여름 한쪽 할머니 할아버지 할인 함께 함부로 합격 합리적 항공 항구 항상 항의 해결 해군 해답 해당 해물 해석 해설 해수욕장 해안 핵심 핸드백 햄버거 햇볕 햇살 행동 행복 행사 행운 행위 향기 향상 향수 허락 허용 헬기 현관 현금 현대 현상 현실 현장 현재 현지 혈액 협력 형부 형사 형수 형식 형제 형태 형편 혜택 호기심 호남 호랑이 호박 호텔 호흡 혹시 홀로 홈페이지 홍보 홍수 홍차 화면 화분 화살 화요일 화장 화학 확보 확인 확장 확정 환갑 환경 환영 환율 환자 활기 활동 활발히 활용 활짝 회견 회관 회복 회색 회원 회장 회전 횟수 횡단보도 효율적 후반 후춧가루 훈련 훨씬 휴식 휴일 흉내 흐름 흑백 흑인 흔적 흔히 흥미 흥분 희곡 희망 희생 흰색 힘껏 ` ) ================================================ FILE: util/bip39/wordlists/spanish.go ================================================ package wordlists import ( "fmt" "hash/crc32" "strings" ) func init() { // Ensure word list is correct // $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/spanish.txt // $ crc32 spanish.txt // 266e4f3d checksum := crc32.ChecksumIEEE([]byte(spanish)) if fmt.Sprintf("%x", checksum) != "266e4f3d" { panic("spanish checksum invalid") } } // Spanish is a slice of mnemonic words taken from the bip39 specification // https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/spanish.txt var ( Spanish = strings.Split(strings.TrimSpace(spanish), "\n") spanish = `ábaco abdomen abeja abierto abogado abono aborto abrazo abrir abuelo abuso acabar academia acceso acción aceite acelga acento aceptar ácido aclarar acné acoger acoso activo acto actriz actuar acudir acuerdo acusar adicto admitir adoptar adorno aduana adulto aéreo afectar afición afinar afirmar ágil agitar agonía agosto agotar agregar agrio agua agudo águila aguja ahogo ahorro aire aislar ajedrez ajeno ajuste alacrán alambre alarma alba álbum alcalde aldea alegre alejar alerta aleta alfiler alga algodón aliado aliento alivio alma almeja almíbar altar alteza altivo alto altura alumno alzar amable amante amapola amargo amasar ámbar ámbito ameno amigo amistad amor amparo amplio ancho anciano ancla andar andén anemia ángulo anillo ánimo anís anotar antena antiguo antojo anual anular anuncio añadir añejo año apagar aparato apetito apio aplicar apodo aporte apoyo aprender aprobar apuesta apuro arado araña arar árbitro árbol arbusto archivo arco arder ardilla arduo área árido aries armonía arnés aroma arpa arpón arreglo arroz arruga arte artista asa asado asalto ascenso asegurar aseo asesor asiento asilo asistir asno asombro áspero astilla astro astuto asumir asunto atajo ataque atar atento ateo ático atleta átomo atraer atroz atún audaz audio auge aula aumento ausente autor aval avance avaro ave avellana avena avestruz avión aviso ayer ayuda ayuno azafrán azar azote azúcar azufre azul baba babor bache bahía baile bajar balanza balcón balde bambú banco banda baño barba barco barniz barro báscula bastón basura batalla batería batir batuta baúl bazar bebé bebida bello besar beso bestia bicho bien bingo blanco bloque blusa boa bobina bobo boca bocina boda bodega boina bola bolero bolsa bomba bondad bonito bono bonsái borde borrar bosque bote botín bóveda bozal bravo brazo brecha breve brillo brinco brisa broca broma bronce brote bruja brusco bruto buceo bucle bueno buey bufanda bufón búho buitre bulto burbuja burla burro buscar butaca buzón caballo cabeza cabina cabra cacao cadáver cadena caer café caída caimán caja cajón cal calamar calcio caldo calidad calle calma calor calvo cama cambio camello camino campo cáncer candil canela canguro canica canto caña cañón caoba caos capaz capitán capote captar capucha cara carbón cárcel careta carga cariño carne carpeta carro carta casa casco casero caspa castor catorce catre caudal causa cazo cebolla ceder cedro celda célebre celoso célula cemento ceniza centro cerca cerdo cereza cero cerrar certeza césped cetro chacal chaleco champú chancla chapa charla chico chiste chivo choque choza chuleta chupar ciclón ciego cielo cien cierto cifra cigarro cima cinco cine cinta ciprés circo ciruela cisne cita ciudad clamor clan claro clase clave cliente clima clínica cobre cocción cochino cocina coco código codo cofre coger cohete cojín cojo cola colcha colegio colgar colina collar colmo columna combate comer comida cómodo compra conde conejo conga conocer consejo contar copa copia corazón corbata corcho cordón corona correr coser cosmos costa cráneo cráter crear crecer creído crema cría crimen cripta crisis cromo crónica croqueta crudo cruz cuadro cuarto cuatro cubo cubrir cuchara cuello cuento cuerda cuesta cueva cuidar culebra culpa culto cumbre cumplir cuna cuneta cuota cupón cúpula curar curioso curso curva cutis dama danza dar dardo dátil deber débil década decir dedo defensa definir dejar delfín delgado delito demora denso dental deporte derecho derrota desayuno deseo desfile desnudo destino desvío detalle detener deuda día diablo diadema diamante diana diario dibujo dictar diente dieta diez difícil digno dilema diluir dinero directo dirigir disco diseño disfraz diva divino doble doce dolor domingo don donar dorado dormir dorso dos dosis dragón droga ducha duda duelo dueño dulce dúo duque durar dureza duro ébano ebrio echar eco ecuador edad edición edificio editor educar efecto eficaz eje ejemplo elefante elegir elemento elevar elipse élite elixir elogio eludir embudo emitir emoción empate empeño empleo empresa enano encargo enchufe encía enemigo enero enfado enfermo engaño enigma enlace enorme enredo ensayo enseñar entero entrar envase envío época equipo erizo escala escena escolar escribir escudo esencia esfera esfuerzo espada espejo espía esposa espuma esquí estar este estilo estufa etapa eterno ética etnia evadir evaluar evento evitar exacto examen exceso excusa exento exigir exilio existir éxito experto explicar exponer extremo fábrica fábula fachada fácil factor faena faja falda fallo falso faltar fama familia famoso faraón farmacia farol farsa fase fatiga fauna favor fax febrero fecha feliz feo feria feroz fértil fervor festín fiable fianza fiar fibra ficción ficha fideo fiebre fiel fiera fiesta figura fijar fijo fila filete filial filtro fin finca fingir finito firma flaco flauta flecha flor flota fluir flujo flúor fobia foca fogata fogón folio folleto fondo forma forro fortuna forzar fosa foto fracaso frágil franja frase fraude freír freno fresa frío frito fruta fuego fuente fuerza fuga fumar función funda furgón furia fusil fútbol futuro gacela gafas gaita gajo gala galería gallo gamba ganar gancho ganga ganso garaje garza gasolina gastar gato gavilán gemelo gemir gen género genio gente geranio gerente germen gesto gigante gimnasio girar giro glaciar globo gloria gol golfo goloso golpe goma gordo gorila gorra gota goteo gozar grada gráfico grano grasa gratis grave grieta grillo gripe gris grito grosor grúa grueso grumo grupo guante guapo guardia guerra guía guiño guion guiso guitarra gusano gustar haber hábil hablar hacer hacha hada hallar hamaca harina haz hazaña hebilla hebra hecho helado helio hembra herir hermano héroe hervir hielo hierro hígado higiene hijo himno historia hocico hogar hoguera hoja hombre hongo honor honra hora hormiga horno hostil hoyo hueco huelga huerta hueso huevo huida huir humano húmedo humilde humo hundir huracán hurto icono ideal idioma ídolo iglesia iglú igual ilegal ilusión imagen imán imitar impar imperio imponer impulso incapaz índice inerte infiel informe ingenio inicio inmenso inmune innato insecto instante interés íntimo intuir inútil invierno ira iris ironía isla islote jabalí jabón jamón jarabe jardín jarra jaula jazmín jefe jeringa jinete jornada joroba joven joya juerga jueves juez jugador jugo juguete juicio junco jungla junio juntar júpiter jurar justo juvenil juzgar kilo koala labio lacio lacra lado ladrón lagarto lágrima laguna laico lamer lámina lámpara lana lancha langosta lanza lápiz largo larva lástima lata látex latir laurel lavar lazo leal lección leche lector leer legión legumbre lejano lengua lento leña león leopardo lesión letal letra leve leyenda libertad libro licor líder lidiar lienzo liga ligero lima límite limón limpio lince lindo línea lingote lino linterna líquido liso lista litera litio litro llaga llama llanto llave llegar llenar llevar llorar llover lluvia lobo loción loco locura lógica logro lombriz lomo lonja lote lucha lucir lugar lujo luna lunes lupa lustro luto luz maceta macho madera madre maduro maestro mafia magia mago maíz maldad maleta malla malo mamá mambo mamut manco mando manejar manga maniquí manjar mano manso manta mañana mapa máquina mar marco marea marfil margen marido mármol marrón martes marzo masa máscara masivo matar materia matiz matriz máximo mayor mazorca mecha medalla medio médula mejilla mejor melena melón memoria menor mensaje mente menú mercado merengue mérito mes mesón meta meter método metro mezcla miedo miel miembro miga mil milagro militar millón mimo mina minero mínimo minuto miope mirar misa miseria misil mismo mitad mito mochila moción moda modelo moho mojar molde moler molino momento momia monarca moneda monja monto moño morada morder moreno morir morro morsa mortal mosca mostrar motivo mover móvil mozo mucho mudar mueble muela muerte muestra mugre mujer mula muleta multa mundo muñeca mural muro músculo museo musgo música muslo nácar nación nadar naipe naranja nariz narrar nasal natal nativo natural náusea naval nave navidad necio néctar negar negocio negro neón nervio neto neutro nevar nevera nicho nido niebla nieto niñez niño nítido nivel nobleza noche nómina noria norma norte nota noticia novato novela novio nube nuca núcleo nudillo nudo nuera nueve nuez nulo número nutria oasis obeso obispo objeto obra obrero observar obtener obvio oca ocaso océano ochenta ocho ocio ocre octavo octubre oculto ocupar ocurrir odiar odio odisea oeste ofensa oferta oficio ofrecer ogro oído oír ojo ola oleada olfato olivo olla olmo olor olvido ombligo onda onza opaco opción ópera opinar oponer optar óptica opuesto oración orador oral órbita orca orden oreja órgano orgía orgullo oriente origen orilla oro orquesta oruga osadía oscuro osezno oso ostra otoño otro oveja óvulo óxido oxígeno oyente ozono pacto padre paella página pago país pájaro palabra palco paleta pálido palma paloma palpar pan panal pánico pantera pañuelo papá papel papilla paquete parar parcela pared parir paro párpado parque párrafo parte pasar paseo pasión paso pasta pata patio patria pausa pauta pavo payaso peatón pecado pecera pecho pedal pedir pegar peine pelar peldaño pelea peligro pellejo pelo peluca pena pensar peñón peón peor pepino pequeño pera percha perder pereza perfil perico perla permiso perro persona pesa pesca pésimo pestaña pétalo petróleo pez pezuña picar pichón pie piedra pierna pieza pijama pilar piloto pimienta pino pintor pinza piña piojo pipa pirata pisar piscina piso pista pitón pizca placa plan plata playa plaza pleito pleno plomo pluma plural pobre poco poder podio poema poesía poeta polen policía pollo polvo pomada pomelo pomo pompa poner porción portal posada poseer posible poste potencia potro pozo prado precoz pregunta premio prensa preso previo primo príncipe prisión privar proa probar proceso producto proeza profesor programa prole promesa pronto propio próximo prueba público puchero pudor pueblo puerta puesto pulga pulir pulmón pulpo pulso puma punto puñal puño pupa pupila puré quedar queja quemar querer queso quieto química quince quitar rábano rabia rabo ración radical raíz rama rampa rancho rango rapaz rápido rapto rasgo raspa rato rayo raza razón reacción realidad rebaño rebote recaer receta rechazo recoger recreo recto recurso red redondo reducir reflejo reforma refrán refugio regalo regir regla regreso rehén reino reír reja relato relevo relieve relleno reloj remar remedio remo rencor rendir renta reparto repetir reposo reptil res rescate resina respeto resto resumen retiro retorno retrato reunir revés revista rey rezar rico riego rienda riesgo rifa rígido rigor rincón riñón río riqueza risa ritmo rito rizo roble roce rociar rodar rodeo rodilla roer rojizo rojo romero romper ron ronco ronda ropa ropero rosa rosca rostro rotar rubí rubor rudo rueda rugir ruido ruina ruleta rulo rumbo rumor ruptura ruta rutina sábado saber sabio sable sacar sagaz sagrado sala saldo salero salir salmón salón salsa salto salud salvar samba sanción sandía sanear sangre sanidad sano santo sapo saque sardina sartén sastre satán sauna saxofón sección seco secreto secta sed seguir seis sello selva semana semilla senda sensor señal señor separar sepia sequía ser serie sermón servir sesenta sesión seta setenta severo sexo sexto sidra siesta siete siglo signo sílaba silbar silencio silla símbolo simio sirena sistema sitio situar sobre socio sodio sol solapa soldado soledad sólido soltar solución sombra sondeo sonido sonoro sonrisa sopa soplar soporte sordo sorpresa sorteo sostén sótano suave subir suceso sudor suegra suelo sueño suerte sufrir sujeto sultán sumar superar suplir suponer supremo sur surco sureño surgir susto sutil tabaco tabique tabla tabú taco tacto tajo talar talco talento talla talón tamaño tambor tango tanque tapa tapete tapia tapón taquilla tarde tarea tarifa tarjeta tarot tarro tarta tatuaje tauro taza tazón teatro techo tecla técnica tejado tejer tejido tela teléfono tema temor templo tenaz tender tener tenis tenso teoría terapia terco término ternura terror tesis tesoro testigo tetera texto tez tibio tiburón tiempo tienda tierra tieso tigre tijera tilde timbre tímido timo tinta tío típico tipo tira tirón titán títere título tiza toalla tobillo tocar tocino todo toga toldo tomar tono tonto topar tope toque tórax torero tormenta torneo toro torpedo torre torso tortuga tos tosco toser tóxico trabajo tractor traer tráfico trago traje tramo trance trato trauma trazar trébol tregua treinta tren trepar tres tribu trigo tripa triste triunfo trofeo trompa tronco tropa trote trozo truco trueno trufa tubería tubo tuerto tumba tumor túnel túnica turbina turismo turno tutor ubicar úlcera umbral unidad unir universo uno untar uña urbano urbe urgente urna usar usuario útil utopía uva vaca vacío vacuna vagar vago vaina vajilla vale válido valle valor válvula vampiro vara variar varón vaso vecino vector vehículo veinte vejez vela velero veloz vena vencer venda veneno vengar venir venta venus ver verano verbo verde vereda verja verso verter vía viaje vibrar vicio víctima vida vídeo vidrio viejo viernes vigor vil villa vinagre vino viñedo violín viral virgo virtud visor víspera vista vitamina viudo vivaz vivero vivir vivo volcán volumen volver voraz votar voto voz vuelo vulgar yacer yate yegua yema yerno yeso yodo yoga yogur zafiro zanja zapato zarza zona zorro zumo zurdo ` ) ================================================ FILE: util/downloader/chunk.go ================================================ package downloader import "fmt" type chunk struct { start, end int64 } func createChunks(contentLength, totalChunks int64) []*chunk { chunks := make([]*chunk, 0, totalChunks) chunkSize := contentLength / totalChunks for i := int64(0); i < totalChunks; i++ { start := i * chunkSize end := start + chunkSize - 1 // adjust the end for the last chunk if i == totalChunks-1 { end = contentLength - 1 } chunks = append(chunks, &chunk{start: start, end: end}) } return chunks } func (c *chunk) rangeHeader() string { return fmt.Sprintf("bytes=%d-%d", c.start, c.end) } func (c *chunk) size() int64 { return (c.end + 1) - c.start } ================================================ FILE: util/downloader/chunk_test.go ================================================ package downloader import ( "testing" "github.com/stretchr/testify/assert" ) func TestCreateChunks(t *testing.T) { tests := []struct { contentLength int64 totalChunks int64 expected []*chunk }{ { contentLength: 181403648, totalChunks: 16, expected: []*chunk{ {start: 0, end: 11337727}, {start: 11337728, end: 22675455}, {start: 22675456, end: 34013183}, {start: 34013184, end: 45350911}, {start: 45350912, end: 56688639}, {start: 56688640, end: 68026367}, {start: 68026368, end: 79364095}, {start: 79364096, end: 90701823}, {start: 90701824, end: 102039551}, {start: 102039552, end: 113377279}, {start: 113377280, end: 124715007}, {start: 124715008, end: 136052735}, {start: 136052736, end: 147390463}, {start: 147390464, end: 158728191}, {start: 158728192, end: 170065919}, {start: 170065920, end: 181403647}, }, }, { contentLength: 10, totalChunks: 3, expected: []*chunk{ {start: 0, end: 2}, {start: 3, end: 5}, {start: 6, end: 9}, }, }, { contentLength: 10, totalChunks: 1, expected: []*chunk{ {start: 0, end: 9}, }, }, { contentLength: 0, totalChunks: 1, expected: []*chunk{ {start: 0, end: -1}, }, }, } for _, tt := range tests { actual := createChunks(tt.contentLength, tt.totalChunks) assert.Equal(t, tt.expected, actual) } } func TestChunkRangeHeader(t *testing.T) { tests := []struct { chunk chunk expected string }{ { chunk: chunk{start: 0, end: 499}, expected: "bytes=0-499", }, { chunk: chunk{start: 500, end: 999}, expected: "bytes=500-999", }, } for _, tt := range tests { actual := tt.chunk.rangeHeader() assert.Equal(t, tt.expected, actual) } } func TestChunkSize(t *testing.T) { tests := []struct { chunk chunk expected int64 }{ { chunk: chunk{start: 0, end: 499}, expected: 500, }, { chunk: chunk{start: 500, end: 999}, expected: 500, }, { chunk: chunk{start: 0, end: 0}, expected: 1, }, } for _, tt := range tests { actual := tt.chunk.size() assert.Equal(t, tt.expected, actual) } } ================================================ FILE: util/downloader/downloader.go ================================================ package downloader import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "net/http" "os" "path/filepath" "sync" "github.com/pactus-project/pactus/util/logger" ) const ( _defaultConcurrencyPerChunk = 16 _defaultMinSizeForChunk = 1 << 20 _defaultMaxRetries = 3 ) type Downloader struct { client *http.Client url string filePath string sha256Sum string fileType string fileName string maxRetries int cancel context.CancelFunc statsCallback func(Stats) chunks []*chunk mu sync.Mutex downloaded int64 } type Stats struct { Downloaded int64 TotalSize int64 Percent float64 Completed bool } func New(url, filePath, sha256Sum string, opts ...Option) *Downloader { opt := defaultOptions() for _, o := range opts { o(opt) } return &Downloader{ client: opt.client, statsCallback: opt.statsCallBack, url: url, filePath: filePath, sha256Sum: sha256Sum, chunks: make([]*chunk, 0, _defaultConcurrencyPerChunk), maxRetries: opt.maxRetries, } } func (d *Downloader) Start(ctx context.Context) { d.download(ctx) } func (d *Downloader) FileType() string { return d.fileType } func (d *Downloader) FileName() string { return d.fileName } func (d *Downloader) download(ctx context.Context) { ctx, cancel := context.WithCancel(ctx) d.cancel = cancel totalSize, err := d.getHeader(ctx) if err != nil { d.handleError(err) return } d.fileName = filepath.Base(d.filePath) if err := d.createDir(); err != nil { d.handleError(err) return } out, err := os.OpenFile(d.filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) if err != nil { d.handleError(err) return } defer func() { _ = out.Close() }() d.updateStats(0, totalSize, false) var wg sync.WaitGroup for _, chk := range d.chunks { wg.Go(func() { if err := d.downloadChunk(ctx, out, chk, totalSize); err != nil { d.handleError(err) } }) } wg.Wait() if ctx.Err() != nil { return } if err := d.finalizeDownload(); err != nil { d.handleError(err) return } } func (d *Downloader) getHeader(ctx context.Context) (int64, error) { req, err := http.NewRequestWithContext(ctx, http.MethodHead, d.url, http.NoBody) if err != nil { return 0, &Error{Message: "failed to create new request for get header", Reason: err} } resp, err := d.client.Do(req) if err != nil { return 0, &Error{Message: "failed to do request get header", Reason: err} } defer func() { _ = resp.Body.Close() }() d.fileType = resp.Header.Get("Content-Type") if resp.ContentLength > _defaultMinSizeForChunk { d.chunks = createChunks(resp.ContentLength, _defaultConcurrencyPerChunk) } else { d.chunks = append(d.chunks, &chunk{ start: 0, end: resp.ContentLength, }) } return resp.ContentLength, nil } func (d *Downloader) createDir() error { dir := filepath.Dir(d.filePath) if err := os.MkdirAll(dir, 0o750); err != nil { return &Error{Message: "failed to create file path directory", Reason: err} } return nil } func (d *Downloader) downloadChunk(ctx context.Context, out *os.File, chk *chunk, totalSize int64) error { var err error for i := 0; i < d.maxRetries; i++ { err = d.downloadChunkWithContext(ctx, out, chk, totalSize) if err == nil || ctx.Err() != nil { return err } } return err } func (d *Downloader) downloadChunkWithContext(ctx context.Context, out *os.File, chk *chunk, totalSize int64) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.url, http.NoBody) if err != nil { return &Error{Message: "failed to create new request for download chunk", Reason: err} } req.Header.Set("Range", chk.rangeHeader()) resp, err := d.client.Do(req) if err != nil { return &Error{Message: "failed to do request download chunk", Reason: err} } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusPartialContent && resp.StatusCode != http.StatusOK { return &Error{ Message: "response has invalid status code", Reason: fmt.Errorf("got http response %s from %s: %w", resp.Status, d.url, err), } } buf := make([]byte, 32*1024) // 32KB buffer for reading the response body offset := chk.start for { count, err := resp.Body.Read(buf) if count > 0 { d.mu.Lock() for written := 0; written < count; { numBytes, err := out.WriteAt(buf[written:count], offset+int64(written)) if err != nil { d.mu.Unlock() return &Error{Message: "failed write data into file", Reason: err} } written += numBytes } offset += int64(count) d.downloaded += int64(count) d.updateStats(d.downloaded, totalSize, false) d.mu.Unlock() } if err != nil { // if error is io.EOF stop write for loop response body. if errors.Is(err, io.EOF) { break } return &Error{Message: "error read body download chunk", Reason: err} } } return nil } func (d *Downloader) updateStats(downloaded, totalSize int64, completed bool) { if d.statsCallback != nil { if downloaded > totalSize { // In case of re-downloading a chunk... downloaded = totalSize } stats := Stats{ Downloaded: downloaded, TotalSize: totalSize, Percent: float64(downloaded) / float64(totalSize) * 100, } if completed { stats.Completed = true } d.statsCallback(stats) } } func (d *Downloader) finalizeDownload() error { // Recalculate the hash by re-reading the entire file out, err := os.Open(d.filePath) if err != nil { return &Error{Message: "failed to open file", Reason: err} } defer func() { _ = out.Close() }() hasher := sha256.New() if _, err := io.Copy(hasher, out); err != nil { return &Error{Message: "failed copy file data to hasher for calculate hash", Reason: err} } sum := hex.EncodeToString(hasher.Sum(nil)) if sum != d.sha256Sum { return &Error{Message: "sha256 mismatch", Reason: fmt.Errorf("expected %s, got %s", d.sha256Sum, sum)} } d.updateStats(0, 0, true) return nil } func (d *Downloader) handleError(err error) { logger.Error("failed to download", "error", err) if d.cancel != nil { d.cancel() } } ================================================ FILE: util/downloader/downloader_test.go ================================================ package downloader import ( "context" "crypto/sha256" "encoding/hex" "fmt" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/pactus-project/pactus/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDownloader(t *testing.T) { fileContent := make([]byte, 1*1024*1024) // 1 MB for i := range fileContent { fileContent[i] = byte(i % 256) } fileURL := "/testfile" expectedSHA256 := sha256.Sum256(fileContent) expectedSHA256Hex := hex.EncodeToString(expectedSHA256[:]) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == fileURL { w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileContent))) _, err := w.Write(fileContent) assert.NoError(t, err) } else { http.NotFound(w, r) } })) defer server.Close() filePath := util.TempFilePath() defer func() { require.NoError(t, os.RemoveAll("./testdata")) }() downloader := New(server.URL+fileURL, filePath, expectedSHA256Hex, WithCustomClient(server.Client()), WithStatsCallback(printDownloaderStats), ) ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) defer cancel() downloader.Start(ctx) t.Log(downloader.FileName()) t.Log(downloader.FileType()) downloadedContent, err := os.ReadFile(filePath) require.NoError(t, err, "Failed to read the downloaded file") assert.Equal(t, fileContent, downloadedContent, "Downloaded file content does not match expected content") } func printDownloaderStats(sts Stats) { if !sts.Completed { fmt.Printf("Downloaded: %d / %d (%.2f%%)\n", sts.Downloaded, sts.TotalSize, sts.Percent) } } ================================================ FILE: util/downloader/errors.go ================================================ package downloader import ( "fmt" ) type Error struct { Message string Reason error } func (e *Error) Error() string { return fmt.Sprintf("%s: %s", e.Message, e.Reason.Error()) } func (e *Error) Unwrap() error { return e.Reason } ================================================ FILE: util/downloader/options.go ================================================ package downloader import "net/http" type options struct { client *http.Client statsCallBack func(Stats) maxRetries int } type Option func(*options) func defaultOptions() *options { return &options{ client: http.DefaultClient, maxRetries: _defaultMaxRetries, } } func WithCustomClient(client *http.Client) Option { return func(o *options) { o.client = client } } func WithMaxRetries(n int) Option { return func(o *options) { if n > 0 { o.maxRetries = n } } } func WithStatsCallback(cb func(Stats)) Option { return func(opt *options) { opt.statsCallBack = cb } } ================================================ FILE: util/encoding/encoding.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package encoding import ( "encoding/binary" "errors" "fmt" "io" "github.com/pactus-project/pactus/crypto/hash" ) const ( // MaxPayloadSize is the maximum bytes a message can be regardless of other // individual limits imposed by messages themselves. MaxPayloadSize = 1024 * 1024 * 32 // 32MB // binaryFreeListMaxItems is the number of buffers to keep in the free // list to use for binary serialization and deserialization. binaryFreeListMaxItems = 1024 ) var ( ErrOverflow = errors.New("overflow") ErrNonCanonical = errors.New("non canonical") ) // binaryFreeList defines a concurrent safe free list of byte slices (up to the // maximum number defined by the binaryFreeListMaxItems constant) that have a // cap of 8 (thus it supports up to a uint64). It is used to provide temporary // buffers for serializing and deserializing primitive numbers to and from their // binary encoding in order to greatly reduce the number of allocations // required. // // For convenience, functions are provided for each of the primitive unsigned // integers that automatically obtain a buffer from the free list, perform the // necessary binary conversion, read from or write to the given io.Reader or // io.Writer, and return the buffer to the free list. type binaryFreeList chan []byte // Borrow returns a byte slice from the free list with a length of 8. A new // buffer is allocated if there are not any available on the free list. func (l binaryFreeList) Borrow() []byte { var buf []byte select { case buf = <-l: default: buf = make([]byte, 8) } return buf[:8] } // Return puts the provided byte slice back on the free list. The buffer MUST // have been obtained via the Borrow function and therefore have a cap of 8. func (l binaryFreeList) Return(buf []byte) { select { case l <- buf: default: // Let it go to the garbage collector. } } // Uint8 reads a single byte from the provided reader using a buffer from the // free list. func (l binaryFreeList) Uint8(r io.Reader, val *uint8) error { buf := l.Borrow()[:1] if _, err := io.ReadFull(r, buf); err != nil { l.Return(buf) return err } *val = buf[0] l.Return(buf) return nil } // Uint16 reads two bytes from the provided reader using a buffer from the // free list, converts it to a number in little endian byte order. func (l binaryFreeList) Uint16(r io.Reader, val *uint16) error { buf := l.Borrow()[:2] if _, err := io.ReadFull(r, buf); err != nil { l.Return(buf) return err } *val = binary.LittleEndian.Uint16(buf) l.Return(buf) return nil } // Uint32 reads four bytes from the provided reader using a buffer from the // free list, converts it to a number in little endian byte order. func (l binaryFreeList) Uint32(r io.Reader, val *uint32) error { buf := l.Borrow()[:4] if _, err := io.ReadFull(r, buf); err != nil { l.Return(buf) return err } *val = binary.LittleEndian.Uint32(buf) l.Return(buf) return nil } // Uint64 reads eight bytes from the provided reader using a buffer from the // free list, converts it to a number in little endian byte order.. func (l binaryFreeList) Uint64(r io.Reader, val *uint64) error { buf := l.Borrow()[:8] if _, err := io.ReadFull(r, buf); err != nil { l.Return(buf) return err } *val = binary.LittleEndian.Uint64(buf) l.Return(buf) return nil } // PutUint8 copies the provided uint8 into a buffer from the free list and // writes the resulting byte to the given writer. func (l binaryFreeList) PutUint8(w io.Writer, val uint8) error { buf := l.Borrow()[:1] buf[0] = val _, err := w.Write(buf) l.Return(buf) return err } // PutUint16 serializes the provided uint16 using the given byte order into a // buffer from the free list and writes the resulting two bytes to the given // writer. func (l binaryFreeList) PutUint16(w io.Writer, val uint16) error { buf := l.Borrow()[:2] binary.LittleEndian.PutUint16(buf, val) _, err := w.Write(buf) l.Return(buf) return err } // PutUint32 serializes the provided uint32 using the given byte order into a // buffer from the free list and writes the resulting four bytes to the given // writer. func (l binaryFreeList) PutUint32(w io.Writer, val uint32) error { buf := l.Borrow()[:4] binary.LittleEndian.PutUint32(buf, val) _, err := w.Write(buf) l.Return(buf) return err } // PutUint64 serializes the provided uint64 using the given byte order into a // buffer from the free list and writes the resulting eight bytes to the given // writer. func (l binaryFreeList) PutUint64(w io.Writer, val uint64) error { buf := l.Borrow()[:8] binary.LittleEndian.PutUint64(buf, val) _, err := w.Write(buf) l.Return(buf) return err } // binarySerializer provides a free list of buffers to use for serializing and // deserializing primitive integer values to and from io.Readers and io.Writers. var binarySerializer binaryFreeList = make(chan []byte, binaryFreeListMaxItems) // ReadElement reads the next sequence of bytes from r using little endian // depending on the concrete type of element pointed to. func ReadElement(r io.Reader, elm any) error { // Attempt to read the element based on the concrete type via fast // type assertions first. var err error switch elm := elm.(type) { case *bool: val := uint8(0) err = binarySerializer.Uint8(r, &val) *elm = val != 0x00 case *int8: val := uint8(0) err = binarySerializer.Uint8(r, &val) *elm = int8(val) case *uint8: err = binarySerializer.Uint8(r, elm) case *int16: val := uint16(0) err = binarySerializer.Uint16(r, &val) *elm = int16(val) case *uint16: err = binarySerializer.Uint16(r, elm) case *int32: rv := uint32(0) err = binarySerializer.Uint32(r, &rv) *elm = int32(rv) case *uint32: err = binarySerializer.Uint32(r, elm) case *int64: val := uint64(0) err = binarySerializer.Uint64(r, &val) *elm = int64(val) case *uint64: err = binarySerializer.Uint64(r, elm) case *hash.Hash: _, err = io.ReadFull(r, elm[:]) default: // Fall back to the slower binary.Read if a fast path was not available // above. err = binary.Read(r, binary.LittleEndian, elm) } return err } // ReadElements reads multiple items from r. It is equivalent to multiple // calls to readElement. func ReadElements(r io.Reader, elms ...any) error { for _, element := range elms { err := ReadElement(r, element) if err != nil { return err } } return nil } // WriteElement writes the little endian representation of element to w. func WriteElement(w io.Writer, elm any) error { // Attempt to write the element based on the concrete type via fast // type assertions first. var err error switch elm := elm.(type) { case bool: if elm { err = binarySerializer.PutUint8(w, 0x01) } else { err = binarySerializer.PutUint8(w, 0x00) } case int8: err = binarySerializer.PutUint8(w, uint8(elm)) case uint8: err = binarySerializer.PutUint8(w, elm) case int16: err = binarySerializer.PutUint16(w, uint16(elm)) case uint16: err = binarySerializer.PutUint16(w, elm) case int32: err = binarySerializer.PutUint32(w, uint32(elm)) case uint32: err = binarySerializer.PutUint32(w, elm) case int64: err = binarySerializer.PutUint64(w, uint64(elm)) case uint64: err = binarySerializer.PutUint64(w, elm) case *hash.Hash: _, err = w.Write(elm[:]) default: // Fall back to the slower binary.Write if a fast path was not available // above. err = binary.Write(w, binary.LittleEndian, elm) } return err } // WriteElements writes multiple items to w. It is equivalent to multiple // calls to writeElement. func WriteElements(w io.Writer, elements ...any) error { for _, element := range elements { err := WriteElement(w, element) if err != nil { return err } } return nil } // ReadVarInt reads a variable length integer from r and returns it as a uint64. func ReadVarInt(r io.Reader) (uint64, error) { bits := 64 write := uint64(0) for shift := 0; ; shift += 7 { byt := uint8(0) err := binarySerializer.Uint8(r, &byt) if err != nil { return 0, err } if shift+7 >= bits && byt >= 1<<(bits-shift) { return uint64(0), ErrOverflow } if byt == 0 && shift != 0 { return uint64(0), ErrNonCanonical } write |= uint64(byt&0x7f) << shift // Does the actually placing into write, stripping the first bit // If there is no next if (byt & 0x80) == 0 { break } } return write, nil } // WriteVarInt serializes val to w using a variable number of bytes depending // on its value. func WriteVarInt(w io.Writer, val uint64) error { // Make sure that there is one after this for val >= 0x80 { n := (uint8(val) & 0x7f) | 0x80 err := binarySerializer.PutUint8(w, n) if err != nil { return err } val >>= 7 // It should be in multiples of 7, this should just get the next part } return binarySerializer.PutUint8(w, uint8(val)) } // VarIntSerializeSize returns the number of bytes it would take to serialize // val as a variable length integer. func VarIntSerializeSize(val uint64) int { switch { case val >= 0x8000000000000000: return 10 case val >= 0x100000000000000: return 9 case val >= 0x2000000000000: return 8 case val >= 0x40000000000: return 7 case val >= 0x800000000: return 6 case val >= 0x10000000: return 5 case val >= 0x200000: return 4 case val >= 0x4000: return 3 case val >= 0x80: return 2 default: return 1 } } // VarStringSerializeSize returns the number of bytes it would take to serialize // val as a string. func VarStringSerializeSize(str string) int { return VarIntSerializeSize(uint64(len(str))) + len(str) } // VarBytesSerializeSize returns the number of bytes it would take to serialize // val as a byte array. func VarBytesSerializeSize(bytes []byte) int { return VarIntSerializeSize(uint64(len(bytes))) + len(bytes) } // ReadVarString reads a variable length string from r and returns it as a Go // string. A variable length string is encoded as a variable length integer // containing the length of the string followed by the bytes that represent the // string itself. An error is returned if the length is greater than the // maximum payload size since it helps protect against memory exhaustion // attacks and forced panics through malformed messages. func ReadVarString(r io.Reader) (string, error) { count, err := ReadVarInt(r) if err != nil { return "", err } // Prevent variable length strings that are larger than the maximum // payload size. It would be possible to cause memory exhaustion and // panics without a sane upper bound on this count. if count > MaxPayloadSize { return "", fmt.Errorf("variable length string is too long "+ "[count %d, max %d]", count, MaxPayloadSize) } buf := make([]byte, count) _, err = io.ReadFull(r, buf) if err != nil { return "", err } return string(buf), nil } // WriteVarString serializes str to w as a variable length integer containing // the length of the string followed by the bytes that represent the string // itself. func WriteVarString(w io.Writer, str string) error { err := WriteVarInt(w, uint64(len(str))) if err != nil { return err } _, err = w.Write([]byte(str)) return err } // ReadVarBytes reads a variable length byte array. A byte array is encoded // as a varInt containing the length of the array followed by the bytes // themselves. An error is returned if the length is greater than the // maximum payload size since it helps protect against memory exhaustion // attacks and forced panics through malformed messages. func ReadVarBytes(r io.Reader) ([]byte, error) { count, err := ReadVarInt(r) if err != nil { return nil, err } // Prevent byte array larger than the max message size. It would // be possible to cause memory exhaustion and panics without a sane // upper bound on this count. if count > uint64(MaxPayloadSize) { return nil, fmt.Errorf("variable length byte array is too long "+ "[count %d, max %d]", count, MaxPayloadSize) } buf := make([]byte, count) _, err = io.ReadFull(r, buf) if err != nil { return nil, err } return buf, nil } // WriteVarBytes serializes a variable length byte array to w as a varInt // containing the number of bytes, followed by the bytes themselves. func WriteVarBytes(w io.Writer, bytes []byte) error { slen := uint64(len(bytes)) err := WriteVarInt(w, slen) if err != nil { return err } _, err = w.Write(bytes) return err } ================================================ FILE: util/encoding/encoding_test.go ================================================ // This file contains code modified from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package encoding import ( "bytes" "crypto/rand" "io" "math/big" "reflect" "strings" "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestElementEncoding tests encode and decode for various element types. This // is mainly to test the "fast" paths in readElement and writeElement which use // type assertions to avoid reflection when possible. func TestElementEncoding(t *testing.T) { type writeElementReflect int32 tests := []struct { in any // Value to encode buf []byte // encoding bytes }{ {int8(-128), []byte{0x80}}, {int8(127), []byte{0x7f}}, {uint8(1), []byte{0x01}}, {int16(-32256), []byte{0x00, 0x82}}, {int16(127), []byte{0x7f, 0x00}}, {uint16(65535), []byte{0xff, 0xff}}, {int32(-1), []byte{0xff, 0xff, 0xff, 0xff}}, {int32(1), []byte{0x01, 0x00, 0x00, 0x00}}, {uint32(256), []byte{0x00, 0x01, 0x00, 0x00}}, {int64(-65536), []byte{0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {int64(65536), []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}}, {uint64(4294967296), []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}}, {true, []byte{0x01}}, {false, []byte{0x00}}, { &hash.Hash{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, }, []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, }, }, // Type not supported by the "fast" path and requires reflection. { writeElementReflect(1), []byte{0x01, 0x00, 0x00, 0x00}, }, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { var buf bytes.Buffer err := WriteElement(&buf, tt.in) require.NoError(t, err, "writeElement #%d", no) assert.Equal(t, buf.Bytes(), tt.buf, "writeElement #%d", no) rbuf := bytes.NewReader(tt.buf) val := tt.in if reflect.ValueOf(tt.in).Kind() != reflect.Ptr { val = reflect.New(reflect.TypeOf(tt.in)).Interface() } err = ReadElement(rbuf, val) require.NoError(t, err, "readElement #%d", no) ival := val if reflect.ValueOf(tt.in).Kind() != reflect.Ptr { ival = reflect.Indirect(reflect.ValueOf(val)).Interface() } assert.Equal(t, ival, tt.in, "readElement #%d", no) } } // TestElementEncodingErrors performs negative tests against encode and decode // of various element types to confirm error paths work correctly. func TestElementEncodingErrors(t *testing.T) { tests := []struct { in any // Value to encode max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error }{ {int8(127), 0, io.ErrShortWrite, io.EOF}, {uint8(1), 0, io.ErrShortWrite, io.EOF}, {int16(127), 1, io.ErrShortWrite, io.ErrUnexpectedEOF}, {uint16(256), 1, io.ErrShortWrite, io.ErrUnexpectedEOF}, {int32(256), 3, io.ErrShortWrite, io.ErrUnexpectedEOF}, {uint32(256), 3, io.ErrShortWrite, io.ErrUnexpectedEOF}, {int64(65536), 7, io.ErrShortWrite, io.ErrUnexpectedEOF}, {uint64(4294967296), 7, io.ErrShortWrite, io.ErrUnexpectedEOF}, {true, 0, io.ErrShortWrite, io.EOF}, {false, 0, io.ErrShortWrite, io.EOF}, { &hash.Hash{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, }, 0, io.ErrShortWrite, io.EOF, }, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { w := util.NewFixedWriter(tt.max) err := WriteElement(w, tt.in) require.ErrorIs(t, err, tt.writeErr, "writeElement #%d", no) r := util.NewFixedReader(tt.max, nil) val := tt.in if reflect.ValueOf(tt.in).Kind() != reflect.Ptr { val = reflect.New(reflect.TypeOf(tt.in)).Interface() } err = ReadElement(r, val) require.ErrorIs(t, err, tt.readErr, "readElement #%d", no) } } // TestVarStringEncoding tests encode and decode for variable length strings. func TestVarStringEncoding(t *testing.T) { // str256 is a string that takes a 2-byte varint to encode. str256 := strings.Repeat("test", 64) tests := []struct { in string // String to encode out string // String to decoded value buf []byte // Encoding bytes }{ // Latest protocol version. // Empty string {"", "", []byte{0x00}}, // Single byte varint + string {"Test", "Test", append([]byte{0x04}, []byte("Test")...)}, // 2-byte varint + string {str256, str256, append([]byte{0x80, 0x02}, []byte(str256)...)}, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { var buf bytes.Buffer err := WriteVarString(&buf, tt.in) require.NoError(t, err, "WriteVarString #%d ", no) assert.Equal(t, buf.Bytes(), tt.buf, "WriteVarString #%d", no) rbuf := bytes.NewReader(tt.buf) val, err := ReadVarString(rbuf) require.NoError(t, err, "ReadVarString #%d", no) assert.Equal(t, val, tt.out, "ReadVarString #%d", no) assert.Len(t, tt.buf, VarStringSerializeSize(tt.in)) } } // TestVarStringEncodingErrors performs negative tests against encode and // decode of variable length strings to confirm error paths work correctly. func TestVarStringEncodingErrors(t *testing.T) { // str256 is a string that takes a 2-byte varint to encode. str256 := strings.Repeat("test", 64) tests := []struct { in string // Value to encode buf []byte // Encoding bytes max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error }{ // Latest protocol version with intentional read/write errors. // Force errors on empty string. {"", []byte{0x00}, 0, io.ErrShortWrite, io.EOF}, // Force error on single byte varint + string. {"Test", []byte{0x04}, 2, io.ErrShortWrite, io.ErrUnexpectedEOF}, // Force errors on 2-byte varint + string. {str256, []byte{0x80}, 1, io.ErrShortWrite, io.EOF}, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { w := util.NewFixedWriter(tt.max) err := WriteVarString(w, tt.in) require.ErrorIs(t, err, tt.writeErr, "WriteVarString #%d", no) r := util.NewFixedReader(tt.max, tt.buf) _, err = ReadVarString(r) require.ErrorIs(t, err, tt.readErr, "ReadVarString #%d wrong", no) } } // TestVarStringOverflowErrors performs tests to ensure deserializing variable // length strings intentionally crafted to use large values for the string // length are handled properly. This could otherwise potentially be used as an // attack vector. func TestVarStringOverflowErrors(t *testing.T) { tests := []struct { buf []byte // Encoding bytes }{ {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {[]byte{0x80, 0x80, 0x80, 0x11}}, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { rbuf := bytes.NewReader(tt.buf) _, err := ReadVarString(rbuf) assert.Contains(t, err.Error(), "variable length string is too long", "ReadVarString #%d", no) } } // TestVarBytesEncoding tests encode and decode for variable length byte array. func TestVarBytesEncoding(t *testing.T) { // bytes256 is a byte array that takes a 2-byte varint to encode. bytes256 := bytes.Repeat([]byte{0x01}, 256) tests := []struct { in []byte // Byte Array to write buf []byte // Encoding bytes }{ // Latest protocol version. // Empty byte array {[]byte{}, []byte{0x00}}, // Single byte varint + byte array {[]byte{0x01}, []byte{0x01, 0x01}}, // 2-byte varint + byte array {bytes256, append([]byte{0x80, 0x02}, bytes256...)}, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { var buf bytes.Buffer err := WriteVarBytes(&buf, tt.in) require.NoError(t, err, "WriteVarBytes #%d", no) assert.Equal(t, buf.Bytes(), tt.buf, "WriteVarBytes #%d", no) rbuf := bytes.NewReader(tt.buf) val, err := ReadVarBytes(rbuf) require.NoError(t, err, "ReadVarBytes #%d", no) assert.Equal(t, buf.Bytes(), tt.buf, "ReadVarBytes #%d", no) assert.Equal(t, val, tt.in, "ReadVarBytes #%d", no) assert.Len(t, tt.buf, VarBytesSerializeSize(tt.in)) } } // TestVarBytesEncodingErrors performs negative tests against encode and // decode of variable length byte arrays to confirm error paths work correctly. func TestVarBytesEncodingErrors(t *testing.T) { // bytes256 is a byte array that takes a 2-byte varint to encode. bytes256 := bytes.Repeat([]byte{0x01}, 256) tests := []struct { in []byte // Byte Array to write buf []byte // Encoding bytes max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error }{ // Latest protocol version with intentional read/write errors. // Force errors on empty byte array. {[]byte{}, []byte{0x00}, 0, io.ErrShortWrite, io.EOF}, // Force error on single byte varint + byte array. {[]byte{0x01, 0x02, 0x03}, []byte{0x04}, 2, io.ErrShortWrite, io.ErrUnexpectedEOF}, // Force errors on 2-byte varint + byte array. {bytes256, []byte{0x80}, 1, io.ErrShortWrite, io.EOF}, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { w := util.NewFixedWriter(tt.max) err := WriteVarBytes(w, tt.in) require.ErrorIs(t, err, tt.writeErr, "WriteVarBytes #%d", no) r := util.NewFixedReader(tt.max, tt.buf) _, err = ReadVarBytes(r) require.ErrorIs(t, err, tt.readErr, "ReadVarBytes #%d", no) } } // TestVarBytesOverflowErrors performs tests to ensure deserializing variable // length byte arrays intentionally crafted to use large values for the array // length are handled properly. This could otherwise potentially be used as an // attack vector. func TestVarBytesOverflowErrors(t *testing.T) { tests := []struct { buf []byte }{ {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {[]byte{0x80, 0x80, 0x80, 0x11}}, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { rbuf := bytes.NewReader(tt.buf) _, err := ReadVarBytes(rbuf) assert.Contains(t, err.Error(), "variable length byte array is too long", "ReadVarString #%d", no) } } // TestVarInt performs tests to ensure deserializing variable integers are // handled properly. This could otherwise potentially be used as an attack // vector. func TestVarInt(t *testing.T) { tests := []struct { in uint64 // Value to encode buf []byte // Encoded bytes }{ {uint64(0x0), []byte{0x00}}, {uint64(0xff), []byte{0xff, 0x01}}, {uint64(0x7fff), []byte{0xff, 0xff, 0x01}}, {uint64(0x3fffff), []byte{0xff, 0xff, 0xff, 0x01}}, {uint64(0x1fffffff), []byte{0xff, 0xff, 0xff, 0xff, 0x01}}, {uint64(0xfffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {uint64(0x7ffffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {uint64(0x3ffffffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {uint64(0x1ffffffffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {uint64(0xffffffffffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}, {uint64(0x200), []byte{0x80, 0x04}}, {uint64(0x027f), []byte{0xff, 0x04}}, {uint64(0xff00000000), []byte{0x80, 0x80, 0x80, 0x80, 0xf0, 0x1f}}, {uint64(0xffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0x0f}}, {uint64(0x100000000), []byte{0x80, 0x80, 0x80, 0x80, 0x10}}, {uint64(0x7ffffffff), []byte{0xff, 0xff, 0xff, 0xff, 0x7f}}, {uint64(0x800000000), []byte{0x80, 0x80, 0x80, 0x80, 0x80, 0x1}}, } for no, tt := range tests { var buf bytes.Buffer err := WriteVarInt(&buf, tt.in) require.NoError(t, err, "WriteVarInt #%d", no) assert.Equal(t, buf.Bytes(), tt.buf, "WriteVarInt #%d", no) val, err := ReadVarInt(&buf) require.NoError(t, err, "ReadVarInt #%d", no) assert.Equal(t, val, tt.in, "ReadVarInt #%d", no) assert.Len(t, tt.buf, VarIntSerializeSize(tt.in)) } } // TestVarIntError ensures variable length integers that are not encoded // properly return the expected error. func TestVarIntError(t *testing.T) { tests := []struct { in []byte // Value to decode readErr error }{ { []byte{0x98, 0}, ErrNonCanonical, }, { []byte{0xFF}, io.EOF, }, { []byte{0x80, 0x00}, ErrNonCanonical, }, { []byte{0x80, 0xfe}, io.EOF, }, { []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02}, ErrOverflow, }, { []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, ErrOverflow, }, } t.Logf("Running %d tests", len(tests)) for no, tt := range tests { rbuf := bytes.NewReader(tt.in) val, err := ReadVarInt(rbuf) require.ErrorIs(t, err, tt.readErr, "ReadVarInt #%d", no) assert.Zero(t, val, "ReadVarInt #%d", no) } } func TestVarIntRandom(t *testing.T) { max := new(big.Int).SetUint64(^uint64(0)) // max uint64 randIntBig, _ := rand.Int(rand.Reader, max) randInt1 := randIntBig.Uint64() var wBuf bytes.Buffer err := WriteVarInt(&wBuf, randInt1) require.NoError(t, err) rBuf := bytes.NewReader(wBuf.Bytes()) randInt2, err := ReadVarInt(rBuf) require.NoError(t, err) assert.Equal(t, randInt1, randInt2) } func TestWriteElements(t *testing.T) { el1 := uint8(1) el2 := uint16(2) el3 := uint32(3) el4 := uint64(4) var buf bytes.Buffer err := WriteElements(&buf, &el1, &el2, &el3, &el4) require.NoError(t, err) assert.Equal(t, []byte{0x1, 0x2, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, buf.Bytes()) } func TestReadElements(t *testing.T) { el1 := uint8(1) el2 := uint16(2) el3 := uint32(3) el4 := uint64(4) r := bytes.NewReader([]byte{0x1, 0x2, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}) err := ReadElements(r, &el1, &el2, &el3, &el4) require.NoError(t, err) assert.Equal(t, uint8(1), el1) assert.Equal(t, uint16(2), el2) assert.Equal(t, uint32(3), el3) assert.Equal(t, uint64(4), el4) } ================================================ FILE: util/htpasswd/htpasswd.go ================================================ package htpasswd import ( "context" "encoding/base64" "errors" "strings" "golang.org/x/crypto/bcrypt" "google.golang.org/grpc/metadata" ) const ( // passwordSeparator defines the separator used in basic auth credentials (username:password). passwordSeparator = ":" ) var ( ErrInvalidUser = errors.New("user is invalid") ErrFailedToParseBasicAuth = errors.New("the provided basic authentication credentials are invalid") ErrMetadataNotFound = errors.New("metadata not found") ErrAuthHeaderNotFound = errors.New("authorization header not found") ErrFailedToDecodeBasicAuth = errors.New("failed to decode authorization header") ErrAuthHeaderInvalidFormat = errors.New("invalid authorization header format") ErrInvalidPassword = errors.New("password is invalid") ) // CompareBasicAuth compares a stored credential (username:password_hash) with a provided username and password. // It uses bcrypt to securely compare the password hash stored in the credential with the provided password. func CompareBasicAuth(storedCredential, user, password string) error { storedUser, storedPasswordHash, err := ExtractBasicAuth(storedCredential) if err != nil { return err } if storedUser != user { return ErrInvalidUser } if err := bcrypt.CompareHashAndPassword([]byte(storedPasswordHash), []byte(password)); err != nil { return ErrInvalidPassword } return nil } // ExtractBasicAuth extracts the user and password or password hash from the given basic auth credential. // The credential should be in the form "user:password" or "user:password_hahs". func ExtractBasicAuth(basicAuthCredential string) (user, password string, err error) { parts := strings.SplitN(basicAuthCredential, passwordSeparator, 2) if len(parts) != 2 { return "", "", ErrFailedToParseBasicAuth } user = parts[0] password = parts[1] return user, password, nil } // ExtractBasicAuthFromContext extracts the user and password from the incoming context in gRPC request. func ExtractBasicAuthFromContext(ctx context.Context) (user, password string, err error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return "", "", ErrMetadataNotFound } authHeader, ok := md["authorization"] if !ok || len(authHeader) == 0 { return "", "", ErrAuthHeaderNotFound } auth := strings.TrimPrefix(authHeader[0], "Basic ") decoded, err := base64.StdEncoding.DecodeString(auth) if err != nil { return "", "", ErrFailedToDecodeBasicAuth } parts := strings.SplitN(string(decoded), ":", 2) if len(parts) != 2 { return "", "", ErrAuthHeaderInvalidFormat } return parts[0], parts[1], nil } ================================================ FILE: util/htpasswd/htpasswd_test.go ================================================ package htpasswd import ( "context" "encoding/base64" "testing" "github.com/stretchr/testify/require" "google.golang.org/grpc/metadata" ) func TestExtractBasicAuth(t *testing.T) { tests := []struct { input string user string encodedPassword string }{ { input: "user:$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", user: "user", encodedPassword: "$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", }, { input: "user1:$2y$10$/4EcZtrJUgivhcTJPGOz/uhQEUAQP.zvThFwIHwdjQT97iL4gWMri", user: "user1", encodedPassword: "$2y$10$/4EcZtrJUgivhcTJPGOz/uhQEUAQP.zvThFwIHwdjQT97iL4gWMri", }, { input: "user2:$2y$10$xXmx6BQv6re3P2sOAoPGNu/MJOwWxDtxtNzlEJ2qkUVRK6SqAXD9m", user: "user2", encodedPassword: "$2y$10$xXmx6BQv6re3P2sOAoPGNu/MJOwWxDtxtNzlEJ2qkUVRK6SqAXD9m", }, { input: "user3:$2y$10$eKLWzld7iMPrcyDqam8.Y.R1deeSUBWFD3P6eQHJ0Iqa1qR4yBxaq", user: "user3", encodedPassword: "$2y$10$eKLWzld7iMPrcyDqam8.Y.R1deeSUBWFD3P6eQHJ0Iqa1qR4yBxaq", }, } for _, tt := range tests { t.Run(tt.user, func(t *testing.T) { user, encodedPass, err := ExtractBasicAuth(tt.input) if err != nil { t.Fatal(err) } require.Equal(t, tt.input, user+":"+encodedPass) }) } } func TestCompareBasicAuth(t *testing.T) { tests := []struct { name string input string user string password string expectError error }{ { name: "SuccessfulAuthentication", input: "user:$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", // hashed 'foobar' user: "user", password: "foobar", expectError: nil, }, { name: "UserMismatch", input: "user:$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", user: "wronguser", password: "foobar", expectError: ErrInvalidUser, }, { name: "PasswordMismatch", input: "user:$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", user: "user", password: "wrongpassword", expectError: ErrInvalidPassword, }, { name: "MalformedCredential", input: "malformed", user: "user", password: "foobar", expectError: ErrFailedToParseBasicAuth, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := CompareBasicAuth(tt.input, tt.user, tt.password) if tt.expectError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectError) } }) } } func BenchmarkParseHtpasswd(b *testing.B) { auth := []string{ "user:$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", "user1:$2y$05$y9dWO1FBS34D7RSZSNZ6S.NjE3LMNBvSAwidgTrER/AHBNN9cBeR.", "user2:$2y$11$RuWzAY2N57m.iZuT9bUh2ufOj2nNd02BviZSVx2Hbid8PvonjPWRi", "user3:$2y$09$866UNklDooeXGSd6MI/XPu1Fg9.2nTX6dFnPsEdgtBY6HMF5.NhPq", } b.ReportAllocs() for b.Loop() { for _, a := range auth { _, _, err := ExtractBasicAuth(a) if err != nil { b.Fatal(err) } } } } func BenchmarkCompareBasicAuth(b *testing.B) { tests := []struct { input string user string password string }{ { input: "user:$2y$10$q6I6fxG2c79jBSXJ8L2jde15czipSRpu/uhW5Le.ooJLyfXiaPDZG", user: "user", password: "foobar", }, { input: "user1:$2y$05$y9dWO1FBS34D7RSZSNZ6S.NjE3LMNBvSAwidgTrER/AHBNN9cBeR.", user: "user1", password: "foobar1", }, { input: "user2:$2y$11$RuWzAY2N57m.iZuT9bUh2ufOj2nNd02BviZSVx2Hbid8PvonjPWRi", user: "user2", password: "foobar2", }, { input: "user3:$2y$09$866UNklDooeXGSd6MI/XPu1Fg9.2nTX6dFnPsEdgtBY6HMF5.NhPq", user: "user3", password: "foobar3", }, } b.ReportAllocs() for b.Loop() { for _, tt := range tests { _ = CompareBasicAuth(tt.input, tt.user, tt.password) } } } func TestExtractBasicAuthFromContext(t *testing.T) { tests := []struct { name string ctx context.Context wantUser string wantPass string expectError error }{ { name: "ValidCredentials", ctx: createTestContext("Basic " + base64.StdEncoding.EncodeToString([]byte("user:password"))), wantUser: "user", wantPass: "password", expectError: nil, }, { name: "InvalidEncoding", ctx: createTestContext("Basic user:password"), wantUser: "", wantPass: "", expectError: ErrFailedToDecodeBasicAuth, }, { name: "NoMetadata", ctx: t.Context(), wantUser: "", wantPass: "", expectError: ErrMetadataNotFound, }, { name: "NoAuthorizationHeader", ctx: metadata.NewIncomingContext(t.Context(), metadata.MD{}), wantUser: "", wantPass: "", expectError: ErrAuthHeaderNotFound, }, { name: "IncorrectFormat", ctx: createTestContext("Basic " + base64.StdEncoding.EncodeToString([]byte("userpassword"))), wantUser: "", wantPass: "", expectError: ErrAuthHeaderInvalidFormat, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { user, pass, err := ExtractBasicAuthFromContext(tt.ctx) if tt.expectError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectError) } if user != tt.wantUser || pass != tt.wantPass { t.Errorf("ExtractBasicAuthFromContext() got = %v, %v, want %v, %v", user, pass, tt.wantUser, tt.wantPass) } }) } } func createTestContext(authValue string) context.Context { md := metadata.New(map[string]string{"authorization": authValue}) return metadata.NewIncomingContext(context.Background(), md) } ================================================ FILE: util/io.go ================================================ package util import ( "bytes" "errors" "fmt" "io" "os" "path/filepath" "strings" ) func IsAbsPath(path string) bool { return filepath.IsAbs(path) } func MakeAbs(path string) string { if IsAbsPath(path) { return path } wd, err := os.Getwd() if err != nil { panic(err) } return filepath.Clean(filepath.Join(wd, path)) } func ReadFile(filename string) ([]byte, error) { return os.ReadFile(filename) } func WriteFile(filename string, data []byte) error { // create directory if err := Mkdir(filepath.Dir(filename)); err != nil { return err } if err := os.WriteFile(filename, data, 0o600); err != nil { return fmt.Errorf("failed to write to %s: %w", filename, err) } return nil } func Mkdir(path string) error { // create the directory if err := os.MkdirAll(path, 0o750); err != nil { return fmt.Errorf("could not create directory %s", path) } return nil } func IsDir(path string) bool { fi, err := os.Stat(path) if err != nil { return false } return fi.IsDir() } func PathExists(path string) bool { _, err := os.Stat(path) if os.IsNotExist(err) { return false } return err == nil } func TempDirPath() string { path, err := os.MkdirTemp("", "pactus*") if err != nil { panic(err) } return path } func TempFilePath() string { return filepath.Join(TempDirPath(), "file") } // IsDirEmpty checks if a directory is empty. func IsDirEmpty(path string) bool { file, err := os.Open(path) if err != nil { panic(err) } defer func() { _ = file.Close() }() // read in ONLY one file _, err = file.Readdir(1) // and if the file is EOF... well, the dir is empty. return errors.Is(err, io.EOF) } // IsDirNotExistsOrEmpty checks if the path exists and, if so, whether the directory is empty. func IsDirNotExistsOrEmpty(path string) bool { if !PathExists(path) { return true } return IsDirEmpty(path) } func IsValidDirPath(path string) bool { fi, err := os.Stat(path) if err == nil { if fi.IsDir() { if err := os.WriteFile(path+"/test", []byte{}, 0o600); err != nil { return false } _ = os.Remove(path + "/test") return true } return false } if err := Mkdir(path); err != nil { return false } _ = os.Remove(path) return true } // TODO: move these to a test suite // FixedWriter implements the io.Writer interface and intentionally allows // testing of error paths by forcing short writes. type FixedWriter struct { b []byte pos int } // Write writes the contents of p to w. When the contents of p would cause // the writer to exceed the maximum allowed size of the fixed writer, // io.ErrShortWrite is returned and the writer is left unchanged. // // This satisfies the io.Writer interface. func (w *FixedWriter) Write(data []byte) (int, error) { lenp := len(data) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } w.pos += copy(w.b[w.pos:], data) return lenp, nil } // Bytes returns the bytes already written to the fixed writer. func (w *FixedWriter) Bytes() []byte { return w.b } // NewFixedWriter returns a new io.Writer that will error once more bytes than // the specified max have been written. func NewFixedWriter(max int) *FixedWriter { b := make([]byte, max) fw := FixedWriter{b, 0} return &fw } // FixedReader implements the io.Reader interface and intentionally allows // testing of error paths by forcing short reads. type FixedReader struct { buf []byte pos int iobuf *bytes.Buffer } // Read reads the next len(p) bytes from the fixed reader. When the number of // bytes read would exceed the maximum number of allowed bytes to be read from // the fixed writer, an error is returned. // // This satisfies the io.Reader interface. func (fr *FixedReader) Read(p []byte) (int, error) { count, err := fr.iobuf.Read(p) if err != nil { return 0, err } fr.pos += count return count, nil } // NewFixedReader returns a new io.Reader that will error once more bytes than // the specified max have been read. func NewFixedReader(max int, data []byte) *FixedReader { buf := make([]byte, max) if data != nil { copy(buf, data) } iobuf := bytes.NewBuffer(buf) fr := FixedReader{buf, 0, iobuf} return &fr } // MoveDirectory moves a directory from srcDir to dstDir, including all its contents. // If dstDir already exists and is not empty, it returns an error. // If the parent directory of dstDir does not exist, it will be created. func MoveDirectory(srcDir, dstDir string) error { if PathExists(dstDir) { return fmt.Errorf("destination directory %s already exists", dstDir) } parentDir := filepath.Dir(dstDir) if err := Mkdir(parentDir); err != nil { return fmt.Errorf("failed to create parent directories for %s: %w", dstDir, err) } err := os.Rename(srcDir, dstDir) if err != nil { // To prevent invalid cross-device link perform a manual copy if err := copyDirectory(srcDir, dstDir); err != nil { return fmt.Errorf("failed to move directory from %s to %s: %w", srcDir, dstDir, err) } // Remove source directory after successful copy if err := os.RemoveAll(srcDir); err != nil { return fmt.Errorf("failed to remove source directory %s: %w", srcDir, err) } } return nil } func copyDirectory(src, dst string) error { return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } relPath, err := filepath.Rel(src, path) if err != nil { return err } dstPath := filepath.Join(dst, relPath) if info.IsDir() { return os.MkdirAll(dstPath, info.Mode()) } return copyFile(path, dstPath, info) }) } func copyFile(src, dst string, info os.FileInfo) error { input, err := os.Open(src) if err != nil { return err } defer func() { _ = input.Close() }() out, err := os.Create(dst) if err != nil { return err } defer func() { _ = out.Close() }() if _, err = io.Copy(out, input); err != nil { return err } // Preserve file permissions return os.Chmod(dst, info.Mode()) } // SanitizeArchivePath mitigates the "Zip Slip" vulnerability by sanitizing archive file paths. // It ensures that the file path is contained within the specified base directory to prevent directory // traversal attacks. For more details on the vulnerability, see https://snyk.io/research/zip-slip-vulnerability. func SanitizeArchivePath(baseDir, archivePath string) (fullPath string, err error) { fullPath = filepath.Join(baseDir, archivePath) if strings.HasPrefix(fullPath, filepath.Clean(baseDir)) { return fullPath, nil } return "", fmt.Errorf("%s: %s", "content filepath is tainted", archivePath) } type listFilesConfig struct { excludeDirs bool } var defaultListFilesConfig = listFilesConfig{ excludeDirs: false, } type ListFilesOption func(*listFilesConfig) // ExcludeDirectories prevents entering subdirectories. func ExcludeDirectories() ListFilesOption { return func(c *listFilesConfig) { c.excludeDirs = true } } // ListFilesInDir return list of files in directory. func ListFilesInDir(dir string, opts ...ListFilesOption) ([]string, error) { cfg := defaultListFilesConfig for _, opt := range opts { opt(&cfg) } files := make([]string, 0) entries, err := os.ReadDir(dir) if err != nil { return nil, err } for _, entry := range entries { if cfg.excludeDirs && entry.IsDir() { continue } fulPath := filepath.Join(dir, entry.Name()) files = append(files, fulPath) } return files, nil } // LimitReaderClose returns a ReadCloser that reads from r // but stops with EOF after n bytes. // The returned ReadCloser always forwards Close to r. // The underlying implementation is a *LimitedReadCloser. func LimitReaderClose(r io.ReadCloser, n int64) io.ReadCloser { return &LimitedReadCloser{R: r, N: n} } // LimitedReadCloser reads from R but limits the amount of // data returned to just N bytes. Each call to Read updates N // to reflect the new amount remaining. Read returns EOF when // N <= 0 or when the underlying R returns EOF. // Close always calls R.Close. type LimitedReadCloser struct { R io.ReadCloser // underlying reader with close support N int64 // max bytes remaining } func (l *LimitedReadCloser) Read(buf []byte) (n int, err error) { if l.N <= 0 { return 0, io.EOF } if int64(len(buf)) > l.N { buf = buf[:l.N] } n, err = l.R.Read(buf) l.N -= int64(n) return n, err } func (l *LimitedReadCloser) Close() error { return l.R.Close() } ================================================ FILE: util/io_test.go ================================================ package util import ( "bytes" "context" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const invalidDirName = "/invalid:path/\x00*folder?\\CON" func TestWriteFile(t *testing.T) { p := TempDirPath() d := []byte("some-data") require.NoError(t, WriteFile(p+"/d.dat", d)) require.NoError(t, WriteFile(p+"/another-folder/d.dat", d)) } func TestEmptyPath(t *testing.T) { p := TempDirPath() assert.Equal(t, p, MakeAbs(p)) assert.True(t, IsDirEmpty(p)) f := TempFilePath() d := []byte("pactus") require.NoError(t, WriteFile(f, d)) o, err := ReadFile(f) require.NoError(t, err) assert.Equal(t, d, o) } func TestAbsPath(t *testing.T) { abs := MakeAbs(".") assert.True(t, IsAbsPath(abs)) assert.False(t, IsAbsPath("abs")) assert.False(t, IsDirEmpty(abs)) assert.False(t, IsDirNotExistsOrEmpty(abs)) } func TestTempDir(t *testing.T) { tmpDir := TempDirPath() assert.True(t, IsAbsPath(tmpDir)) assert.True(t, IsDirEmpty(tmpDir)) assert.True(t, PathExists(tmpDir)) assert.True(t, IsDirNotExistsOrEmpty(tmpDir)) } func TestTempFile(t *testing.T) { tmpFile := TempFilePath() assert.True(t, IsAbsPath(tmpFile)) t.Run("Should panic because it doesn't exist", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("The code did not panic") } }() IsDirEmpty(tmpFile) }) assert.False(t, PathExists(tmpFile)) assert.True(t, IsDirNotExistsOrEmpty(tmpFile)) require.NoError(t, Mkdir(tmpFile)) assert.True(t, IsDirNotExistsOrEmpty(tmpFile)) assert.True(t, IsDirEmpty(tmpFile)) // no panic now } func isRoot() bool { cmd := exec.CommandContext(context.Background(), "id", "-u") output, err := cmd.Output() if err != nil { fmt.Println(err) } // 0 = root, 501 = non-root user i, err := strconv.Atoi(string(output[:len(output)-1])) if err != nil { fmt.Println(err) } return i == 0 } func TestIsValidPath(t *testing.T) { // To pass this tests inside docker if runtime.GOOS != "windows" && !isRoot() { assert.False(t, IsValidDirPath("/root")) assert.False(t, IsValidDirPath("/test")) } assert.False(t, IsValidDirPath(invalidDirName)) assert.False(t, IsValidDirPath("./io_test.go")) assert.True(t, IsValidDirPath("/tmp")) assert.True(t, IsValidDirPath("/tmp/pactus")) } func TestMoveDirectory(t *testing.T) { t.Run("DestinationDirectoryExistsAndNotEmpty", func(t *testing.T) { srcDir := TempDirPath() dstDir := TempDirPath() err := MoveDirectory(srcDir, dstDir) require.Error(t, err) assert.Contains(t, err.Error(), "destination directory") }) t.Run("ParentDirectoryCreationFailure", func(t *testing.T) { srcDir := TempDirPath() err := MoveDirectory(srcDir, invalidDirName) require.Error(t, err) assert.Contains(t, err.Error(), "failed to create parent directories") }) t.Run("SourceDirectoryRenameFailure", func(t *testing.T) { srcDir := TempDirPath() dstDir := TempDirPath() err := os.RemoveAll(dstDir) require.NoError(t, err) // Remove the source directory to simulate the rename failure err = os.RemoveAll(srcDir) require.NoError(t, err) err = MoveDirectory(srcDir, dstDir) require.Error(t, err) assert.Contains(t, err.Error(), "failed to move directory") }) t.Run("MoveDirectorySuccess", func(t *testing.T) { // Create temporary directories srcDir := TempDirPath() dstDir := TempDirPath() defer func() { _ = os.RemoveAll(srcDir) }() defer func() { _ = os.RemoveAll(dstDir) }() // Create a subdirectory in the source directory subDir := filepath.Join(srcDir, "subdir") err := Mkdir(subDir) require.NoError(t, err) // Create multiple files in the subdirectory files := []struct { name string content string }{ {"file1.txt", "content 1"}, {"file2.txt", "content 2"}, } for _, file := range files { filePath := filepath.Join(subDir, file.name) err = WriteFile(filePath, []byte(file.content)) require.NoError(t, err) } // Move the directory dstDirPath := filepath.Join(dstDir, "movedir") err = MoveDirectory(srcDir, dstDirPath) require.NoError(t, err) // Assert the source directory no longer exists assert.False(t, PathExists(srcDir)) // Assert the destination directory exists assert.True(t, PathExists(dstDirPath)) // Verify that all files have been moved and their contents are correct for _, file := range files { movedFilePath := filepath.Join(dstDirPath, "subdir", file.name) data, err := ReadFile(movedFilePath) require.NoError(t, err) assert.Equal(t, file.content, string(data)) } }) } func TestSanitizeArchivePath(t *testing.T) { if runtime.GOOS == "windows" { return } baseDir := "/safe/directory" tests := []struct { name string inputPath string expected string expectErr bool }{ {"Valid path", "file.txt", "/safe/directory/file.txt", false}, {"Valid path in subdirectory", "subdir/file.txt", "/safe/directory/subdir/file.txt", false}, {"Path with parent directory traversal", "../outside/file.txt", "", true}, {"Absolute path outside base directory", "/etc/passwd", "/safe/directory/etc/passwd", false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := SanitizeArchivePath(baseDir, tt.inputPath) if tt.expectErr { require.Error(t, err, "Expected error but got none") assert.Empty(t, result, "Expected empty result due to error") } else { require.NoError(t, err, "Unexpected error occurred") assert.Equal(t, tt.expected, result, "Sanitized path did not match expected") } }) } } func TestListFilesInDir(t *testing.T) { tmpDir := TempDirPath() file1Path := filepath.Join(tmpDir, "public_file") file1, err := os.Create(file1Path) require.NoError(t, err) require.NoError(t, file1.Close()) file2Path := filepath.Join(tmpDir, ".hidden_file") file2, err := os.Create(file2Path) require.NoError(t, err) require.NoError(t, file2.Close()) file3Path := filepath.Join(tmpDir, "directory") err = Mkdir(file3Path) require.NoError(t, err) file4Path := filepath.Join(file3Path, "file_in_directory") err = Mkdir(file4Path) require.NoError(t, err) t.Run("Exclude Directories", func(t *testing.T) { files, err := ListFilesInDir(tmpDir, ExcludeDirectories()) require.NoError(t, err) assert.Len(t, files, 2) assert.Contains(t, files, file1Path) assert.Contains(t, files, file2Path) }) t.Run("Include Directories", func(t *testing.T) { files, err := ListFilesInDir(tmpDir) require.NoError(t, err) assert.Len(t, files, 3) assert.Contains(t, files, file1Path) assert.Contains(t, files, file2Path) assert.Contains(t, files, file3Path) }) } func TestLimitReaderClose(t *testing.T) { // Helper to create a ReadCloser from a byte slice newReadCloser := func(data []byte) io.ReadCloser { return io.NopCloser(bytes.NewReader(data)) } t.Run("Read less than limit", func(t *testing.T) { data := []byte("hello world") limit := int64(5) r := LimitReaderClose(newReadCloser(data), limit) buf := make([]byte, 10) n, err := r.Read(buf) require.NoError(t, err) assert.Equal(t, int(limit), n) assert.Equal(t, data[:limit], buf[:n]) // Next read should return EOF n, err = r.Read(buf) assert.Equal(t, 0, n) assert.Equal(t, io.EOF, err) require.NoError(t, r.Close()) }) t.Run("Read exactly limit", func(t *testing.T) { data := []byte("hello world") limit := int64(len(data)) r := LimitReaderClose(newReadCloser(data), limit) buf := make([]byte, limit) n, err := r.Read(buf) require.NoError(t, err) assert.Equal(t, int(limit), n) assert.Equal(t, data, buf) n, err = r.Read(buf) assert.Equal(t, 0, n) assert.Equal(t, io.EOF, err) require.NoError(t, r.Close()) }) t.Run("Read with zero limit", func(t *testing.T) { data := []byte("hello world") r := LimitReaderClose(newReadCloser(data), 0) buf := make([]byte, 10) n, err := r.Read(buf) assert.Equal(t, 0, n) assert.Equal(t, io.EOF, err) require.NoError(t, r.Close()) }) t.Run("Underlying reader returns EOF before limit", func(t *testing.T) { data := []byte("short") limit := int64(10) r := LimitReaderClose(newReadCloser(data), limit) buf := make([]byte, 10) n, err := r.Read(buf) require.NoError(t, err) assert.Equal(t, len(data), n) assert.Equal(t, data, buf[:n]) n, err = r.Read(buf) assert.Equal(t, 0, n) assert.Equal(t, io.EOF, err) require.NoError(t, r.Close()) }) } func TestIsDir(t *testing.T) { assert.True(t, IsDir(TempDirPath())) assert.False(t, IsDir(TempFilePath())) } ================================================ FILE: util/ipblocker/ipblocker.go ================================================ package ipblocker import ( "net" ) type IPBlocker struct { cidrs []*net.IPNet } func New(bannedNets []string) (*IPBlocker, error) { ipBlocker := &IPBlocker{ cidrs: make([]*net.IPNet, 0), } for _, cidr := range bannedNets { _, ipNet, err := net.ParseCIDR(cidr) if err != nil { return nil, err } ipBlocker.cidrs = append(ipBlocker.cidrs, ipNet) } return ipBlocker, nil } func (i *IPBlocker) IsBanned(ip string) bool { parsedIP := net.ParseIP(ip) if parsedIP == nil { return false } // TODO: if scaled cidrs and ips items we can improve using trie or radix tree for _, cidr := range i.cidrs { if cidr.Contains(parsedIP) { return true } } return false } ================================================ FILE: util/ipblocker/ipblocker_test.go ================================================ package ipblocker import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNew(t *testing.T) { tests := []struct { name string bannedNets []string expectedError bool expectedLength int }{ { "Valid CIDRs", []string{"240e:390:8a1:ae80::/64", "192.168.1.0/24"}, false, 2, }, {"Invalid CIDR", []string{"invalid-cidr"}, true, 0}, {"Empty CIDRs", []string{}, false, 0}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ipBlocker, err := New(tt.bannedNets) if tt.expectedError { require.Error(t, err) } else { require.NoError(t, err) assert.Len(t, ipBlocker.cidrs, tt.expectedLength) } }) } } func TestIsBlocked(t *testing.T) { tests := []struct { name string bannedNets []string ip string expected bool }{ { "Blocked IPv6", []string{"240e:390:8a1:ae80::/64"}, "240e:390:8a1:ae80:7dbc:64b6:e84c:d2bf", true, }, { "Not Blocked IPv6", []string{"240e:390:8a1:ae80::/64"}, "240e:391:8a1:ae80:7dbc:64b6:e84c:d2bf", false, }, {"Blocked IPv4", []string{"192.168.1.0/24"}, "192.168.1.1", true}, {"Not Blocked IPv4", []string{"192.168.1.0/24"}, "10.0.0.1", false}, {"Empty CIDR List", []string{}, "192.168.1.1", false}, {"Invalid IP", []string{"192.168.1.0/24"}, "invalid-ip", false}, { "Blocked IPv4 in multiple CIDRs", []string{"10.0.0.0/8", "192.168.1.0/24"}, "192.168.1.1", true, }, { "Blocked IPv6 in multiple CIDRs", []string{"240e:390:8a1:ae80::/64", "2001:db8::/32"}, "2001:db8::1", true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ipBlocker, err := New(tt.bannedNets) require.NoError(t, err) result := ipBlocker.IsBanned(tt.ip) assert.Equal(t, tt.expected, result) }) } } ================================================ FILE: util/linkedlist/linkedlist.go ================================================ package linkedlist type Element[T any] struct { Data T Next *Element[T] Prev *Element[T] } func NewElement[T any](data T) *Element[T] { return &Element[T]{ Data: data, Next: nil, Prev: nil, } } // LinkedList represents a doubly linked list. type LinkedList[T any] struct { Head *Element[T] Tail *Element[T] length int } func New[T any]() *LinkedList[T] { return &LinkedList[T]{ Head: nil, Tail: nil, length: 0, } } // InsertAtHead inserts a new element at the head of the list. func (ll *LinkedList[T]) InsertAtHead(data T) *Element[T] { elm := NewElement(data) if ll.Head == nil { // Empty list case ll.Head = elm ll.Tail = elm } else { elm.Next = ll.Head ll.Head.Prev = elm ll.Head = elm } ll.length++ return elm } // InsertAtTail appends a new element at the tail of the list. func (ll *LinkedList[T]) InsertAtTail(data T) *Element[T] { elm := NewElement(data) if ll.Head == nil { // Empty list case ll.Head = elm ll.Tail = elm } else { elm.Prev = ll.Tail ll.Tail.Next = elm ll.Tail = elm } ll.length++ return elm } func (ll *LinkedList[T]) InsertBefore(data T, pos *Element[T]) *Element[T] { elm := NewElement[T](data) if pos == ll.Head { ll.Head = elm elm.Next = pos elm.Next.Prev = elm } else { elm.Prev = pos.Prev elm.Next = pos elm.Next.Prev = elm elm.Prev.Next = elm } ll.length++ return elm } func (ll *LinkedList[T]) InsertAfter(data T, pos *Element[T]) *Element[T] { elm := NewElement[T](data) if pos == ll.Tail { ll.Tail = elm elm.Prev = pos elm.Prev.Next = elm } else { elm.Prev = pos elm.Next = pos.Next elm.Prev.Next = elm elm.Next.Prev = elm } ll.length++ return elm } // DeleteAtHead deletes the element at the head of the list. func (ll *LinkedList[T]) DeleteAtHead() { if ll.Head == nil { // Empty list case return } ll.Head = ll.Head.Next if ll.Head != nil { ll.Head.Prev = nil } else { ll.Tail = nil } ll.length-- } // DeleteAtTail deletes the element at the tail of the list. func (ll *LinkedList[T]) DeleteAtTail() { if ll.Tail == nil { // Empty list case return } ll.Tail = ll.Tail.Prev if ll.Tail != nil { ll.Tail.Next = nil } else { ll.Head = nil } ll.length-- } // Delete removes a specific element from the list. func (ll *LinkedList[T]) Delete(elm *Element[T]) { if elm.Prev != nil { elm.Prev.Next = elm.Next } else { ll.Head = elm.Next } if elm.Next != nil { elm.Next.Prev = elm.Prev } else { ll.Tail = elm.Prev } ll.length-- } // Length returns the number of elements in the list. func (ll *LinkedList[T]) Length() int { return ll.length } // Values returns a slice of values in the list. func (ll *LinkedList[T]) Values() []T { values := []T{} cur := ll.Head for cur != nil { values = append(values, cur.Data) cur = cur.Next } return values } // Clear removes all elements from the list, making it empty. func (ll *LinkedList[T]) Clear() { ll.Head = nil ll.Tail = nil ll.length = 0 } ================================================ FILE: util/linkedlist/linkedlist_test.go ================================================ package linkedlist_test import ( "testing" "github.com/pactus-project/pactus/util/linkedlist" "github.com/stretchr/testify/assert" ) func TestDoublyLink_InsertAtHead(t *testing.T) { list := linkedlist.New[int]() list.InsertAtHead(1) list.InsertAtHead(2) list.InsertAtHead(3) list.InsertAtHead(4) assert.Equal(t, []int{4, 3, 2, 1}, list.Values()) assert.Equal(t, 4, list.Length()) assert.Equal(t, 4, list.Head.Data) assert.Equal(t, 1, list.Tail.Data) } func TestSinglyLink_InsertAtTail(t *testing.T) { list := linkedlist.New[int]() list.InsertAtTail(1) list.InsertAtTail(2) list.InsertAtTail(3) list.InsertAtTail(4) assert.Equal(t, []int{1, 2, 3, 4}, list.Values()) assert.Equal(t, 4, list.Length()) assert.Equal(t, 1, list.Head.Data) assert.Equal(t, 4, list.Tail.Data) } func TestDeleteAtHead(t *testing.T) { list := linkedlist.New[int]() list.InsertAtTail(1) list.InsertAtTail(2) list.InsertAtTail(3) list.DeleteAtHead() assert.Equal(t, []int{2, 3}, list.Values()) assert.Equal(t, 2, list.Length()) list.DeleteAtHead() assert.Equal(t, []int{3}, list.Values()) assert.Equal(t, 1, list.Length()) list.DeleteAtHead() assert.Equal(t, []int{}, list.Values()) assert.Equal(t, 0, list.Length()) list.DeleteAtHead() assert.Equal(t, []int{}, list.Values()) assert.Equal(t, 0, list.Length()) } func TestDeleteAtTail(t *testing.T) { list := linkedlist.New[int]() list.InsertAtTail(1) list.InsertAtTail(2) list.InsertAtTail(3) list.DeleteAtTail() assert.Equal(t, []int{1, 2}, list.Values()) assert.Equal(t, 2, list.Length()) list.DeleteAtTail() assert.Equal(t, []int{1}, list.Values()) assert.Equal(t, 1, list.Length()) list.DeleteAtTail() assert.Equal(t, []int{}, list.Values()) assert.Equal(t, 0, list.Length()) list.DeleteAtTail() assert.Equal(t, []int{}, list.Values()) assert.Equal(t, 0, list.Length()) } func TestDelete(t *testing.T) { list := linkedlist.New[int]() elm1 := list.InsertAtTail(1) elm2 := list.InsertAtTail(2) elm3 := list.InsertAtTail(3) elm4 := list.InsertAtTail(4) list.Delete(elm1) assert.Equal(t, []int{2, 3, 4}, list.Values()) assert.Equal(t, 3, list.Length()) list.Delete(elm4) assert.Equal(t, []int{2, 3}, list.Values()) assert.Equal(t, 2, list.Length()) list.Delete(elm2) assert.Equal(t, []int{3}, list.Values()) assert.Equal(t, 1, list.Length()) list.Delete(elm3) assert.Equal(t, []int{}, list.Values()) assert.Equal(t, 0, list.Length()) } func TestClear(t *testing.T) { list := linkedlist.New[int]() list.InsertAtTail(1) list.InsertAtTail(2) list.InsertAtTail(3) list.Clear() assert.Equal(t, []int{}, list.Values()) assert.Equal(t, 0, list.Length()) } func TestInsertAfter(t *testing.T) { list := linkedlist.New[int]() elm1 := list.InsertAtHead(1) elm2 := list.InsertAfter(2, elm1) list.InsertAfter(3, elm2) list.InsertAfter(4, list.Head) list.InsertAfter(5, list.Tail) assert.Equal(t, []int{1, 4, 2, 3, 5}, list.Values()) } func TestInsertBefore(t *testing.T) { list := linkedlist.New[int]() elm1 := list.InsertAtHead(1) elm2 := list.InsertBefore(2, elm1) list.InsertBefore(3, elm2) list.InsertBefore(4, list.Head) list.InsertBefore(5, list.Tail) assert.Equal(t, []int{4, 3, 2, 5, 1}, list.Values()) } ================================================ FILE: util/linkedmap/linkedmap.go ================================================ package linkedmap import ( "github.com/pactus-project/pactus/util/linkedlist" ) type Pair[K comparable, V any] struct { Key K Value V } type LinkedMap[K comparable, V any] struct { list *linkedlist.LinkedList[Pair[K, V]] hashmap map[K]*linkedlist.Element[Pair[K, V]] capacity int } // New creates a new LinkedMap with the specified capacity. func New[K comparable, V any](capacity int) *LinkedMap[K, V] { return &LinkedMap[K, V]{ list: linkedlist.New[Pair[K, V]](), hashmap: make(map[K]*linkedlist.Element[Pair[K, V]]), capacity: capacity, } } // SetCapacity sets the capacity of the LinkedMap and prunes the excess elements if needed. func (lm *LinkedMap[K, V]) SetCapacity(capacity int) { lm.capacity = capacity lm.prune() } // Has checks if the specified key exists in the LinkedMap. func (lm *LinkedMap[K, V]) Has(key K) bool { _, found := lm.hashmap[key] return found } // PushBack adds a new key-value pair to the end of the LinkedMap. func (lm *LinkedMap[K, V]) PushBack(key K, value V) { node, found := lm.hashmap[key] if found { // Update the value if the key already exists node.Data.Value = value return } p := Pair[K, V]{Key: key, Value: value} node = lm.list.InsertAtTail(p) lm.hashmap[key] = node lm.prune() } // PushFront adds a new key-value pair to the beginning of the LinkedMap. func (lm *LinkedMap[K, V]) PushFront(key K, value V) { node, found := lm.hashmap[key] if found { // Update the value if the key already exists node.Data.Value = value return } p := Pair[K, V]{Key: key, Value: value} node = lm.list.InsertAtHead(p) lm.hashmap[key] = node lm.prune() } // GetNode returns the Element corresponding to the specified key. func (lm *LinkedMap[K, V]) GetNode(key K) *linkedlist.Element[Pair[K, V]] { node, found := lm.hashmap[key] if found { return node } return nil } // TailNode returns the Element at the end (tail) of the LinkedMap. func (lm *LinkedMap[K, V]) TailNode() *linkedlist.Element[Pair[K, V]] { node := lm.list.Tail if node == nil { return nil } return node } func (lm *LinkedMap[K, V]) RemoveTail() { lm.remove(lm.list.Tail) } // HeadNode returns the Element at the beginning (head) of the LinkedMap. func (lm *LinkedMap[K, V]) HeadNode() *linkedlist.Element[Pair[K, V]] { node := lm.list.Head if node == nil { return nil } return node } func (lm *LinkedMap[K, V]) RemoveHead() { lm.remove(lm.list.Head) } // Remove removes the key-value pair with the specified key from the LinkedMap. // It returns true if the key was found and removed, otherwise false. func (lm *LinkedMap[K, V]) Remove(key K) bool { element, found := lm.hashmap[key] if found { lm.remove(element) } return found } // remove removes the specified element pair from the LinkedMap. func (lm *LinkedMap[K, V]) remove(element *linkedlist.Element[Pair[K, V]]) { lm.list.Delete(element) delete(lm.hashmap, element.Data.Key) } // Empty checks if the LinkedMap is empty (contains no key-value pairs). func (lm *LinkedMap[K, V]) Empty() bool { return lm.Size() == 0 } // Capacity returns the capacity of the LinkedMap. func (lm *LinkedMap[K, V]) Capacity() int { return lm.capacity } // Size returns the number of key-value pairs in the LinkedMap. func (lm *LinkedMap[K, V]) Size() int { return lm.list.Length() } // Full checks if the LinkedMap is full (reached its capacity). func (lm *LinkedMap[K, V]) Full() bool { return lm.list.Length() == lm.capacity } // Clear removes all key-value pairs from the LinkedMap, making it empty. func (lm *LinkedMap[K, V]) Clear() { lm.list.Clear() lm.hashmap = make(map[K]*linkedlist.Element[Pair[K, V]]) } // prune removes excess elements from the LinkedMap if its size exceeds the capacity. func (lm *LinkedMap[K, V]) prune() { if lm.capacity == 0 { return } for lm.list.Length() > lm.capacity { head := lm.list.Head key := head.Data.Key lm.list.Delete(head) delete(lm.hashmap, key) } } ================================================ FILE: util/linkedmap/linkedmap_test.go ================================================ package linkedmap import ( "testing" "github.com/stretchr/testify/assert" ) func TestLinkedMap(t *testing.T) { t.Run("Test FirstNode", func(t *testing.T) { lmp := New[int, string](4) assert.Nil(t, lmp.HeadNode()) lmp.PushFront(3, "c") lmp.PushFront(2, "b") lmp.PushFront(1, "a") assert.Equal(t, 1, lmp.HeadNode().Data.Key) assert.Equal(t, "a", lmp.HeadNode().Data.Value) }) t.Run("Test LastNode", func(t *testing.T) { lmp := New[int, string](4) assert.Nil(t, lmp.TailNode()) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") assert.Equal(t, 3, lmp.TailNode().Data.Key) assert.Equal(t, "c", lmp.TailNode().Data.Value) }) t.Run("Test Get", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(2, "b") lmp.PushBack(1, "a") node := lmp.GetNode(2) assert.Equal(t, 2, node.Data.Key) assert.Equal(t, "b", node.Data.Value) node = lmp.GetNode(5) assert.Nil(t, node) }) t.Run("Test Remove", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(0, "-") lmp.PushBack(2, "b") lmp.PushBack(1, "a") assert.True(t, lmp.Remove(2)) assert.False(t, lmp.Remove(2)) }) t.Run("Test RemoveTail", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(0, "-") lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.RemoveTail() assert.Equal(t, "a", lmp.TailNode().Data.Value) assert.NotEqual(t, "b", lmp.TailNode().Data.Value) }) t.Run("Test RemoveHead", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(0, "-") lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.RemoveHead() assert.Equal(t, "a", lmp.HeadNode().Data.Value) assert.NotEqual(t, "-", lmp.HeadNode().Data.Value) }) t.Run("Should updates v", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(1, "a") lmp.PushBack(1, "b") node := lmp.GetNode(1) assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "b", node.Data.Value) lmp.PushFront(1, "c") node = lmp.GetNode(1) assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "c", node.Data.Value) }) t.Run("Should prunes oldest item", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.PushBack(4, "d") node := lmp.GetNode(1) assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "a", node.Data.Value) lmp.PushBack(5, "e") node = lmp.GetNode(1) assert.Nil(t, node) }) t.Run("Should prunes by changing capacity", func(t *testing.T) { lmp := New[int, string](4) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.PushBack(4, "d") lmp.SetCapacity(6) node := lmp.GetNode(2) assert.Equal(t, 2, node.Data.Key) assert.Equal(t, "b", node.Data.Value) lmp.SetCapacity(2) assert.True(t, lmp.Full()) node = lmp.GetNode(2) assert.Nil(t, node) }) t.Run("Test PushBack and prune", func(t *testing.T) { lmp := New[int, string](3) lmp.PushBack(1, "a") // This item should be pruned lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.PushBack(4, "d") node := lmp.HeadNode() assert.Equal(t, 2, node.Data.Key) assert.Equal(t, "b", node.Data.Value) }) t.Run("Test PushFront and prune", func(t *testing.T) { lmp := New[int, string](3) lmp.PushFront(1, "a") lmp.PushFront(2, "b") lmp.PushFront(3, "c") lmp.PushFront(4, "d") // This item should be pruned node := lmp.TailNode() assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "a", node.Data.Value) }) t.Run("Delete first ", func(t *testing.T) { lmp := New[int, string](3) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.Remove(1) assert.Equal(t, 2, lmp.HeadNode().Data.Key) assert.Equal(t, "b", lmp.HeadNode().Data.Value) }) t.Run("Delete last", func(t *testing.T) { lmp := New[int, string](3) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.Remove(3) assert.Equal(t, 2, lmp.TailNode().Data.Key) assert.Equal(t, "b", lmp.TailNode().Data.Value) }) t.Run("Test Has function", func(t *testing.T) { lmp := New[int, string](2) lmp.PushBack(1, "a") assert.True(t, lmp.Has(1)) assert.False(t, lmp.Has(2)) }) t.Run("Test Clear", func(t *testing.T) { lmp := New[int, string](2) lmp.PushBack(1, "a") lmp.Clear() assert.True(t, lmp.Empty()) }) } func TestCapacity(t *testing.T) { t.Run("Check Capacity", func(t *testing.T) { capacity := 100 lmp := New[int, string](capacity) assert.Equal(t, capacity, lmp.Capacity()) }) t.Run("Test FirstNode with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) assert.Nil(t, lmp.HeadNode()) lmp.PushFront(3, "c") lmp.PushFront(2, "b") lmp.PushFront(1, "a") assert.Equal(t, 1, lmp.HeadNode().Data.Key) assert.Equal(t, "a", lmp.HeadNode().Data.Value) }) t.Run("Test LastNode with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) assert.Nil(t, lmp.TailNode()) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") assert.Equal(t, 3, lmp.TailNode().Data.Key) assert.Equal(t, "c", lmp.TailNode().Data.Value) }) t.Run("Test Get with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(2, "b") lmp.PushBack(1, "a") node := lmp.GetNode(2) assert.Equal(t, 2, node.Data.Key) assert.Equal(t, "b", node.Data.Value) node = lmp.GetNode(5) assert.Nil(t, node) }) t.Run("Test Remove with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(0, "-") lmp.PushBack(2, "b") lmp.PushBack(1, "a") assert.True(t, lmp.Remove(2)) assert.False(t, lmp.Remove(2)) }) t.Run("Test RemoveTail with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(0, "-") lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.RemoveTail() assert.Equal(t, "a", lmp.TailNode().Data.Value) assert.NotEqual(t, "b", lmp.TailNode().Data.Value) }) t.Run("Test RemoveHead with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(0, "-") lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.RemoveHead() assert.Equal(t, "a", lmp.HeadNode().Data.Value) assert.NotEqual(t, "-", lmp.HeadNode().Data.Value) }) t.Run("Should updates v with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") lmp.PushBack(1, "b") node := lmp.GetNode(1) assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "b", node.Data.Value) lmp.PushFront(1, "c") node = lmp.GetNode(1) assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "c", node.Data.Value) }) t.Run("Should not prunes oldest item with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.PushBack(4, "d") node := lmp.GetNode(1) assert.Equal(t, 1, node.Data.Key) assert.Equal(t, "a", node.Data.Value) lmp.PushBack(5, "e") node = lmp.GetNode(1) assert.NotNil(t, node) }) t.Run("Should prunes by changing capacity with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.PushBack(4, "d") lmp.SetCapacity(6) node := lmp.GetNode(2) assert.Equal(t, 2, node.Data.Key) assert.Equal(t, "b", node.Data.Value) lmp.SetCapacity(2) assert.True(t, lmp.Full()) node = lmp.GetNode(2) assert.Nil(t, node) }) t.Run("Test PushBack and should not prune with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") // This item should be pruned lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.PushBack(4, "d") node := lmp.TailNode() assert.Equal(t, 4, node.Data.Key) assert.Equal(t, "d", node.Data.Value) }) t.Run("Test PushFront and prune with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushFront(1, "a") lmp.PushFront(2, "b") lmp.PushFront(3, "c") lmp.PushFront(4, "d") // This item should be pruned n := lmp.TailNode() assert.Equal(t, 1, n.Data.Key) assert.Equal(t, "a", n.Data.Value) }) t.Run("Delete first with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.Remove(1) assert.Equal(t, 2, lmp.HeadNode().Data.Key) assert.Equal(t, "b", lmp.HeadNode().Data.Value) }) t.Run("Delete last with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") lmp.PushBack(2, "b") lmp.PushBack(3, "c") lmp.Remove(3) assert.Equal(t, 2, lmp.TailNode().Data.Key) assert.Equal(t, "b", lmp.TailNode().Data.Value) }) t.Run("Test Has function with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") assert.True(t, lmp.Has(1)) assert.False(t, lmp.Has(2)) }) t.Run("Test Clear with Zero Capacity", func(t *testing.T) { lmp := New[int, string](0) lmp.PushBack(1, "a") lmp.Clear() assert.True(t, lmp.Empty()) }) } ================================================ FILE: util/logger/config.go ================================================ package logger // Config defines parameters for the logger module. type Config struct { Colorful bool `toml:"colorful"` MaxBackups int `toml:"max_backups"` RotateLogAfterDays int `toml:"rotate_log_after_days"` Compress bool `toml:"compress"` Targets []string `toml:"targets"` Levels map[string]string `toml:"levels"` } func DefaultConfig() *Config { conf := &Config{ Levels: make(map[string]string), Colorful: true, MaxBackups: 0, RotateLogAfterDays: 1, Compress: true, Targets: []string{"console", "file"}, } conf.Levels["default"] = "info" conf.Levels["_network"] = "error" conf.Levels["_consensus"] = "warn" conf.Levels["_state"] = "info" conf.Levels["_sync"] = "error" conf.Levels["_pool"] = "error" conf.Levels["_http"] = "info" conf.Levels["_html"] = "info" conf.Levels["_grpc"] = "info" conf.Levels["_jsonrpc"] = "info" conf.Levels["_zmq"] = "info" conf.Levels["_firewall"] = "warn" return conf } // BasicCheck performs basic checks on the configuration. func (*Config) BasicCheck() error { return nil } ================================================ FILE: util/logger/logger.go ================================================ package logger import ( "context" "encoding/hex" "fmt" "io" "os" "reflect" "slices" "github.com/pactus-project/pactus/util" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "gopkg.in/natefinch/lumberjack.v2" ) type LogStringer interface { LogString() string } var ( LogFilename = "pactus.log" MaxLogSize = 10 // 10MB to rotate a log file ) var globalInst *logger type logger struct { config *Config subs map[string]*SubLogger writer io.Writer } type SubLogger struct { logger zerolog.Logger name string obj LogStringer } func getLoggersInst() *logger { if globalInst == nil { // Only during tests the globalInst is nil LogFilename = util.TempFilePath() conf := &Config{ Levels: make(map[string]string), Colorful: true, } conf.Levels["default"] = "debug" conf.Levels["_network"] = "debug" conf.Levels["_consensus"] = "debug" conf.Levels["_state"] = "debug" conf.Levels["_sync"] = "debug" conf.Levels["_pool"] = "debug" conf.Levels["_http"] = "debug" conf.Levels["_grpc"] = "debug" conf.Levels["_zmq"] = "debug" conf.Levels["_firewall"] = "debug" globalInst = &logger{ config: conf, subs: make(map[string]*SubLogger), writer: zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: "15:04:05"}, } log.Logger = zerolog.New(globalInst.writer).With().Timestamp().Logger() } return globalInst } func InitGlobalLogger(ctx context.Context, conf *Config) { if globalInst != nil { return } writers := []io.Writer{} if slices.Contains(conf.Targets, "file") { fileWriter := &lumberjack.Logger{ Filename: LogFilename, MaxSize: MaxLogSize, MaxBackups: conf.MaxBackups, Compress: conf.Compress, MaxAge: conf.RotateLogAfterDays, } writers = append(writers, fileWriter) } if slices.Contains(conf.Targets, "console") { // console writer if conf.Colorful { consoleWriter := &zerolog.ConsoleWriter{ Out: os.Stderr, TimeFormat: "15:04:05", } writers = append(writers, consoleWriter) } else { writers = append(writers, os.Stderr) } } globalInst = &logger{ config: conf, subs: make(map[string]*SubLogger), writer: io.MultiWriter(writers...), } log.Logger = zerolog.New(globalInst.writer).With().Ctx(ctx).Timestamp().Logger() lvl, err := zerolog.ParseLevel(conf.Levels["default"]) if err != nil { Warn("invalid default log level", "error", err) } log.Logger = log.Logger.Level(lvl) } func addFields(event *zerolog.Event, keyvals ...any) *zerolog.Event { if event == nil { return nil } if len(keyvals)%2 != 0 { keyvals = append(keyvals, "!MISSING-VALUE!") } for index := 0; index < len(keyvals); index += 2 { key, ok := keyvals[index].(string) if !ok { key = "!INVALID-KEY!" } value := keyvals[index+1] switch typ := value.(type) { case LogStringer: if isNil(typ) { event.Any(key, typ) } else { event.Str(key, typ.LogString()) } case fmt.Stringer: if isNil(typ) { event.Any(key, typ) } else { event.Stringer(key, typ) } case error: event.AnErr(key, typ) case []byte: event.Str(key, hex.EncodeToString(typ)) default: event.Any(key, typ) } } return event } func NewSubLogger(name string, obj LogStringer) *SubLogger { inst := getLoggersInst() sub := &SubLogger{ logger: zerolog.New(inst.writer).With().Timestamp().Logger(), name: name, obj: obj, } lvlStr := inst.config.Levels[name] if lvlStr == "" { lvlStr = inst.config.Levels["default"] } lvl, err := zerolog.ParseLevel(lvlStr) if err != nil { Warn("invalid log level", "error", err, "name", name) } sub.logger = sub.logger.Level(lvl) inst.subs[name] = sub return sub } func (sl *SubLogger) logObj(event *zerolog.Event, msg string, keyvals ...any) { if event == nil { return } if sl.obj != nil { event = event.Str(sl.name, sl.obj.LogString()) } addFields(event, keyvals...).Msg(msg) } func (sl *SubLogger) Trace(msg string, keyvals ...any) { sl.logObj(sl.logger.Trace(), msg, keyvals...) } func (sl *SubLogger) Debug(msg string, keyvals ...any) { sl.logObj(sl.logger.Debug(), msg, keyvals...) } func (sl *SubLogger) Info(msg string, keyvals ...any) { sl.logObj(sl.logger.Info(), msg, keyvals...) } func (sl *SubLogger) Warn(msg string, keyvals ...any) { sl.logObj(sl.logger.Warn(), msg, keyvals...) } func (sl *SubLogger) Error(msg string, keyvals ...any) { sl.logObj(sl.logger.Error(), msg, keyvals...) } func (sl *SubLogger) Fatal(msg string, keyvals ...any) { sl.logObj(sl.logger.Fatal(), msg, keyvals...) } func (sl *SubLogger) Panic(msg string, keyvals ...any) { sl.logObj(sl.logger.Panic(), msg, keyvals...) } func Trace(msg string, keyvals ...any) { addFields(log.Trace(), keyvals...).Msg(msg) } func Debug(msg string, keyvals ...any) { addFields(log.Debug(), keyvals...).Msg(msg) } func Info(msg string, keyvals ...any) { addFields(log.Info(), keyvals...).Msg(msg) } func Warn(msg string, keyvals ...any) { addFields(log.Warn(), keyvals...).Msg(msg) } func Error(msg string, keyvals ...any) { addFields(log.Error(), keyvals...).Msg(msg) } func Fatal(msg string, keyvals ...any) { addFields(log.Fatal(), keyvals...).Msg(msg) } func Panic(msg string, keyvals ...any) { addFields(log.Panic(), keyvals...).Msg(msg) } func isNil(val any) bool { if val == nil { return true } if reflect.TypeOf(val).Kind() == reflect.Ptr { return reflect.ValueOf(val).IsNil() } return false } func (sl *SubLogger) SetObj(obj LogStringer) { sl.obj = obj } ================================================ FILE: util/logger/logger_test.go ================================================ package logger import ( "bytes" "errors" "fmt" "testing" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" ) type Foo struct{} func (Foo) LogString() string { return "foo" } func TestNilObjLogger(t *testing.T) { l := NewSubLogger("test", nil) var buf bytes.Buffer l.logger = l.logger.Output(&buf) l.Info("hello", "error", errors.New("error")) assert.Contains(t, buf.String(), "hello") assert.Contains(t, buf.String(), "error") } func TestSubLogger(t *testing.T) { globalInst = nil c := DefaultConfig() c.Colorful = false InitGlobalLogger(t.Context(), c) globalInst.config.Levels["test"] = "warn" subLogger := NewSubLogger("test", Foo{}) var buf bytes.Buffer subLogger.logger = subLogger.logger.Output(&buf) subLogger.Trace("msg") subLogger.Debug("msg") subLogger.Info("msg") subLogger.Warn("msg") subLogger.Error("msg") out := buf.String() assert.Contains(t, out, "foo") assert.NotContains(t, out, "trace") assert.NotContains(t, out, "debug") assert.NotContains(t, out, "info") assert.Contains(t, out, "warn") assert.Contains(t, out, "error") } func TestLogger(t *testing.T) { globalInst = nil c := DefaultConfig() c.Colorful = true InitGlobalLogger(t.Context(), c) var buf bytes.Buffer log.Logger = log.Output(&buf) Trace("msg", "trace", "trace") Debug("msg", "trace", "trace") Info("msg", nil) Info("msg", "a", nil) Info("msg", "b", []byte{1, 2, 3}) Warn("msg", "x") Error("msg", "y", Foo{}) out := buf.String() fmt.Println(out) assert.NotContains(t, out, "trace") assert.NotContains(t, out, "debug") assert.Contains(t, out, "foo") assert.Contains(t, out, "010203") assert.Contains(t, out, "!INVALID-KEY!") assert.Contains(t, out, "!MISSING-VALUE!") assert.Contains(t, out, "null") assert.NotContains(t, out, "trace") assert.NotContains(t, out, "debug") assert.Contains(t, out, "info") assert.Contains(t, out, "warn") assert.Contains(t, out, "error") } func TestNilValue(t *testing.T) { var buf bytes.Buffer log.Logger = log.Output(&buf) foo := new(Foo) if true { // to avoid some linting errors foo = nil } Info("msg", "null", nil) Info("msg", "error", error(nil)) Info("msg", "stringer", foo) out := buf.String() fmt.Println(out) assert.Contains(t, out, "null") assert.Contains(t, out, "error") assert.Contains(t, out, "stringer") } func TestInvalidLevel(t *testing.T) { globalInst = nil c := DefaultConfig() c.Colorful = false InitGlobalLogger(t.Context(), c) var buf bytes.Buffer log.Logger = log.Logger.Output(&buf) globalInst.config.Levels["test"] = "invalid" l := NewSubLogger("test", Foo{}) var buf2 bytes.Buffer l.logger = l.logger.Output(&buf2) l.Error("message", "key", "val") out := buf.String() out2 := buf2.String() fmt.Println(out) assert.Contains(t, out, "Unknown Level String") assert.NotContains(t, out2, "error") assert.NotContains(t, out2, "message") } ================================================ FILE: util/net.go ================================================ package util import ( "context" "net" "time" ) // NetworkListen listens on a network address with a context. func NetworkListen(ctx context.Context, network, address string) (net.Listener, error) { var lc net.ListenConfig return lc.Listen(ctx, network, address) } // NetworkDialTimeout dials a network address with a timeout and a context. func NetworkDialTimeout(ctx context.Context, network, address string, timeout time.Duration) (net.Conn, error) { d := net.Dialer{Timeout: timeout} return d.DialContext(ctx, network, address) } ================================================ FILE: util/ntp/ntp.go ================================================ package ntp import ( "context" "math" "sync" "time" "github.com/ezex-io/gopkg/scheduler" "github.com/pactus-project/pactus/util/logger" ) const ( maxClockOffset = time.Duration(math.MinInt64) ) // QueryError is returned when a query from all NTP pools encounters an error // and we have no valid response from them. type QueryError struct{} func (QueryError) Error() string { return "failed to get NTP query from all pools" } var _pools = []string{ "pool.ntp.org", "time.google.com", "time.cloudflare.com", "time.apple.com", "time.windows.com", "ntp.ubuntu.com", } // Checker represents a NTP checker that periodically checks the system time against the network time. type Checker struct { lk sync.RWMutex ctx context.Context cancel func() querier Querier offset time.Duration interval time.Duration threshold time.Duration } // CheckerOption defines the type for functions that configure a Checker. type CheckerOption func(*Checker) // WithQuerier sets the Querier for the Checker. func WithQuerier(querier Querier) CheckerOption { return func(c *Checker) { c.querier = querier } } // WithInterval sets the interval at which the checker will run. // Default interval is 1 minute. func WithInterval(interval time.Duration) CheckerOption { return func(c *Checker) { c.interval = interval } } // WithThreshold sets the threshold for determining if the system time is out of sync. // Default threshold is 1 second. func WithThreshold(threshold time.Duration) CheckerOption { return func(c *Checker) { c.threshold = threshold } } // NewNtpChecker creates a new Checker with the provided options. // If no options are provided, it uses default values for interval and threshold. func NewNtpChecker(ctx context.Context, opts ...CheckerOption) *Checker { ctx, cancel := context.WithCancel(ctx) defaultInterval := time.Minute defaultThreshold := time.Second // Initialize the checker with default values. checker := &Checker{ ctx: ctx, cancel: cancel, interval: defaultInterval, threshold: defaultThreshold, querier: RemoteQuerier{}, } // Apply provided options to override default values. for _, opt := range opts { opt(checker) } return checker } func (c *Checker) Start() { scheduler.Every(c.interval).Do(c.ctx, func(_ context.Context) { offset, _ := c.queryClockOffset() c.lk.Lock() c.offset = offset c.lk.Unlock() if c.offset != maxClockOffset && c.IsOutOfSync() { logger.Error( "the system time is out of sync with the network time by more than one second", "threshold", c.threshold, "offset", offset) } }) } func (c *Checker) Stop() { c.cancel() } func (c *Checker) IsOutOfSync() bool { c.lk.RLock() defer c.lk.RUnlock() return c.offset.Abs() > c.threshold } func (c *Checker) ClockOffset() (time.Duration, error) { c.lk.RLock() defer c.lk.RUnlock() if c.offset == maxClockOffset { return 0, QueryError{} } return c.offset, nil } func (c *Checker) queryClockOffset() (time.Duration, error) { for _, server := range _pools { response, err := c.querier.Query(server) if err != nil { logger.Debug("ntp query error", "server", server, "error", err) continue } if err := response.Validate(); err != nil { logger.Debug("ntp validate error", "server", server, "error", err) continue } logger.Debug("successful ntp query", "offset", response.ClockOffset, "RTT", response.RTT) return response.ClockOffset, nil } logger.Error("failed to get ntp query from all pool") return maxClockOffset, QueryError{} } ================================================ FILE: util/ntp/ntp_test.go ================================================ package ntp import ( "errors" "testing" "time" "github.com/beevik/ntp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testQuerier struct { err error res *ntp.Response } func (q *testQuerier) Query(_ string) (*ntp.Response, error) { return q.res, q.err } type testData struct { checker *Checker querier *testQuerier } func setup(t *testing.T) *testData { t.Helper() querier := &testQuerier{} opts := []CheckerOption{ WithInterval(100 * time.Millisecond), WithThreshold(1 * time.Second), WithQuerier(querier), } checker := NewNtpChecker(t.Context(), opts...) td := &testData{ checker: checker, querier: querier, } return td } func (td *testData) Stop() { td.checker.Stop() } func TestNTPChecker(t *testing.T) { t.Run("Offset less than one second", func(t *testing.T) { td := setup(t) defer td.Stop() ntpOffset := 100 * time.Millisecond td.querier.res = &ntp.Response{ Stratum: 1, ClockOffset: ntpOffset, } go td.checker.Start() require.Eventually(t, func() bool { offset, _ := td.checker.ClockOffset() return offset == ntpOffset }, 5*time.Second, 100*time.Millisecond) offset, err := td.checker.ClockOffset() require.NoError(t, err) assert.Equal(t, ntpOffset, offset) assert.False(t, td.checker.IsOutOfSync()) }) t.Run("Offset more than one second", func(t *testing.T) { td := setup(t) defer td.Stop() ntpOffset := 2 * time.Second td.querier.res = &ntp.Response{ Stratum: 1, ClockOffset: ntpOffset, } go td.checker.Start() require.Eventually(t, func() bool { offset, _ := td.checker.ClockOffset() return offset == ntpOffset }, 5*time.Second, 100*time.Millisecond) offset, err := td.checker.ClockOffset() require.NoError(t, err) assert.Equal(t, ntpOffset, offset) assert.True(t, td.checker.IsOutOfSync()) }) t.Run("Query error", func(t *testing.T) { td := setup(t) defer td.Stop() td.querier.err = errors.New("unable to query") go td.checker.Start() require.Eventually(t, func() bool { _, err := td.checker.ClockOffset() return err != nil }, 5*time.Second, 100*time.Millisecond) offset, err := td.checker.ClockOffset() require.Error(t, err) assert.Zero(t, offset) assert.True(t, td.checker.IsOutOfSync()) }) t.Run("Validation error", func(t *testing.T) { td := setup(t) defer td.Stop() td.querier.err = nil td.querier.res = &ntp.Response{ Stratum: 0, } go td.checker.Start() require.Eventually(t, func() bool { _, err := td.checker.ClockOffset() return err != nil }, 5*time.Second, 100*time.Millisecond) offset, err := td.checker.ClockOffset() require.Error(t, err) assert.Zero(t, offset) assert.True(t, td.checker.IsOutOfSync()) }) } ================================================ FILE: util/ntp/query.go ================================================ package ntp import "github.com/beevik/ntp" type Querier interface { Query(address string) (*ntp.Response, error) } type RemoteQuerier struct{} func (RemoteQuerier) Query(address string) (*ntp.Response, error) { return ntp.Query(address) } ================================================ FILE: util/number.go ================================================ package util import ( "strconv" "strings" ) func FormatIntWithDelimiters(num int64) string { numStr := strconv.FormatInt(num, 10) return formatNumberString(numStr) } func FormatFloatWithDelimiters(num float64, prec int) string { numStr := strconv.FormatFloat(num, 'f', prec, 64) parts := strings.Split(numStr, ".") numStr = parts[0] numStr = formatNumberString(numStr) if len(parts) > 1 { numStr += "." + parts[1] } return numStr } func formatNumberString(numStr string) string { var formattedNum string if strings.HasPrefix(numStr, "-") { formattedNum = "-" numStr = numStr[1:] } for i, c := range numStr { if (i > 0) && (len(numStr)-i)%3 == 0 { formattedNum += "," } formattedNum += string(c) } return formattedNum } ================================================ FILE: util/number_test.go ================================================ package util import ( "testing" "github.com/stretchr/testify/assert" ) func TestFormatNumberWithDelimiters(t *testing.T) { tests := []struct { input int64 expected string }{ {123456, "123,456"}, {123, "123"}, {0, "0"}, {-123, "-123"}, {-123456, "-123,456"}, } for _, test := range tests { result := FormatIntWithDelimiters(test.input) assert.Equal(t, test.expected, result, "FormatNumber(%d)", test.input) } } func TestFormatFloatWithDelimiters(t *testing.T) { tests := []struct { input float64 expected string }{ {123456.789, "123,456.789"}, {123.456, "123.456"}, {0.0, "0"}, {-123.456, "-123.456"}, {-123456.789, "-123,456.789"}, {123456, "123,456"}, {123, "123"}, {0, "0"}, {-123, "-123"}, {-123456, "-123,456"}, } for _, test := range tests { result := FormatFloatWithDelimiters(test.input, -1) assert.Equal(t, test.expected, result, "FormatFloat(%f)", test.input) } } ================================================ FILE: util/pairslice/pairslice.go ================================================ package pairslice import ( "golang.org/x/exp/slices" ) // Pair represents a key-value pair. type Pair[K comparable, V any] struct { First K Second V } // PairSlice represents a slice of key-value pairs. type PairSlice[K comparable, V any] struct { pairs []*Pair[K, V] } // New creates a new instance of PairSlice with a specified capacity. func New[K comparable, V any](capacity int) *PairSlice[K, V] { return &PairSlice[K, V]{ pairs: make([]*Pair[K, V], 0, capacity), } } // Append adds the first and second to the end of the slice. func (ps *PairSlice[K, V]) Append(first K, second V) { ps.pairs = append(ps.pairs, &Pair[K, V]{first, second}) } // RemoveFirst removes the first element from PairSlice. func (ps *PairSlice[K, V]) RemoveFirst() { ps.remove(0) } // RemoveLast removes the last element from PairSlice. func (ps *PairSlice[K, V]) RemoveLast() { ps.remove(ps.Len() - 1) } // Len returns the number of elements in the PairSlice. func (ps *PairSlice[K, V]) Len() int { return len(ps.pairs) } // remove removes the element at the specified index from PairSlice. func (ps *PairSlice[K, V]) remove(index int) { ps.pairs = slices.Delete(ps.pairs, index, index+1) } // Get returns the properties at the specified index. If the index is out of bounds, it returns false. func (ps *PairSlice[K, V]) Get(index int) (K, V, bool) { if index < 0 || index >= len(ps.pairs) { var first K var second V return first, second, false } pair := ps.pairs[index] return pair.First, pair.Second, true } // First returns the first properties in the PairSlice. If the PairSlice is empty, it returns false. func (ps *PairSlice[K, V]) First() (K, V, bool) { return ps.Get(0) } // Last returns the last properties in the PairSlice. If the PairSlice is empty, it returns false. func (ps *PairSlice[K, V]) Last() (K, V, bool) { return ps.Get(ps.Len() - 1) } ================================================ FILE: util/pairslice/pairslice_test.go ================================================ package pairslice import ( "testing" "github.com/stretchr/testify/assert" ) func TestNew(t *testing.T) { slice := New[int, string](10) assert.NotNil(t, slice) assert.Equal(t, 10, cap(slice.pairs)) assert.Empty(t, slice.pairs) } func TestPairSlice(t *testing.T) { t.Run("Test Append", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") assert.Equal(t, 3, slice.Len()) assert.Equal(t, 3, slice.pairs[2].First) assert.Equal(t, "c", slice.pairs[2].Second) }) t.Run("Test RemoveFirst", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") slice.RemoveFirst() assert.Equal(t, 2, slice.pairs[0].First) assert.Equal(t, "b", slice.pairs[0].Second) }) t.Run("Test RemoveLast", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") slice.Append(4, "d") slice.RemoveLast() assert.Equal(t, 3, slice.pairs[2].First) assert.Equal(t, "c", slice.pairs[2].Second) }) t.Run("Test Len", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") assert.Equal(t, 2, slice.Len()) }) t.Run("Test Remove", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") slice.Append(4, "d") slice.remove(1) assert.Equal(t, 3, slice.pairs[1].First) assert.Equal(t, "c", slice.pairs[1].Second) }) t.Run("Test Get", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") slice.Append(4, "d") first, second, _ := slice.Get(2) assert.Equal(t, slice.pairs[2].First, first) assert.Equal(t, slice.pairs[2].Second, second) }) t.Run("Test Get negative index or bigger than len", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(4, "d") _, _, result1 := slice.Get(-1) _, _, result2 := slice.Get(10) assert.False(t, result1) assert.False(t, result2) }) t.Run("Test First", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") slice.Append(4, "d") first, second, _ := slice.First() assert.Equal(t, slice.pairs[0].First, first) assert.Equal(t, slice.pairs[0].Second, second) }) t.Run("Test Last", func(t *testing.T) { slice := New[int, string](4) slice.Append(1, "a") slice.Append(2, "b") slice.Append(3, "c") slice.Append(4, "d") first, second, _ := slice.Last() assert.Equal(t, slice.pairs[3].First, first) assert.Equal(t, slice.pairs[3].Second, second) }) } ================================================ FILE: util/persistentmerkle/merkle.go ================================================ package persistentmerkle import ( "math" "github.com/pactus-project/pactus/crypto/hash" ) type Tree struct { nodes map[uint32]*node maxWidth int32 maxHeight int32 } type node struct { width int32 height int32 hash *hash.Hash } // nodeID return the node ID (four bytes): // +-+---+ // |h| w | // +-+---+ // h: height // w: width func nodeID(width, height int32) uint32 { return (uint32(height&0xff) << 24) | uint32(width&0xffffff) } func New() *Tree { return &Tree{ nodes: make(map[uint32]*node), } } func (*Tree) createNode(width, height int32) *node { return &node{ width: width, height: height, } } func (t *Tree) getNode(width, height int32) *node { id := nodeID(width, height) return t.nodes[id] } func (t *Tree) getOrCreateNode(width, height int32) *node { id := nodeID(width, height) node, ok := t.nodes[id] if !ok { node = t.createNode(width, height) t.nodes[id] = node } return node } func (t *Tree) invalidateNode(width, height int32) { n := t.getOrCreateNode(width, height) n.hash = nil } func (t *Tree) recalculateHeight(maxWidth int32) { if maxWidth > t.maxWidth { t.maxWidth = maxWidth maxHeight := math.Log2(float64(maxWidth)) if math.Remainder(maxHeight, 1.0) != 0 { t.maxHeight = int32(math.Trunc(maxHeight)) + 2 } else { t.maxHeight = int32(math.Trunc(maxHeight)) + 1 } } } func (t *Tree) SetData(leaf int32, data []byte) { t.SetHash(leaf, hash.CalcHash(data)) } func (t *Tree) SetHash(leaf int32, h hash.Hash) { t.recalculateHeight(leaf + 1) node := t.getOrCreateNode(leaf, 0) node.hash = &h w := leaf / 2 for h := int32(1); h < t.maxHeight; h++ { t.invalidateNode(w, h) w /= 2 } } func (t *Tree) Root() hash.Hash { return t.nodeHash(0, t.maxHeight-1) } func (t *Tree) nodeHash(width, height int32) hash.Hash { node := t.getNode(width, height) if node == nil { node = t.getNode(width-1, height) if node == nil { panic("invalid merkle tree") } } if node.hash != nil { return *node.hash } left := t.nodeHash(width*2, height-1) right := t.nodeHash(width*2+1, height-1) data := make([]byte, len(left)+len(right)) copy(data[:hash.HashSize], left.Bytes()) copy(data[hash.HashSize:], right.Bytes()) h := hash.CalcHash(data) node.hash = &h return h } ================================================ FILE: util/persistentmerkle/merkle_test.go ================================================ package persistentmerkle import ( "encoding/hex" "testing" "github.com/stretchr/testify/assert" ) func TestNodeID(t *testing.T) { assert.Equal(t, uint32(0x00000000), nodeID(0, 0)) assert.Equal(t, uint32(0x01000000), nodeID(0, 1)) assert.Equal(t, uint32(0x00000001), nodeID(1, 0)) assert.Equal(t, uint32(0x01000001), nodeID(1, 1)) assert.Equal(t, uint32(0xffffffff), nodeID(0xffffff, 0xff)) assert.Equal(t, uint32(0x00ffffff), nodeID(0xffffff, 0x00)) assert.Equal(t, uint32(0x77ff00ff), nodeID(0xff00ff, 0x77)) } func TestCalculateHeight(t *testing.T) { tree := New() tree.recalculateHeight(0) assert.Equal(t, int32(0), tree.maxHeight) tree.recalculateHeight(1) assert.Equal(t, int32(1), tree.maxHeight) tree.recalculateHeight(2) assert.Equal(t, int32(2), tree.maxHeight) tree.recalculateHeight(4) assert.Equal(t, int32(3), tree.maxHeight) tree.recalculateHeight(5) assert.Equal(t, int32(4), tree.maxHeight) tree.recalculateHeight(8) assert.Equal(t, int32(4), tree.maxHeight) tree.recalculateHeight(9) assert.Equal(t, int32(5), tree.maxHeight) } func TestMerkleTree(t *testing.T) { tree := New() data := []string{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", } roots := []string{ "a3a0081351bb785d0758ddf68076a95ffd3f10b88bbc9911e9fea4d793c06414", "f8c780ed425c674e458b1e42abc894d144af4660476b63adc900e5ca72ef3a7d", "fba254b63bc4f71e560d3d94bacaa555b57b0d15073bdde95d028176cc702952", "62edcdc731948255463d6a8b7809bf26de2bdc1e2b351e76bf0adb5a2b863f5a", "c0c5e5d5389593188ef48b73f808571f88252491696cb481d8d587e3d59a282b", "0ff43eeca0576185050fea37c7cfc81219ceca762f9e29bc77c57a651efc6ae6", "e071cda6628d87d405c82c9948795b99b5afabb01c5a93b4970b4f97b866b32b", "f4b351a896639e122c81c5819d278fc67392abc87592daeaa1bddda9bec57186", "0086ad0c0b55b087d82733f8feaff319bc9dd7bcfbc6ddd3f8322e4dc9bd492e", "b0b18c74adc184b14f6dc6546062aad6475f4b167334bc4a4a537c5b78a22b44", "fbb6818ed0eb4b31ae3a273498e2cd26d4dbdb44d09ea71a115958f31687ebf5", "8e7cc64ef18bf44612520a06e9cfa2b6117d2587a1832ec79365b463656b81ea", "7d1fa0a14c9d83fde2638c7f404041a667365c1ada96e59c42ff2573a4b1bd83", "dcab86df00b139cec708c3cfe2c29cc4adf47ba3b9981059e3f62403d26635bb", "6d44b6badb9521bdafc83b84bfd4ce3dbc2eae270ad22b676c84e356fab81c9c", "41cfad12a1964a1e5f534dd3b247f6b9e80fb6e64772ad9ff7f7f8cee375b94c", "673fe9e5a964a3d2fd2fea41be5a4bc8e6fcc958422f6636d26c25156902f0ea", "880e8f2691c0ebc2292b8e03733ad96796a4f9792d1a604a28e575fbfcc56b45", "a1796d57ebf723c58b8518c6c70ee602f772afe6bc3b127a74804c0944957162", "3618d980b28f432b383d8658c0d8ee8c087c206df59a1d535c7512c85fa745c3", "e05db943b9ef0f90c90989d2bd29e74ece5cc99882d7ef75832b575cd14f8c88", "4c490979a140a3d4a4661ccb0804c08aabb3ee15fc941d473f866fa04cef0613", "414e11e90180869501a2bf1762be6e3e5c34eaa2b9eb7510b7a77b7bf32f08d2", "e0e435e50a8bb83d1610b4288f11a4d313db0b47a61929078990508185243bbc", "7f8da04ec98800942cb7b9bb2fe795b51cdb91b2ff48b3451d4e74da0414b6ef", "1d1f6d1c6e1afb8a6c3e6b93d708cebbfcaab5fc8d27c7d44ff5454d8906e3e9", } for i, d := range data { tree.SetData(int32(i), []byte(d)) expected, _ := hex.DecodeString(roots[i]) assert.Equal(t, expected, tree.Root().Bytes(), "Root %d not matched", i) } // Modifying some data blocks tree.SetData(0, []byte("a")) tree.SetData(21, []byte("v")) expected, _ := hex.DecodeString("ec4446ea16b8f82083cc2d727b8f9e7b9c318e35bb37295a2e87064393572800") assert.Equal(t, expected, tree.Root().Bytes()) } ================================================ FILE: util/prompt/prompt.go ================================================ //nolint:forbidigo // enable printing function for prompt package package prompt import ( "errors" "fmt" "os" "strconv" "strings" "github.com/manifoldco/promptui" ) func checkError(err error) { if err == nil { return } if errors.Is(err, promptui.ErrAbort) { return } if errors.Is(err, promptui.ErrInterrupt) || errors.Is(err, promptui.ErrEOF) { fmt.Printf("%v\n", err) os.Exit(1) } fmt.Printf("Prompt failed: %v\n", err) os.Exit(1) } // PromptPassword prompts the user to enter a password. // If confirmation is true, the user will be asked to re-enter the password // for confirmation. func PromptPassword(label string, confirmation bool) string { prompt := promptui.Prompt{ Label: label, Mask: '*', Pointer: promptui.PipeCursor, } password, err := prompt.Run() checkError(err) if confirmation { validate := func(input string) error { if input != password { return errors.New("passwords do not match") } return nil } confirmPrompt := promptui.Prompt{ Label: "Confirm password", Validate: validate, Mask: '*', Pointer: promptui.PipeCursor, } _, err := confirmPrompt.Run() checkError(err) } return password } // PromptConfirm prompts the user to confirm an operation. // It returns true if the user confirms (Y/y), otherwise false. // The program exits if the user aborts or if an unexpected error occurs. func PromptConfirm(label string) bool { prompt := promptui.Prompt{ Label: label, IsConfirm: true, Pointer: promptui.PipeCursor, } result, err := prompt.Run() checkError(err) if result != "" && strings.ToUpper(result[:1]) == "Y" { return true } return false } // PromptInput prompts the user for a string input. func PromptInput(label string) string { prompt := promptui.Prompt{ Label: label, Pointer: promptui.PipeCursor, } result, err := prompt.Run() checkError(err) return result } // PromptSelect displays a list of choices for the user to select from. // It returns the index of the selected item. func PromptSelect(label string, items []string) int { prompt := promptui.Select{ Label: label, Items: items, Pointer: promptui.PipeCursor, } choice, _, err := prompt.Run() checkError(err) return choice } // PromptInputWithSuggestion prompts the user for a string input, // showing a suggested default value. func PromptInputWithSuggestion(label, suggestion string) string { prompt := promptui.Prompt{ Label: label, Default: suggestion, Pointer: promptui.PipeCursor, } result, err := prompt.Run() checkError(err) return result } // PromptInputWithRange prompts the user to enter an integer value // within the specified range [min, max]. The default value is shown as a suggestion. func PromptInputWithRange(label string, def, min, max int) int { prompt := promptui.Prompt{ Label: label, Default: fmt.Sprintf("%v", def), Pointer: promptui.PipeCursor, Validate: func(input string) error { num, err := strconv.Atoi(input) if err != nil { return fmt.Errorf("invalid number %q", input) } if num < min || num > max { return fmt.Errorf("enter a number between %v and %v", min, max) } return nil }, } result, err := prompt.Run() checkError(err) num, _ := strconv.Atoi(result) return num } ================================================ FILE: util/ratelimit/ratelimit.go ================================================ package ratelimit import ( "sync" "time" ) type RateLimit struct { lk sync.RWMutex referenceTime time.Time threshold int counter int window time.Duration } // NewRateLimit initializes a new RateLimit instance with the given threshold and window duration. func NewRateLimit(threshold int, window time.Duration) *RateLimit { return &RateLimit{ referenceTime: time.Now(), threshold: threshold, counter: 0, window: window, } } func (r *RateLimit) diff() time.Duration { return time.Since(r.referenceTime) } func (r *RateLimit) reset() { r.counter = 0 r.referenceTime = time.Now() } // AllowRequest increments the counter and checks if the rate limit is exceeded. // If the threshold is zero, it allows all requests. func (r *RateLimit) AllowRequest() bool { r.lk.Lock() defer r.lk.Unlock() // If the threshold is zero, allow all requests if r.threshold == 0 { return true } // Check if the window has expired and reset if necessary if r.diff() > r.window { r.reset() } r.counter++ // Check if the threshold is exceeded return r.counter <= r.threshold } ================================================ FILE: util/ratelimit/ratelimit_test.go ================================================ package ratelimit import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestRateLimit(t *testing.T) { threshold := 5 window := 100 * time.Millisecond rateLimit := NewRateLimit(threshold, window) t.Run("InitialState", func(t *testing.T) { assert.Equal(t, 0, rateLimit.counter) }) t.Run("AllowRequestWithinThreshold", func(t *testing.T) { for i := 0; i < threshold; i++ { assert.True(t, rateLimit.AllowRequest()) } assert.Equal(t, threshold, rateLimit.counter) }) t.Run("ExceedThreshold", func(t *testing.T) { assert.False(t, rateLimit.AllowRequest()) }) t.Run("ResetAfterWindow", func(t *testing.T) { time.Sleep(window + 10*time.Millisecond) assert.True(t, rateLimit.AllowRequest()) assert.Equal(t, 1, rateLimit.counter) }) t.Run("ResetMethod", func(t *testing.T) { rateLimit.reset() assert.Equal(t, 0, rateLimit.counter) assert.True(t, rateLimit.AllowRequest()) assert.Equal(t, 1, rateLimit.counter) }) t.Run("DiffMethod", func(t *testing.T) { assert.LessOrEqual(t, rateLimit.diff(), window) }) } func TestRateLimitZeroThreshold(t *testing.T) { window := 100 * time.Millisecond r := NewRateLimit(0, window) assert.True(t, r.AllowRequest()) assert.Zero(t, r.counter) } ================================================ FILE: util/shell/shell.go ================================================ package shell import ( "bytes" "fmt" "os" "slices" "strings" "github.com/c-bata/go-prompt" "github.com/google/shlex" "github.com/spf13/cobra" "github.com/spf13/pflag" "golang.org/x/term" ) type lexer struct { root *cobra.Command refresh func() *cobra.Command cache map[string][]prompt.Suggest stdin *term.State } // New creates a Cobra CLI command named "interactive" which runs an interactive shell prompt for the root command. func New(root *cobra.Command, refresh func() *cobra.Command, opts ...prompt.Option) *cobra.Command { lexer := &lexer{ root: root, refresh: refresh, cache: make(map[string][]prompt.Suggest), } prefix := fmt.Sprintf("> %s ", root.Name()) opts = append(opts, prompt.OptionPrefix(prefix), prompt.OptionShowCompletionAtStart()) return &cobra.Command{ Use: "interactive", Short: "Start pactus-shell in interactive mode", Run: func(cmd *cobra.Command, _ []string) { lexer.saveStdin() lexer.editCommandTree(cmd) prompt.New(lexer.executor, lexer.completer, opts...).Run() lexer.restoreStdin() }, } } func (s *lexer) editCommandTree(shell *cobra.Command) { s.root.RemoveCommand(shell) // Hide the "completion" command if cmd, _, err := s.root.Find([]string{"completion"}); err == nil { // TODO: Remove this command cmd.Hidden = true } s.root.AddCommand(&cobra.Command{ Use: "exit", Short: "Exit the interactive shell", Run: func(*cobra.Command, []string) { // TODO: Exit cleanly without help from the os package os.Exit(0) }, }) initDefaultHelpFlag(s.root) } func initDefaultHelpFlag(cmd *cobra.Command) { cmd.InitDefaultHelpFlag() for _, subcommand := range cmd.Commands() { initDefaultHelpFlag(subcommand) } } func (s *lexer) saveStdin() { state, err := term.GetState(int(os.Stdin.Fd())) if err != nil { return } s.stdin = state } func (s *lexer) executor(line string) { // Allow command to read from stdin s.restoreStdin() args, _ := shlex.Split(line) _ = execute(s.root, args) if s.refresh != nil { s.root = s.refresh() s.editCommandTree(s.root) } else { if cmd, _, err := s.root.Find(args); err == nil { cmd.Flags().VisitAll(func(flag *pflag.Flag) { flag.Changed = false }) } } s.cache = make(map[string][]prompt.Suggest) } func (s *lexer) restoreStdin() { if s.stdin != nil { _ = term.Restore(int(os.Stdin.Fd()), s.stdin) } } func (s *lexer) completer(doc prompt.Document) []prompt.Suggest { args, err := buildCompletionArgs(doc.CurrentLine()) if err != nil { return nil } if !isFlag(args[len(args)-1]) { // Clear partial strings to generate all possible completions args[len(args)-1] = "" } key := strings.Join(args, " ") suggestions, ok := s.cache[key] if !ok { out, err := readCommandOutput(s.root, args) if err != nil { return nil } suggestions = parseSuggestions(out) s.cache[key] = suggestions } return prompt.FilterHasPrefix(suggestions, doc.GetWordBeforeCursor(), true) } func buildCompletionArgs(input string) ([]string, error) { args, err := shlex.Split(input) args = append([]string{"__complete"}, args...) if input == "" || input[len(input)-1] == ' ' { args = append(args, "") } return args, err } func readCommandOutput(cmd *cobra.Command, args []string) (string, error) { buf := new(bytes.Buffer) stdout := cmd.OutOrStdout() stderr := os.Stderr cmd.SetOut(buf) _, os.Stderr, _ = os.Pipe() err := execute(cmd, args) cmd.SetOut(stdout) os.Stderr = stderr return buf.String(), err } func execute(cmd *cobra.Command, args []string) error { if cobraCmd, _, err := cmd.Find(args); err == nil { // Reset flag values between runs due to a limitation in Cobra cobraCmd.Flags().VisitAll(func(flag *pflag.Flag) { if val, ok := flag.Value.(pflag.SliceValue); ok { _ = val.Replace([]string{}) } else { _ = flag.Value.Set(flag.DefValue) } _ = cobraCmd.Flags().SetAnnotation(flag.Name, cobra.BashCompOneRequiredFlag, []string{"false"}) }) cobraCmd.InitDefaultHelpFlag() } cmd.SetArgs(args) return cmd.Execute() } func parseSuggestions(out string) []prompt.Suggest { suggestions := make([]prompt.Suggest, 0) x := strings.Split(out, "\n") if len(x) < 2 { return nil } for _, line := range x[:len(x)-2] { tokens := strings.SplitN(line, "\t", 2) if isShorthandFlag(tokens[0]) { continue } suggestion := prompt.Suggest{Text: escapeSpecialCharacters(tokens[0])} if len(tokens) > 1 { suggestion.Description = tokens[1] } suggestions = append(suggestions, suggestion) } slices.SortFunc(suggestions, func(a, b prompt.Suggest) int { aText, bText := a.Text, b.Text aFlag, bFlag := isFlag(aText), isFlag(bText) switch { case aFlag && bFlag: return strings.Compare(aText, bText) case aFlag: return 1 case bFlag: return -1 default: return strings.Compare(aText, bText) } }) return suggestions } func escapeSpecialCharacters(val string) string { for _, c := range []string{`\`, `"`, "$", "`", "!"} { val = strings.ReplaceAll(val, c, `\`+c) } if strings.ContainsAny(val, " #&*;<>?[]|~") { val = fmt.Sprintf("%q", val) } return val } func isFlag(arg string) bool { return strings.HasPrefix(arg, "-") } func isShorthandFlag(arg string) bool { return isFlag(arg) && !strings.HasPrefix(arg, "--") } ================================================ FILE: util/shell/shell_test.go ================================================ package shell import ( "errors" "testing" "github.com/c-bata/go-prompt" "github.com/spf13/cobra" "github.com/stretchr/testify/require" ) func TestBuildCompletionArgs_Empty(t *testing.T) { args, err := buildCompletionArgs("") require.NoError(t, err) expected := []string{"__complete", ""} require.Equal(t, expected, args) } func TestBuildCompletionArgs_CurrentArg(t *testing.T) { args, err := buildCompletionArgs("a b") require.NoError(t, err) expected := []string{"__complete", "a", "b"} require.Equal(t, expected, args) } func TestBuildCompletionArgs_MultiwordString(t *testing.T) { args, err := buildCompletionArgs(`a "b c"`) require.NoError(t, err) expected := []string{"__complete", "a", "b c"} require.Equal(t, expected, args) } func TestBuildCompletionArgs_NextArg(t *testing.T) { args, err := buildCompletionArgs("a b ") require.NoError(t, err) expected := []string{"__complete", "a", "b", ""} require.Equal(t, expected, args) } func TestReadCommandOutput_Stdout(t *testing.T) { cmd := &cobra.Command{ Use: "command", Run: func(cmd *cobra.Command, _ []string) { cmd.Print("out") }, } out, err := readCommandOutput(cmd, []string{}) require.NoError(t, err) require.Equal(t, "out", out) } func TestReadCommandOutput_Stderr(t *testing.T) { cmd := &cobra.Command{ Use: "command", Run: func(cmd *cobra.Command, _ []string) { cmd.PrintErr("out") }, } out, err := readCommandOutput(cmd, []string{}) require.NoError(t, err) require.Empty(t, out) } func TestReadCommandOutput_Err(t *testing.T) { cmd := &cobra.Command{ Use: "command", RunE: func(_ *cobra.Command, _ []string) error { return errors.New("err") }, } _, err := readCommandOutput(cmd, []string{}) require.Error(t, err) } func TestParseSuggestions_WithDescription(t *testing.T) { out := `command-with-description description :4 Completion ended with directive: ShellCompDirectiveNoFileComp` expected := []prompt.Suggest{{Text: "command-with-description", Description: "description"}} require.Equal(t, expected, parseSuggestions(out)) } func TestParseSuggestions_WithoutDescription(t *testing.T) { out := `command-without-description :4 Completion ended with directive: ShellCompDirectiveNoFileComp` expected := []prompt.Suggest{{Text: "command-without-description"}} require.Equal(t, expected, parseSuggestions(out)) } func TestParseSuggestions_HideShorthandFlags(t *testing.T) { out := `--flag A flag. -f A flag. :4 Completion ended with directive: ShellCompDirectiveNoFileComp` expected := []prompt.Suggest{{Text: "--flag", Description: "A flag."}} require.Equal(t, expected, parseSuggestions(out)) } func TestParseSuggestions_Sort(t *testing.T) { out := `b a :4 Completion ended with directive: ShellCompDirectiveNoFileComp` expected := []prompt.Suggest{{Text: "a"}, {Text: "b"}} require.Equal(t, expected, parseSuggestions(out)) } func TestEscapeSpecialCharacters_Spaces(t *testing.T) { require.Equal(t, `"string with spaces"`, escapeSpecialCharacters("string with spaces")) } func TestEscapeSpecialCharacters_All(t *testing.T) { require.Equal(t, "\\\\\\\"\\$\\`\\!", escapeSpecialCharacters("\\\"$`!")) } func TestEditCommandTree_RemoveShell(t *testing.T) { root := &cobra.Command{} sh := &cobra.Command{Use: "lexer"} root.AddCommand(sh) s := &lexer{root: root} s.editCommandTree(sh) require.False(t, hasSubcommand(root, "lexer")) } func TestEditCommandTree_AddExit(t *testing.T) { root := &cobra.Command{} s := &lexer{root: root} s.editCommandTree(nil) require.True(t, hasSubcommand(root, "exit")) } func hasSubcommand(cmd *cobra.Command, name string) bool { for _, subcommand := range cmd.Commands() { if subcommand.Name() == name { return true } } return false } func TestNew_CommandProperties(t *testing.T) { // Test that the New function creates a command with correct properties root := &cobra.Command{} interactiveCmd := New(root, nil) require.Equal(t, "interactive", interactiveCmd.Use) require.Equal(t, "Start pactus-shell in interactive mode", interactiveCmd.Short) require.NotNil(t, interactiveCmd.Run) } func TestNew_CommandName(t *testing.T) { // Test that the command is named "interactive" not "shell" root := &cobra.Command{} interactiveCmd := New(root, nil) require.Equal(t, "interactive", interactiveCmd.Name()) require.NotEqual(t, "shell", interactiveCmd.Name()) } func TestNew_WithOptions(t *testing.T) { // Test that New function accepts prompt options root := &cobra.Command{} // Test with some dummy options interactiveCmd := New(root, nil, prompt.OptionPrefix("test> "), prompt.OptionShowCompletionAtStart(), ) require.Equal(t, "interactive", interactiveCmd.Use) require.NotNil(t, interactiveCmd.Run) } func TestNew_InteractiveCommandCreation(t *testing.T) { // Test that the New function creates a command with the exact changed properties root := &cobra.Command{} interactiveCmd := New(root, nil) // Verify the specific changed lines require.Equal(t, "interactive", interactiveCmd.Use) require.Equal(t, "Start pactus-shell in interactive mode", interactiveCmd.Short) require.NotNil(t, interactiveCmd.Run) // Test that it's not the old values require.NotEqual(t, "shell", interactiveCmd.Use) require.NotEqual(t, "Start an interactive shell", interactiveCmd.Short) } func TestNew_WithAllOptions(t *testing.T) { root := &cobra.Command{} refresh := func() *cobra.Command { return root } interactiveCmd := New(root, refresh, prompt.OptionPrefix("test> "), prompt.OptionShowCompletionAtStart(), prompt.OptionSuggestionBGColor(prompt.Black), prompt.OptionSuggestionTextColor(prompt.Green), ) // Verify the changed properties are correct require.Equal(t, "interactive", interactiveCmd.Use) require.Equal(t, "Start pactus-shell in interactive mode", interactiveCmd.Short) require.NotNil(t, interactiveCmd.Run) } func TestNew_CommandNameNotShell(t *testing.T) { // Explicitly test that the command is NOT named "shell" anymore root := &cobra.Command{} interactiveCmd := New(root, nil) // This ensures we're testing the actual change require.NotEqual(t, "shell", interactiveCmd.Name()) require.Equal(t, "interactive", interactiveCmd.Name()) } func TestChangedLinesExecution(t *testing.T) { root := &cobra.Command{} cmd := New(root, nil) // Verify the exact changes require.Equal(t, "interactive", cmd.Use) require.Equal(t, "Start pactus-shell in interactive mode", cmd.Short) require.NotEqual(t, "shell", cmd.Use) require.NotEqual(t, "Start an interactive shell", cmd.Short) } ================================================ FILE: util/simplemerkle/merkle.go ================================================ // This file contains code from the btcd project, // which is licensed under the ISC License. // // Original license: https://github.com/btcsuite/btcd/blob/master/LICENSE // package simplemerkle import ( "math" "github.com/pactus-project/pactus/crypto/hash" ) var hasher func([]byte) hash.Hash func init() { hasher = hash.CalcHash } type Tree struct { merkles []*hash.Hash } // nextPowerOfTwo returns the smallest power of two that is greater than or equal to // the given number. If the number is already a power of two, it returns the number itself. func nextPowerOfTwo(num int) int { // Return the number if it's already a power of 2. if num&(num-1) == 0 { return num } // Figure out and return the next power of two. exponent := uint(math.Log2(float64(num))) + 1 return 1 << exponent // 2^exponent } // HashMerkleBranches takes two hashes, treated as the left and right tree // nodes, and returns the hash of their concatenation. This is a helper // function used to aid in the generation of a merkle tree. func HashMerkleBranches(left, right *hash.Hash) *hash.Hash { // Concatenate the left and right nodes. var h [hash.HashSize * 2]byte copy(h[:hash.HashSize], left.Bytes()) copy(h[hash.HashSize:], right.Bytes()) newHash := hasher(h[:]) return &newHash } func NewTreeFromSlices(slices [][]byte) *Tree { hashes := make([]hash.Hash, len(slices)) for i, b := range slices { hashes[i] = hasher(b) } return NewTreeFromHashes(hashes) } func NewTreeFromHashes(hashes []hash.Hash) *Tree { if len(hashes) == 0 { return nil } // Calculate how many entries are required to hold the binary merkle // tree as a linear array and create an array of that size. nextPoT := nextPowerOfTwo(len(hashes)) arraySize := nextPoT*2 - 1 merkles := make([]*hash.Hash, arraySize) for i := range hashes { merkles[i] = &hashes[i] } // Start the array offset after the last transaction and adjusted to the // next power of two. offset := nextPoT for index := 0; index < arraySize-1; index += 2 { switch { // When there is no left child node, the parent is nil too. case merkles[index] == nil: merkles[offset] = nil // When there is no right child, the parent is generated by // hashing the concatenation of the left child with itself. case merkles[index+1] == nil: newHash := HashMerkleBranches(merkles[index], merkles[index]) merkles[offset] = newHash // The normal case sets the parent node to the double sha256 // of the concatenation of the left and right children. default: newHash := HashMerkleBranches(merkles[index], merkles[index+1]) merkles[offset] = newHash } offset++ } return &Tree{merkles: merkles} } func (tree *Tree) Root() hash.Hash { if tree == nil { return hash.UndefHash } h := tree.merkles[len(tree.merkles)-1] if h != nil { return *h } return hash.UndefHash } func (tree *Tree) Depth() int { if tree == nil { return 0 } return int(math.Log2(float64(len(tree.merkles)))) } ================================================ FILE: util/simplemerkle/merkle_test.go ================================================ package simplemerkle import ( "crypto/sha256" "encoding/hex" "fmt" "testing" "github.com/pactus-project/pactus/crypto/hash" "github.com/stretchr/testify/assert" ) func strToHash(str string) hash.Hash { h := hash.CalcHash([]byte(str)) return h } func TestMerkleTree(t *testing.T) { slices := [][]byte{[]byte("a"), []byte("b"), []byte("c")} hashes := []hash.Hash{ strToHash("a"), strToHash("b"), strToHash("c"), } tree1 := NewTreeFromHashes(hashes) if tree1.Root().String() != "e6061997a9011668bcf216020aaad9cc7f5f34d5b6f78f1e63ef6257c1aa1f37" { t.Error("invalid merkle root") } tree2 := NewTreeFromSlices(slices) assert.Equal(t, tree1.Root(), tree2.Root()) fmt.Println(tree2.ToString()) } func TestMerkleTreeDepth2(t *testing.T) { slices := [][]byte{[]byte("a"), []byte("b"), []byte("c")} hashes := []hash.Hash{ strToHash("a"), strToHash("b"), strToHash("c"), } tree1 := NewTreeFromHashes(hashes) if tree1.Root().String() != "e6061997a9011668bcf216020aaad9cc7f5f34d5b6f78f1e63ef6257c1aa1f37" { t.Error("invalid merkle root") } tree2 := NewTreeFromSlices(slices) assert.Equal(t, tree1.Root(), tree2.Root()) fmt.Println(tree2.ToString()) } func TestMerkleTree_Bitcoin_Block100000(t *testing.T) { hasher = func(data []byte) hash.Hash { first := sha256.Sum256(data) second := sha256.Sum256(first[:]) h, _ := hash.FromBytes(second[:]) return h } // Block 100000 in bitcoin root, _ := hash.FromString("6657A9252AACD5C0B2940996ECFF952228C3067CC38D4885EFB5A4AC4247E9F3") hash1, _ := hash.FromString("876DD0A3EF4A2816FFD1C12AB649825A958B0FF3BB3D6F3E1250F13DDBF0148C") hash2, _ := hash.FromString("C40297F730DD7B5A99567EB8D27B78758F607507C52292D02D4031895B52F2FF") hash3, _ := hash.FromString("C46E239AB7D28E2C019B6D66AD8FAE98A56EF1F21AEECB94D1B1718186F05963") hash4, _ := hash.FromString("1D0CB83721529A062D9675B98D6E5C587E4A770FC84ED00ABC5A5DE04568A6E9") hashes := []hash.Hash{ hash1, hash2, hash3, hash4, } tree := NewTreeFromHashes(hashes) assert.Equal(t, root, tree.Root()) assert.Equal(t, 2, tree.Depth()) } func TestMerkleTree_Bitcoin_Block153342(t *testing.T) { hasher = func(data []byte) hash.Hash { first := sha256.Sum256(data) second := sha256.Sum256(first[:]) h, _ := hash.FromBytes(second[:]) return h } // Block 153342 in bitcoin wantMerkle, _ := hex.DecodeString("dd8ee246e19ec5c77ddd46c1138e8af6a272da4dbb6500ea74a79c0bf89e2c07") hash1, _ := hash.FromString("216404816ca6261f9206d471d0403ba49bda4264719d879819fbda9849781e62") hash2, _ := hash.FromString("56f2602c15cb0b8e0b38e54b2961a2e541a7febbe852516cd425aa5fb72c5578") hash3, _ := hash.FromString("0d065da59871386321c2c9b2e4b6482426bcce88600ab7f55f0d27b9916a9e0c") hash4, _ := hash.FromString("1129038c38783f4c4241e54d9d702965b305b8d1e54c091fdd9f9df21240586e") hash5, _ := hash.FromString("81461f9e0e093dad14d0c5fb3978431a321bf61de33512d6cc344edb86f359f3") hash6, _ := hash.FromString("22140f4b15d76ff27d657a731fdc3040487c22ee3577c6522239d9cfbe0292ad") hash7, _ := hash.FromString("0fa273bce5137a0dbffac068ebb6f1ebe64e6be2b00cdae5a967edeb0cd96b93") hash8, _ := hash.FromString("cab481631e7f2f7d864a65d23c34bd357f46ecba60bb8117f55ed43232aa75e5") hash9, _ := hash.FromString("dffea4c267fa6949111fed23b15977d5e2efa82fefd9cd5ac81e38518d2c2bef") hash10, _ := hash.FromString("ed9f4ee5e07a47a7026725173de32efa7372243117be1aa7f60a650aef075475") hash11, _ := hash.FromString("8822c80afa3eb84bc3603509b8b6deeee37cf771ca7b49d3dd73294e05f7b29f") hash12, _ := hash.FromString("23ad44934167cc712b358f2a097b7316ca2b3c2f34472017273969e7c7e5cdb4") hash13, _ := hash.FromString("c1dc3762c6a57757a9aa895b8229613d96f272f79d14c9854132b980eaa2a2c4") root, _ := hash.FromBytes(wantMerkle) hashes := []hash.Hash{ hash1, hash2, hash3, hash4, hash5, hash6, hash7, hash8, hash9, hash10, hash11, hash12, hash13, } tree := NewTreeFromHashes(hashes) assert.Equal(t, root, tree.Root()) assert.Equal(t, 4, tree.Depth()) fmt.Println(tree.ToString()) assert.Contains(t, tree.ToString(), root.String()) right, _ := hash.FromString("4a3ee07bb7baf6dfa265fa5c85a8955c8e79ddab0f70657a14df5744a103e24d") left, _ := hash.FromString("114799e25e6dc376d65fd5406516919e1e619b89316be91ea064a69400472d1e") root2 := HashMerkleBranches(&left, &right) assert.Equal(t, root, *root2) } ================================================ FILE: util/simplemerkle/printing.go ================================================ package simplemerkle import ( "strings" ) func (tree *Tree) ToString() string { nodes := tree.merkles if len(nodes) == 0 { return "" } lines := make([]string, len(tree.merkles)) depth := 1 offset := 0 indent := "" j := 1 for i := len(nodes) - 1; i >= 0; i-- { if j == (1 << depth) { lines[offset] += "\n" indent += " " depth++ } if nodes[i] != nil { lines[offset] = indent + nodes[i].String() } else { lines[offset] = indent + "" } j++ offset++ } return strings.Join(lines, "\n") } ================================================ FILE: util/slice.go ================================================ package util import ( "bytes" "compress/gzip" "crypto/subtle" "encoding/binary" "math/rand" "slices" ) func Uint16ToBytesLE(n uint16) []byte { bs := make([]byte, 2) binary.LittleEndian.PutUint16(bs, n) return bs } func Int16ToBytesLE(n int16) []byte { return Uint16ToBytesLE(uint16(n)) } func BytesToUint16LE(bs []byte) uint16 { return binary.LittleEndian.Uint16(bs) } func BytesToInt16LE(bs []byte) int16 { return int16(BytesToUint16LE(bs)) } func Uint32ToBytesLE(n uint32) []byte { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, n) return bs } func Int32ToBytesLE(n int32) []byte { return Uint32ToBytesLE(uint32(n)) } func BytesToUint32LE(bs []byte) uint32 { return binary.LittleEndian.Uint32(bs) } func BytesToInt32LE(bs []byte) int32 { return int32(BytesToUint32LE(bs)) } func Uint64ToBytesLE(n uint64) []byte { bs := make([]byte, 8) binary.LittleEndian.PutUint64(bs, n) return bs } func Int64ToBytesLE(n int64) []byte { return Uint64ToBytesLE(uint64(n)) } func BytesToUint64LE(bs []byte) uint64 { n := binary.LittleEndian.Uint64(bs) return n } func BytesToInt64LE(bs []byte) int64 { return int64(BytesToUint64LE(bs)) } // StringToBytes converts a string to a slice of bytes. func StringToBytes(s string) []byte { return []byte(s) } func CompressBuffer(data []byte) ([]byte, error) { var buf bytes.Buffer gz := gzip.NewWriter(&buf) if _, err := gz.Write(data); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } return buf.Bytes(), nil } func DecompressBuffer(s []byte) ([]byte, error) { buf := bytes.NewBuffer(s) reader, err := gzip.NewReader(buf) if err != nil { return nil, err } var res bytes.Buffer if _, err = res.ReadFrom(reader); err != nil { return nil, err } return res.Bytes(), nil } // Subtracts removes elements of slice2 from slice1 while preserving order. // Examples: // // [1,2,3,4] - [1,2] = [3,4] // [1,2,3,4] - [2,4] = [1,3] // [1,2,3,4] - [4,2] = [1,3] // [1,2,3,4] - [4,5] = [1,2,3] func Subtracts(slice1, slice2 []int32) []int32 { sub := []int32{} if slice2 == nil { return slice1 } for _, num1 := range slice1 { found := slices.Contains(slice2, num1) if !found { sub = append(sub, num1) } } return sub } // SafeCmp compares two slices with constant time. // Note that we are using the subtle.ConstantTimeCompare() function for this // to help prevent timing attacks. func SafeCmp(left, right []byte) bool { return subtle.ConstantTimeCompare(left, right) == 1 } // Merge accepts multiple slices and returns a single merged slice. func Merge[T any](slices ...[]T) []T { var totalLength int // Calculate the total length of the merged slice. for _, slice := range slices { totalLength += len(slice) } // Create a merged slice with the appropriate capacity. merged := make([]T, 0, totalLength) // Append each input slice to the merged slice. for _, slice := range slices { merged = append(merged, slice...) } return merged } // Reverse replaces the contents of a slice with the same elements in reverse // order. func Reverse[S ~[]E, E any](slice S) { for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 { slice[i], slice[j] = slice[j], slice[i] } } // PadToLeft grows the slice to the given length by prepending zero-valued // elements if necessary. func PadToLeft[T any](slice []T, length int) []T { if len(slice) < length { pad := make([]T, length-len(slice), length+len(slice)) slice = append(pad, slice...) } return slice } // PadToRight grows the slice to the given length by appending zero-valued // elements if necessary. func PadToRight[T any](slice []T, length int) []T { if len(slice) < length { pad := make([]T, length-len(slice)) slice = append(slice, pad...) } return slice } // IsSubset checks if subSet is a subset of parentSet. // It returns true if all elements of subSet are in parentSet. func IsSubset[T comparable](parentSet, subSet []T) bool { lastIndex := 0 for i := 0; i < len(subSet); i++ { matchFound := false for j := lastIndex; j < len(parentSet); j++ { if subSet[i] == parentSet[j] { matchFound = true lastIndex = j break } } if !matchFound { return false } } return true } // RemoveFirstOccurrenceOf removes the first occurrence of element from slice. // It returns the modified slice and a boolean indicating whether an element was removed. func RemoveFirstOccurrenceOf[T comparable](slice []T, element T) ([]T, bool) { for i, v := range slice { if v == element { return append(slice[:i], slice[i+1:]...), true } } return slice, false } // Trim truncates a slice to the given length. func Trim[T any](slice []T, newLength int) []T { if newLength <= len(slice) { return slice[:newLength] } return slice } // Shuffle randomly permutes the elements of slice in place. func Shuffle[T any](slice []T) { rand.Shuffle(len(slice), func(i, j int) { slice[i], slice[j] = slice[j], slice[i] }) } // Prepend adds elements to the beginning of a slice and returns the modified slice. func Prepend[T any](slice []T, elements ...T) []T { return append(elements, slice...) } ================================================ FILE: util/slice_test.go ================================================ package util import ( "encoding/hex" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSliceToInt16(t *testing.T) { tests := []struct { in int16 slice []byte }{ {MinInt16, []byte{0x00, 0x80}}, {int16(-128), []byte{0x80, 0xff}}, {int16(-1), []byte{0xff, 0xff}}, {int16(0), []byte{0x00, 0x00}}, {int16(1), []byte{0x01, 0x00}}, {int16(256), []byte{0x00, 0x01}}, {MaxInt16, []byte{0xff, 0x7f}}, } for _, tt := range tests { s1 := Uint16ToBytesLE(uint16(tt.in)) s2 := Int16ToBytesLE(tt.in) assert.Equal(t, s1, s2) assert.Equal(t, tt.slice, s1) v1 := BytesToInt16LE(tt.slice) v2 := BytesToUint16LE(tt.slice) assert.Equal(t, int16(v2), v1) assert.Equal(t, tt.in, v1) } } func TestSliceToInt32(t *testing.T) { tests := []struct { in int32 slice []byte }{ {MinInt32, []byte{0x00, 0x00, 0x00, 0x80}}, {int32(-128), []byte{0x80, 0xff, 0xff, 0xff}}, {int32(-1), []byte{0xff, 0xff, 0xff, 0xff}}, {int32(0), []byte{0x00, 0x00, 0x00, 0x00}}, {int32(1), []byte{0x01, 0x00, 0x00, 0x00}}, {int32(256), []byte{0x00, 0x01, 0x00, 0x00}}, {MaxInt32, []byte{0xff, 0xff, 0xff, 0x7f}}, } for _, tt := range tests { s1 := Uint32ToBytesLE(uint32(tt.in)) s2 := Int32ToBytesLE(tt.in) assert.Equal(t, s1, s2) assert.Equal(t, tt.slice, s1) v1 := BytesToInt32LE(tt.slice) v2 := BytesToUint32LE(tt.slice) assert.Equal(t, int32(v2), v1) assert.Equal(t, tt.in, v1) } } func TestSliceToInt64(t *testing.T) { tests := []struct { in int64 slice []byte }{ {MinInt64, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}}, {int64(-128), []byte{0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {int64(-1), []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {int64(0), []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {int64(1), []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {int64(256), []byte{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {MaxInt64, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}}, } for _, tt := range tests { s1 := Uint64ToBytesLE(uint64(tt.in)) s2 := Int64ToBytesLE(tt.in) assert.Equal(t, s1, s2) assert.Equal(t, tt.slice, s1) v1 := BytesToInt64LE(tt.slice) v2 := BytesToUint64LE(tt.slice) assert.Equal(t, int64(v2), v1) assert.Equal(t, tt.in, v1) } } func TestCompress(t *testing.T) { a := []byte{1, 2, 3, 4, 5, 6, 7} c, err := CompressBuffer(a) require.NoError(t, err) b, err := DecompressBuffer(c) require.NoError(t, err) assert.Equal(t, a, b) } func TestDecompress(t *testing.T) { data, _ := hex.DecodeString( "1f8b08000000000000ff5accb8929191492afefe9620e60805060280254221ac2238cb57f8d6da3ecfc47b617bd47bf80fbe503b11b7aef3" + "85a6c0ba159a2142ac110a1d8f2e447cd46a3f3d71d6fc5c9eac45377ec4efffa0b76c33bb1377fead15f5cdf7d9085bc44e58094784c216" + "9fcd92c947ee35a43a49ff5d57b563eeaad9415b8ed6d685bd72aaf9afd3b5898b334455a26edf71fd634957941ead7f15ad5fe0e96517ce" + "f48d79216323616702020000ffffa63359ef1b010000") _, err := DecompressBuffer(data[1:]) require.Error(t, err) _, err = DecompressBuffer(data) require.NoError(t, err) } func TestSubtractAndSubset(t *testing.T) { t.Run("Case 1", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{1, 2, 3} s3 := Subtracts(s1, s2) assert.Equal(t, []int32{4}, s3) }) t.Run("Case 2", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{2, 3, 5} s3 := Subtracts(s1, s2) assert.Equal(t, []int32{1, 4}, s3) }) t.Run("Case 3", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{} s3 := Subtracts(s1, s2) assert.Equal(t, []int32{1, 2, 3, 4}, s3) }) t.Run("Case 4", func(t *testing.T) { s1 := []int32{} s2 := []int32{1, 2, 3, 4} s3 := Subtracts(s1, s2) assert.Equal(t, []int32{}, s3) }) t.Run("Case 5", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{1, 2, 3, 4} s3 := Subtracts(s1, s2) assert.Equal(t, []int32{}, s3) }) t.Run("Case 6", func(t *testing.T) { s1 := []int32{1, 3, 5} s2 := []int32{1, 2, 3, 4, 5} s3 := Subtracts(s1, s2) assert.Equal(t, []int32{}, s3) }) t.Run("Case 7", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s3 := Subtracts(s1, nil) assert.Equal(t, s3, s1) }) t.Run("Case 8", func(t *testing.T) { s2 := []int32{1, 2, 3, 4} s3 := Subtracts(nil, s2) assert.Equal(t, []int32{}, s3) }) } func TestSafeCmp(t *testing.T) { assert.True(t, SafeCmp([]byte{1, 2, 3}, []byte{1, 2, 3})) assert.False(t, SafeCmp([]byte{1, 2, 3, 3}, []byte{1, 2, 3})) } func TestMerge(t *testing.T) { tests := []struct { slices [][]byte merged []byte }{ {[][]byte{nil}, []byte{}}, {[][]byte{{0, 1, 2}}, []byte{0, 1, 2}}, {[][]byte{{}}, []byte{}}, {[][]byte{{}, {}}, []byte{}}, {[][]byte{{0}, {0}}, []byte{0, 0}}, {[][]byte{{0}, {1}, {2}}, []byte{0, 1, 2}}, } for _, tt := range tests { merged := Merge(tt.slices...) assert.Equal(t, tt.merged, merged) } } func TestReverse(t *testing.T) { tests := []struct { slice []byte reversed []byte }{ {[]byte{}, []byte{}}, {[]byte{0}, []byte{0}}, {[]byte{1, 2, 3}, []byte{3, 2, 1}}, {[]byte{1, 2}, []byte{2, 1}}, } for _, tt := range tests { Reverse(tt.slice) assert.Equal(t, tt.slice, tt.reversed) } } func TestPadToLeft(t *testing.T) { tests := []struct { in []int size int want []int }{ {[]int{1, 2, 3}, 5, []int{0, 0, 1, 2, 3}}, {[]int{1, 2, 3}, 3, []int{1, 2, 3}}, {[]int{1, 2, 3}, 2, []int{1, 2, 3}}, {[]int{}, 5, []int{0, 0, 0, 0, 0}}, {[]int{}, 0, []int{}}, } for _, tt := range tests { got := PadToLeft(tt.in, tt.size) assert.Equal(t, tt.want, got, "PadToLeft failed, got %v, want %v", got, tt.want) } } func TestPadToRight(t *testing.T) { tests := []struct { in []int size int want []int }{ {[]int{1, 2, 3}, 5, []int{1, 2, 3, 0, 0}}, {[]int{1, 2, 3}, 3, []int{1, 2, 3}}, {[]int{1, 2, 3}, 2, []int{1, 2, 3}}, {[]int{}, 4, []int{0, 0, 0, 0}}, {[]int{}, 0, []int{}}, } for _, tt := range tests { got := PadToRight(tt.in, tt.size) assert.Equal(t, tt.want, got, "PadToRight failed, got %v, want %v", got, tt.want) } } func TestIsSubset(t *testing.T) { tests := []struct { arr1, arr2 []int want bool }{ {[]int{11, 1, 13, 21, 3, 7}, []int{11, 3, 7}, true}, {[]int{11, 1, 13, 21, 3, 7}, []int{3, 11, 7}, false}, {[]int{1, 2, 3, 4, 5}, []int{1, 2, 3}, true}, {[]int{1, 2, 3}, []int{1, 2, 3, 4}, false}, {[]int{1, 2, 3, 4, 5}, []int{6, 7, 8}, false}, {[]int{}, []int{1, 2, 3, 4, 5}, false}, {[]int{1, 2, 3, 4, 5}, []int{}, true}, {[]int{}, []int{}, true}, } for _, tt := range tests { got := IsSubset(tt.arr1, tt.arr2) assert.Equal(t, tt.want, got, "isSubset(%v, %v) = %v; want %v", tt.arr1, tt.arr2, got, tt.want) } } func TestStringToBytes(t *testing.T) { tests := []struct { input string output []byte }{ {"Hello", []byte("Hello")}, {"Go", []byte("Go")}, {"", []byte("")}, } for _, tt := range tests { got := StringToBytes(tt.input) assert.Equal(t, tt.output, got, "StringToBytes('%s') = %v, want %v", tt.input, got, tt.output) } } func TestRemoveFirstOccurrenceOf(t *testing.T) { tests := []struct { name string s []int e int want []int removed bool }{ { name: "empty slice", s: []int{}, e: 1, want: []int{}, removed: false, }, { name: "element not in slice", s: []int{1, 2, 3}, e: 4, want: []int{1, 2, 3}, removed: false, }, { name: "element in slice", s: []int{1, 2, 3}, e: 2, want: []int{1, 3}, removed: true, }, { name: "two elements in slice", s: []int{1, 2, 2, 3}, e: 2, want: []int{1, 2, 3}, removed: true, }, } for _, tt := range tests { got, removed := RemoveFirstOccurrenceOf(tt.s, tt.e) assert.Equal(t, tt.want, got, "%s failed: got %v, want %v", tt.name, got, tt.want) assert.Equal(t, tt.removed, removed, "%s failed: got %v, want %v", tt.name, removed, tt.removed) } } func TestTrimSlice(t *testing.T) { tests := []struct { input []int newLength int want []int }{ {[]int{1, 2, 3, 4, 5}, 3, []int{1, 2, 3}}, {[]int{1}, 3, []int{1}}, {[]int{}, 3, []int{}}, {[]int{1, 2, 3, 4, 5}, 0, []int{}}, } for _, tt := range tests { got := Trim(tt.input, tt.newLength) assert.Equal(t, tt.want, got, "Trim() = %v, want %v", got, tt.want) } } func TestShuffle(t *testing.T) { // Create a slice with 100 integers ints := make([]int, 100) for i := range ints { ints[i] = i + 1 } originalInts := make([]int, len(ints)) copy(originalInts, ints) Shuffle(ints) assert.NotEqual(t, originalInts, ints, "ints slice was not shuffled") assert.ElementsMatch(t, originalInts, ints, "ints slice does not contain the same elements") } func TestPrepend(t *testing.T) { tests := []struct { slice []int elements []int want []int }{ {[]int{3, 4, 5}, []int{1, 2}, []int{1, 2, 3, 4, 5}}, {[]int{3, 4, 5}, []int{}, []int{3, 4, 5}}, {[]int{}, []int{1, 2}, []int{1, 2}}, {[]int{}, []int{}, []int{}}, } for _, tt := range tests { got := Prepend(tt.slice, tt.elements...) assert.Equal(t, tt.want, got, "Prepend(%v, %v) = %v; want %v", tt.slice, tt.elements, got, tt.want) } } ================================================ FILE: util/terminal/terminal.go ================================================ //nolint:forbidigo // enable printing function for terminal package package terminal import ( "bytes" "encoding/json" "fmt" "os" "strings" "github.com/k0kubun/go-ansi" "github.com/schollz/progressbar/v3" ) var terminalSupported = false func init() { terminalSupported = CheckTerminalSupported() } // CheckTerminalSupported returns true if the current terminal supports // ANSI escape sequences and advanced terminal features. func CheckTerminalSupported() bool { bad := map[string]bool{"": true, "dumb": true, "cons25": true} return !bad[strings.ToLower(os.Getenv("TERM"))] } func FatalErrorCheck(err error) { if err != nil { if terminalSupported { fmt.Printf("\033[31m%s\033[0m\n", err.Error()) } else { fmt.Printf("%s\n", err.Error()) } os.Exit(1) } } func PrintErrorMsgf(format string, args ...any) { format = "[ERROR] " + format if terminalSupported { // Print error msg with red color format = fmt.Sprintf("\033[31m%s\033[0m", format) } fmt.Printf(format+"\n", args...) } func PrintSuccessMsgf(format string, a ...any) { if terminalSupported { // Print successful msg with green color format = fmt.Sprintf("\033[32m%s\033[0m", format) } fmt.Printf(format+"\n", a...) } func PrintWarnMsgf(format string, a ...any) { if terminalSupported { // Print warning msg with yellow color format = fmt.Sprintf("\033[33m%s\033[0m", format) } fmt.Printf(format+"\n", a...) } func PrintInfoMsgf(format string, a ...any) { fmt.Printf(format+"\n", a...) } func PrintInfoMsgBoldf(format string, a ...any) { if terminalSupported { format = fmt.Sprintf("\033[1m%s\033[0m", format) } fmt.Printf(format+"\n", a...) } func PrintLine() { fmt.Println() } func PrintJSONData(data []byte) { var out bytes.Buffer err := json.Indent(&out, data, "", " ") FatalErrorCheck(err) PrintInfoMsgf(out.String()) } func PrintJSONObject(obj any) { data, err := json.Marshal(obj) FatalErrorCheck(err) PrintJSONData(data) } func ProgressBar(totalSize int64, barWidth int) *progressbar.ProgressBar { if barWidth < 15 { barWidth = 15 } opts := []progressbar.Option{ progressbar.OptionSetWriter(ansi.NewAnsiStdout()), progressbar.OptionEnableColorCodes(true), progressbar.OptionSetWidth(barWidth), progressbar.OptionSetElapsedTime(false), progressbar.OptionSetPredictTime(false), progressbar.OptionShowDescriptionAtLineEnd(), progressbar.OptionSetTheme(progressbar.Theme{ Saucer: "[green]=[reset]", SaucerHead: "[green]>[reset]", SaucerPadding: " ", BarStart: "[", BarEnd: "]", }), } return progressbar.NewOptions64(totalSize, opts...) } ================================================ FILE: util/terminal/terminal_test.go ================================================ package terminal import ( "bytes" "io" "os" "testing" "github.com/stretchr/testify/assert" ) // captureOutput is a helper function to capture the printed output of a function. func captureOutput(fun func()) string { // Redirect stdout to a buffer oldStdout := os.Stdout reader, writer, _ := os.Pipe() os.Stdout = writer // Capture the printed output outC := make(chan string) go func() { var buf bytes.Buffer _, _ = io.Copy(&buf, reader) outC <- buf.String() }() // Execute the function fun() // Reset stdout _ = writer.Close() os.Stdout = oldStdout out := <-outC return out } func TestPrintNotSupported(t *testing.T) { terminalSupported = false output := captureOutput(func() { PrintJSONObject([]int{1, 2, 3}) PrintLine() PrintInfoMsgBoldf("This is PrintInfoMsgBoldf: %s", "msg") PrintInfoMsgf("This is PrintInfoMsgf: %s", "msg") PrintSuccessMsgf("This is PrintSuccessMsgf: %s", "msg") PrintWarnMsgf("This is PrintWarnMsgf: %s", "msg") PrintErrorMsgf("This is PrintErrorMsgf: %s", "msg") }) expected := "[\n 1,\n 2,\n 3\n]\n" + "\n" + "This is PrintInfoMsgBoldf: msg\n" + "This is PrintInfoMsgf: msg\n" + "This is PrintSuccessMsgf: msg\n" + "This is PrintWarnMsgf: msg\n" + "[ERROR] This is PrintErrorMsgf: msg\n" assert.Equal(t, expected, output) } func TestPrintSupported(t *testing.T) { terminalSupported = true output := captureOutput(func() { PrintJSONObject([]int{1, 2, 3}) PrintLine() PrintInfoMsgBoldf("This is PrintInfoMsgBoldf: %s", "msg") PrintInfoMsgf("This is PrintInfoMsgf: %s", "msg") PrintSuccessMsgf("This is PrintSuccessMsgf: %s", "msg") PrintWarnMsgf("This is PrintWarnMsgf: %s", "msg") PrintErrorMsgf("This is PrintErrorMsgf: %s", "msg") }) expected := "[\n 1,\n 2,\n 3\n]\n" + "\n" + "\x1b[1mThis is PrintInfoMsgBoldf: msg\x1b[0m\n" + "This is PrintInfoMsgf: msg\n" + "\x1b[32mThis is PrintSuccessMsgf: msg\x1b[0m\n" + "\x1b[33mThis is PrintWarnMsgf: msg\x1b[0m\n" + "\x1b[31m[ERROR] This is PrintErrorMsgf: msg\x1b[0m\n" assert.Equal(t, expected, output) } ================================================ FILE: util/testsuite/logger.go ================================================ package testsuite import ( "github.com/pactus-project/pactus/util/logger" ) type OverrideStringer struct { obj logger.LogStringer name string } func NewOverrideLogStringer(name string, obj logger.LogStringer) *OverrideStringer { return &OverrideStringer{ obj: obj, name: name, } } func (o *OverrideStringer) LogString() string { return o.name + o.obj.LogString() } ================================================ FILE: util/testsuite/testsuite.go ================================================ package testsuite import ( "context" "encoding/hex" "fmt" "net" "testing" "time" "github.com/ezex-io/gopkg/testsuite" "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/committee" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/sortition" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/certificate" "github.com/pactus-project/pactus/types/proposal" "github.com/pactus-project/pactus/types/protocol" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" "github.com/pactus-project/pactus/util" "go.uber.org/mock/gomock" "golang.org/x/exp/slices" ) // TestSuite provides a set of helper functions for testing purposes. // All the random values are generated based on a logged seed. // By using a pre-generated seed, it is possible to reproduce failed tests // by re-evaluating all the random values. This helps in identifying and debugging // failures in testing conditions. type TestSuite struct { testsuite.TestSuite Ctrl *gomock.Controller } func GenerateSeed() int64 { return time.Now().UTC().UnixNano() } // NewTestSuiteFromSeed creates a new TestSuite with the given seed. func NewTestSuiteFromSeed(t *testing.T, seed int64) *TestSuite { t.Helper() ctrl := gomock.NewController(t) t.Cleanup(ctrl.Finish) return &TestSuite{ TestSuite: *testsuite.NewTestSuiteFromSeed(t, seed), Ctrl: ctrl, } } // NewTestSuite creates a new TestSuite by generating new seed. func NewTestSuite(t *testing.T) *TestSuite { t.Helper() seed := GenerateSeed() t.Logf("%v seed is %v", t.Name(), seed) return NewTestSuiteFromSeed(t, seed) } func (ts *TestSuite) MockingController() *gomock.Controller { return ts.Ctrl } type HeightRange struct { Min types.Height Max types.Height } func NewHeightRange() *HeightRange { return &HeightRange{ Min: 1e3, Max: 1e6, } } type HeightRangeOption func(*HeightRange) func HeightWithMin(min uint32) HeightRangeOption { return func(h *HeightRange) { h.Min = types.Height(min) } } func HeightWithMax(max uint32) HeightRangeOption { return func(h *HeightRange) { h.Max = types.Height(max) } } // RandHeight returns a random number between [1,000, 1,000,000] for block height. func (ts *TestSuite) RandHeight(opts ...HeightRangeOption) types.Height { h := NewHeightRange() for _, opt := range opts { opt(h) } return types.Height(ts.RandUint32( testsuite.WithMin(uint32(h.Min)), testsuite.WithMax(uint32(h.Max)))) } // RandRound returns a random number between [0, 10) for block round. func (ts *TestSuite) RandRound() types.Round { return types.Round(ts.RandInt16(testsuite.WithMax(int16(10)))) } // RandInt32NonZero returns a random int32 in [1, max]. func (ts *TestSuite) RandInt32NonZero(max int32) int32 { return ts.RandInt32(testsuite.WithMin(int32(1)), testsuite.WithMax(max)) } // RandUint32Max returns a random uint32 in [0, max). func (ts *TestSuite) RandUint32Max(max uint32) uint32 { return ts.RandUint32(testsuite.WithMax(max)) } // RandInt32Max returns a random int32 in [0, max). func (ts *TestSuite) RandInt32Max(max int32) int32 { return ts.RandInt32(testsuite.WithMax(max)) } // RandIntMax returns a random int in [0, max). func (ts *TestSuite) RandIntMax(max int) int { return ts.RandInt(testsuite.WithMax(max)) } // RandInt64Max returns a random int64 in [0, max). func (ts *TestSuite) RandInt64Max(max int64) int64 { return ts.RandInt64(testsuite.WithMax(max)) } // RandIntNonZero returns a random int in [1, max]. func (ts *TestSuite) RandIntNonZero(max int) int { return ts.RandInt(testsuite.WithMin(1), testsuite.WithMax(max)) } // RandAmount returns a random amount between [1e9, max). // If max is not set, it defaults to 100e9. func (ts *TestSuite) RandAmount(max ...amount.Amount) amount.Amount { maxAmt := amount.Amount(100e9) // default max amount if len(max) > 0 { maxAmt = max[0] } return ts.RandAmountRange(1e9, maxAmt) } // RandAmountRange returns a random amount between [min, max). func (ts *TestSuite) RandAmountRange(min, max amount.Amount) amount.Amount { return amount.Amount(ts.RandInt64(testsuite.WithMin(min.ToNanoPAC()), testsuite.WithMax(max.ToNanoPAC()))) } // RandFee returns a random fee between [1e7, max). // If max is not set, it defaults to 1e9. func (ts *TestSuite) RandFee(max ...amount.Amount) amount.Amount { maxFee := amount.Amount(1e9) // default max fee if len(max) > 0 { maxFee = max[0] } return ts.RandAmountRange(1e7, maxFee) } // RandBytes returns a slice of random bytes of the given length. func (ts *TestSuite) RandBytes(length int) []byte { buf := make([]byte, length) _, _ = ts.Rand.Read(buf) return buf } // RandSlice generates a random non-repeating slice of int32 elements with the specified length. func (ts *TestSuite) RandSlice(length int) []int32 { slice := []int32{} for { randInt := ts.RandInt32(testsuite.WithMax(int32(1000))) if !slices.Contains(slice, randInt) { slice = append(slice, randInt) } if len(slice) == length { return slice } } } // RandString generates a random string of the given length. func (ts *TestSuite) RandString(length int) string { const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" b := make([]byte, length) for i := range b { b[i] = letterBytes[ts.RandInt(testsuite.WithMax(52))] } return string(b) } // DecodingHex decodes the input string from hexadecimal format and returns the resulting byte slice. func (*TestSuite) DecodingHex(in string) []byte { d, _ := hex.DecodeString(in) return d } func (ts *TestSuite) RandKeyPair() (crypto.PublicKey, crypto.PrivateKey) { switch ts.RandInt(testsuite.WithMax(2)) { case 0: return ts.RandBLSKeyPair() case 1: return ts.RandEd25519KeyPair() } // Impossible return nil, nil } // RandBLSKeyPair generates a random BLS key pair for testing purposes. func (ts *TestSuite) RandBLSKeyPair() (*bls.PublicKey, *bls.PrivateKey) { buf := ts.RandBytes(bls.PrivateKeySize) prv, _ := bls.PrivateKeyFromBytes(buf) pub := prv.PublicKeyNative() return pub, prv } // RandEd25519KeyPair generates a random Ed25519 key pair for testing purposes. func (ts *TestSuite) RandEd25519KeyPair() (*ed25519.PublicKey, *ed25519.PrivateKey) { buf := ts.RandBytes(ed25519.PrivateKeySize) prv, _ := ed25519.PrivateKeyFromBytes(buf) pub := prv.PublicKeyNative() return pub, prv } // RandValKey generates a random validator key for testing purposes. func (ts *TestSuite) RandValKey() *bls.ValidatorKey { _, prv := ts.RandBLSKeyPair() return bls.NewValidatorKey(prv) } // RandBLSSignature generates a random BLS signature for testing purposes. func (ts *TestSuite) RandBLSSignature() *bls.Signature { _, prv := ts.RandBLSKeyPair() return prv.SignNative(ts.RandBytes(8)) } // RandEd25519Signature generates a random BLS signature for testing purposes. func (ts *TestSuite) RandEd25519Signature() *ed25519.Signature { _, prv := ts.RandEd25519KeyPair() return prv.SignNative(ts.RandBytes(8)) } // RandHash generates a random hash for testing purposes. func (ts *TestSuite) RandHash() hash.Hash { return hash.CalcHash(util.Int64ToBytesLE(ts.RandInt64(testsuite.WithMax(util.MaxInt64)))) } // RandAccAddress generates a random account address for testing purposes. func (ts *TestSuite) RandAccAddress() crypto.Address { useBLSAddress := ts.RandBool() if useBLSAddress { return crypto.NewAddress(crypto.AddressTypeBLSAccount, ts.RandBytes(20)) } return crypto.NewAddress(crypto.AddressTypeEd25519Account, ts.RandBytes(20)) } // RandValAddress generates a random validator address for testing purposes. func (ts *TestSuite) RandValAddress() crypto.Address { addr := crypto.NewAddress(crypto.AddressTypeValidator, ts.RandBytes(20)) return addr } // RandSeed generates a random VerifiableSeed for testing purposes. func (ts *TestSuite) RandSeed() sortition.VerifiableSeed { sig := ts.RandBLSSignature() seed, _ := sortition.VerifiableSeedFromBytes(sig.Bytes()) return seed } // RandProof generates a random Proof for testing purposes. func (ts *TestSuite) RandProof() sortition.Proof { _, prv := ts.RandBLSKeyPair() sig := prv.Sign(ts.RandHash().Bytes()) proof, _ := sortition.ProofFromBytes(sig.Bytes()) return proof } // RandPeerID returns a random peer ID. func (ts *TestSuite) RandPeerID() peer.ID { s := ts.RandBytes(32) id := [34]byte{0x12, 32} copy(id[2:], s) return peer.ID(id[:]) } // RandMultiAddress returns a random MultiAddress. func (ts *TestSuite) RandMultiAddress() string { return fmt.Sprintf("/dns/%s/udp/1234", ts.RandString(12)) } type AccountMaker struct { Number int32 Balance amount.Amount Address crypto.Address } type AccountMakerOption func(*AccountMaker) // NewAccountMaker creates a new instance of AccountMaker with random values. func (ts *TestSuite) NewAccountMaker() *AccountMaker { return &AccountMaker{ Number: ts.RandInt32(testsuite.WithMin(int32(1)), testsuite.WithMax(int32(100000))), Balance: ts.RandAmountRange(100e9, 1000e9), Address: ts.RandAccAddress(), } } // AccountWithAddress sets the address for the generated test account. func AccountWithAddress(address crypto.Address) AccountMakerOption { return func(am *AccountMaker) { am.Address = address } } // AccountWithNumber sets the account number for the generated test account. func AccountWithNumber(number int32) AccountMakerOption { return func(am *AccountMaker) { am.Number = number } } // AccountWithBalance sets the balance for the generated test account. func AccountWithBalance(balance amount.Amount) AccountMakerOption { return func(am *AccountMaker) { am.Balance = balance } } // GenerateTestAccount generates an account for testing purposes. func (ts *TestSuite) GenerateTestAccount(opts ...AccountMakerOption) (*account.Account, crypto.Address) { amk := ts.NewAccountMaker() for _, opt := range opts { opt(amk) } acc := account.NewAccount(amk.Number) acc.AddToBalance(amk.Balance) return acc, amk.Address } type ValidatorMaker struct { Number int32 Stake amount.Amount PublicKey *bls.PublicKey } type ValidatorMakerOption func(*ValidatorMaker) // NewValidatorMaker creates a new instance of ValidatorMaker with random values. func (ts *TestSuite) NewValidatorMaker() *ValidatorMaker { return &ValidatorMaker{ Number: ts.RandInt32(testsuite.WithMax(int32(100000))), Stake: ts.RandAmountRange(100e9, 1000e9), PublicKey: ts.RandValKey().PublicKey(), } } // ValidatorWithNumber sets the validator number for the generated test validator. func ValidatorWithNumber(number int32) ValidatorMakerOption { return func(vm *ValidatorMaker) { vm.Number = number } } // ValidatorWithStake sets the stake for the generated test account. func ValidatorWithStake(stake amount.Amount) ValidatorMakerOption { return func(vm *ValidatorMaker) { vm.Stake = stake } } // ValidatorWithPublicKey sets the public Key for the generated test account. func ValidatorWithPublicKey(publicKey *bls.PublicKey) ValidatorMakerOption { return func(vm *ValidatorMaker) { vm.PublicKey = publicKey } } // GenerateTestValidator generates a validator for testing purposes. func (ts *TestSuite) GenerateTestValidator(opts ...ValidatorMakerOption) *validator.Validator { vmk := ts.NewValidatorMaker() for _, opt := range opts { opt(vmk) } val := validator.NewValidator(vmk.PublicKey, vmk.Number) val.AddToStake(vmk.Stake) return val } type BlockMaker struct { Version protocol.Version Txs block.Txs Proposer crypto.Address Time time.Time StateHash hash.Hash PrevHash hash.Hash Seed sortition.VerifiableSeed PrevCert *certificate.Certificate } type BlockMakerOption func(*BlockMaker) // NewBlockMaker creates a new BlockMaker instance. func (ts *TestSuite) NewBlockMaker() *BlockMaker { txs := block.NewTxs() tx0 := ts.GenerateTestSubsidyTx() tx1 := ts.GenerateTestTransferTx() tx2 := ts.GenerateTestSortitionTx() tx3 := ts.GenerateTestBondTx() tx4 := ts.GenerateTestUnbondTx() tx5 := ts.GenerateTestWithdrawTx() txs.Append(tx0) txs.Append(tx1) txs.Append(tx2) txs.Append(tx3) txs.Append(tx4) txs.Append(tx5) return &BlockMaker{ Version: protocol.ProtocolVersion2, Txs: txs, Proposer: ts.RandValAddress(), Time: time.Now(), PrevHash: ts.RandHash(), Seed: ts.RandSeed(), PrevCert: nil, } } // BlockWithVersion sets version to the block. func BlockWithVersion(ver protocol.Version) BlockMakerOption { return func(bm *BlockMaker) { bm.Version = ver } } // BlockWithProposer sets proposer address to the block. func BlockWithProposer(addr crypto.Address) BlockMakerOption { return func(bm *BlockMaker) { bm.Proposer = addr } } // BlockWithTime sets block creation time to the block. func BlockWithTime(t time.Time) BlockMakerOption { return func(bm *BlockMaker) { bm.Time = t } } // BlockWithStateHash sets state hash to the block. func BlockWithStateHash(h hash.Hash) BlockMakerOption { return func(bm *BlockMaker) { bm.StateHash = h } } // BlockWithPrevHash sets previous block hash to the block. func BlockWithPrevHash(h hash.Hash) BlockMakerOption { return func(bm *BlockMaker) { bm.PrevHash = h } } // BlockWithSeed sets verifiable seed to the block. func BlockWithSeed(seed sortition.VerifiableSeed) BlockMakerOption { return func(bm *BlockMaker) { bm.Seed = seed } } // BlockWithPrevCert sets previous block certificate to the block. func BlockWithPrevCert(cert *certificate.Certificate) BlockMakerOption { return func(bm *BlockMaker) { bm.PrevCert = cert } } // BlockWithTransactions adds transactions to the block. func BlockWithTransactions(txs block.Txs) BlockMakerOption { return func(bm *BlockMaker) { bm.Txs = txs } } // GenerateTestBlock generates a block for testing purposes with optional configuration. func (ts *TestSuite) GenerateTestBlock(height types.Height, opts ...BlockMakerOption) ( *block.Block, *certificate.Certificate, ) { bmk := ts.NewBlockMaker() bmk.PrevCert = ts.GenerateTestCertificate(height - 1) if height == 1 { bmk.PrevCert = nil bmk.PrevHash = hash.UndefHash } for _, opt := range opts { opt(bmk) } header := block.NewHeader(bmk.Version, bmk.Time, bmk.PrevHash, bmk.PrevHash, bmk.Seed, bmk.Proposer) blk := block.NewBlock(header, bmk.PrevCert, bmk.Txs) blockCert := ts.GenerateTestCertificate(height) return blk, blockCert } // GenerateTestCertificate generates a block certificate for testing purposes. func (ts *TestSuite) GenerateTestCertificate(height types.Height) *certificate.Certificate { sig := ts.RandBLSSignature() cert := certificate.NewCertificate(height, ts.RandRound()) committers := ts.RandSlice(4) absentees := []int32{committers[3]} cert.SetSignature(committers, absentees, sig) return cert } type ProposalMaker struct { ProposerKey *bls.ValidatorKey } // NewProposalMaker creates a new NewProposalMaker instance. func (ts *TestSuite) NewProposalMaker() *ProposalMaker { return &ProposalMaker{ ProposerKey: ts.RandValKey(), } } // ProposalWithKey sets the private key of the proposer. func ProposalWithKey(key *bls.ValidatorKey) func(*ProposalMaker) { return func(pm *ProposalMaker) { pm.ProposerKey = key } } // GenerateTestProposal generates a proposal for testing purposes. func (ts *TestSuite) GenerateTestProposal(height types.Height, round types.Round, opts ...func(*ProposalMaker), ) *proposal.Proposal { pmk := ts.NewProposalMaker() for _, opt := range opts { opt(pmk) } blk, _ := ts.GenerateTestBlock(height, BlockWithProposer(pmk.ProposerKey.Address())) prop := proposal.NewProposal(height, round, blk) ts.HelperSignProposal(pmk.ProposerKey, prop) return prop } type TransactionMaker struct { LockTime types.Height Amount amount.Amount Fee amount.Amount Signer crypto.PrivateKey ValPubKey *bls.PublicKey Recipients []payload.BatchRecipient Receiver crypto.Address } type TransactionMakerOption func(*TransactionMaker) func (tm *TransactionMaker) SignerAccountAddress() crypto.Address { blsPub, ok := tm.Signer.PublicKey().(*bls.PublicKey) if ok { return blsPub.AccountAddress() } ed25519Pub := tm.Signer.PublicKey().(*ed25519.PublicKey) return ed25519Pub.AccountAddress() } func (tm *TransactionMaker) SignerValidatorAddress() crypto.Address { blsPub := tm.Signer.PublicKey().(*bls.PublicKey) return blsPub.ValidatorAddress() } // NewTransactionMaker creates a new TransactionMaker instance. func (ts *TestSuite) NewTransactionMaker() *TransactionMaker { numOfRecipients := ts.RandInt(testsuite.WithMax(6)) + 2 recipients := make([]payload.BatchRecipient, numOfRecipients) for i := 0; i < numOfRecipients; i++ { recipients[i] = payload.BatchRecipient{ To: ts.RandAccAddress(), Amount: ts.RandAmount(10e9), } } _, signer := ts.RandBLSKeyPair() return &TransactionMaker{ LockTime: ts.RandHeight(), Amount: ts.RandAmount(), Fee: ts.RandFee(), Signer: signer, ValPubKey: nil, Recipients: recipients, Receiver: ts.RandAccAddress(), } } // TransactionWithLockTime sets lock-time to the transaction. func TransactionWithLockTime(lockTime types.Height) TransactionMakerOption { return func(tm *TransactionMaker) { tm.LockTime = lockTime } } // TransactionWithAmount sets amount to the transaction. func TransactionWithAmount(amt amount.Amount) TransactionMakerOption { return func(tm *TransactionMaker) { tm.Amount = amt } } // TransactionWithFee sets fee to the transaction. func TransactionWithFee(fee amount.Amount) TransactionMakerOption { return func(tm *TransactionMaker) { tm.Fee = fee } } // TransactionWithSigner sets the BLS signer to sign the test transaction. func TransactionWithSigner(signer crypto.PrivateKey) TransactionMakerOption { return func(tm *TransactionMaker) { tm.Signer = signer } } // TransactionWithValidatorPublicKey sets the Validator's public key for the Bond transaction. func TransactionWithValidatorPublicKey(pubKey *bls.PublicKey) TransactionMakerOption { return func(tm *TransactionMaker) { tm.ValPubKey = pubKey } } // TransactionWithRecipients sets the recipients for the Bath Transfer transaction. func TransactionWithRecipients(recipients []payload.BatchRecipient) TransactionMakerOption { return func(tm *TransactionMaker) { tm.Recipients = recipients } } // TransactionWithReceiver sets the receiver for the Transfer transaction. func TransactionWithReceiver(receiver crypto.Address) TransactionMakerOption { return func(tm *TransactionMaker) { tm.Receiver = receiver } } // GenerateTestTransferTx generates a transfer transaction for testing purposes. func (ts *TestSuite) GenerateTestTransferTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } sender := tmk.SignerAccountAddress() trx := tx.NewTransferTx(tmk.LockTime, sender, tmk.Receiver, tmk.Amount, tmk.Fee) ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestBatchTransferTx generate a batch transfer transaction for test. func (ts *TestSuite) GenerateTestBatchTransferTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } numOfRecip := ts.RandInt(testsuite.WithMax(6)) + 2 recipients := make([]payload.BatchRecipient, numOfRecip) for i := 0; i < numOfRecip; i++ { recipients[i] = payload.BatchRecipient{ To: ts.RandAccAddress(), Amount: ts.RandAmount(10e9), } } trx := tx.NewBatchTransferTx(tmk.LockTime, tmk.SignerAccountAddress(), tmk.Recipients, tmk.Fee) ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestSubsidyTx creates a subsidy transaction for testing. func (ts *TestSuite) GenerateTestSubsidyTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } if tmk.LockTime == 0 { tmk.LockTime = ts.RandHeight() } return tx.NewSubsidyTx(tmk.LockTime, tmk.Recipients) } // GenerateTestBondTx generates a bond transaction for testing purposes. func (ts *TestSuite) GenerateTestBondTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } sender := tmk.SignerAccountAddress() receiver := ts.RandValAddress() if tmk.ValPubKey != nil { receiver = tmk.ValPubKey.ValidatorAddress() } trx := tx.NewBondTx(tmk.LockTime, sender, receiver, tmk.ValPubKey, tmk.Amount, tmk.Fee) ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestSortitionTx generates a sortition transaction for testing purposes. func (ts *TestSuite) GenerateTestSortitionTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } proof := ts.RandProof() sender := tmk.SignerValidatorAddress() trx := tx.NewSortitionTx(tmk.LockTime, sender, proof) ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestUnbondTx generates an unbond transaction for testing purposes. func (ts *TestSuite) GenerateTestUnbondTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } sender := tmk.SignerValidatorAddress() trx := tx.NewUnbondTx(tmk.LockTime, sender) ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestWithdrawTx generates a withdraw transaction for testing purposes. func (ts *TestSuite) GenerateTestWithdrawTx(opts ...TransactionMakerOption) *tx.Tx { tmk := ts.NewTransactionMaker() for _, opt := range opts { opt(tmk) } sender := tmk.SignerValidatorAddress() trx := tx.NewWithdrawTx(tmk.LockTime, sender, tmk.Receiver, tmk.Amount, tmk.Fee) ts.HelperSignTransaction(tmk.Signer, trx) return trx } // GenerateTestPrecommitVote generates a precommit vote for testing purposes. func (ts *TestSuite) GenerateTestPrecommitVote(height types.Height, round types.Round) (*vote.Vote, *bls.ValidatorKey) { valKey := ts.RandValKey() vote := vote.NewPrecommitVote( ts.RandHash(), height, round, valKey.Address()) ts.HelperSignVote(valKey, vote) return vote, valKey } // GenerateTestPrepareVote generates a prepare vote for testing purposes. func (ts *TestSuite) GenerateTestPrepareVote(height types.Height, round types.Round) (*vote.Vote, *bls.ValidatorKey) { valKey := ts.RandValKey() vote := vote.NewPrepareVote( ts.RandHash(), height, round, valKey.Address()) ts.HelperSignVote(valKey, vote) return vote, valKey } // GenerateTestCommittee generates a committee for testing purposes. // All committee members have the same power. func (ts *TestSuite) GenerateTestCommittee(num int) (committee.Committee, []*bls.ValidatorKey) { valKeys := make([]*bls.ValidatorKey, num) vals := make([]*validator.Validator, num) for index := int32(0); index < int32(num); index++ { valKey := ts.RandValKey() val := ts.GenerateTestValidator( ValidatorWithNumber(index), ValidatorWithPublicKey(valKey.PublicKey())) valKeys[index] = valKey vals[index] = val val.UpdateLastBondingHeight(types.Height(1 + index)) val.UpdateLastSortitionHeight(types.Height(1 + index)) val.SubtractFromStake(val.Stake()) val.AddToStake(10e9) } cmt, _ := committee.NewCommittee(vals, num, vals[0].Address()) return cmt, valKeys } func (*TestSuite) HelperSignVote(valKey *bls.ValidatorKey, v *vote.Vote) { sig := valKey.Sign(v.SignBytes()) v.SetSignature(sig) } func (*TestSuite) HelperSignProposal(valKey *bls.ValidatorKey, p *proposal.Proposal) { sig := valKey.Sign(p.SignBytes()) p.SetSignature(sig) } func (*TestSuite) HelperSignTransaction(prv crypto.PrivateKey, trx *tx.Tx) { if prv != nil { sig := prv.Sign(trx.SignBytes()) trx.SetSignature(sig) trx.SetPublicKey(prv.PublicKey()) } } func FindFreePort() int { var freePort int for { // Find a free TCP port listenerTCP, err := util.NetworkListen(context.Background(), "tcp", "127.0.0.1:0") if err != nil { continue } freePort = listenerTCP.Addr().(*net.TCPAddr).Port _ = listenerTCP.Close() udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", freePort)) if err != nil { continue } udpConn, err := net.ListenUDP("udp", udpAddr) if err != nil { continue } _ = udpConn.Close() break } return freePort } ================================================ FILE: util/time.go ================================================ package util import ( "time" ) // RoundNow returns the result of rounding sec to the current time in UTC. // The rounding behavior is rounding down. func RoundNow(sec int) time.Time { return roundDownTime(time.Now(), sec) } func roundDownTime(t time.Time, sec int) time.Time { t = t.Truncate(time.Duration(sec) * time.Second) t = t.UTC() return t } ================================================ FILE: util/time_test.go ================================================ package util import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRoundNow(t *testing.T) { time1 := time.Now() time2 := RoundNow(1) time3 := RoundNow(5) assert.NotEqual(t, time1, time2) assert.Equal(t, time1.Second(), time2.Second()) assert.Equal(t, int64(0), time2.UnixMicro()%1000000) assert.Equal(t, int64(0), time2.UnixMilli()%1000) assert.Equal(t, 0, time3.Nanosecond()) assert.Equal(t, 0, time3.Second()%5) } func TestRoundingTime(t *testing.T) { tests := []struct { input string expected int }{ {"2006-01-02T15:04:11.111111111Z", 10}, {"2006-01-02T15:04:24.333333333Z", 20}, {"2006-01-02T15:04:35.555555555Z", 30}, {"2006-01-02T15:04:48.777777777Z", 40}, {"2006-01-02T15:04:59.999999999Z", 50}, } for _, tt := range tests { parsedTime, err := time.Parse(time.RFC3339Nano, tt.input) require.NoError(t, err, "Failed to parse time") roundedTime := roundDownTime(parsedTime, 10) assert.Equal(t, 0, roundedTime.Nanosecond(), "Nanoseconds should be rounded to 0") assert.Equal(t, tt.expected, roundedTime.Second(), "Seconds should match the expected rounded value") } } ================================================ FILE: util/utils.go ================================================ package util import ( crand "crypto/rand" "errors" "fmt" "math/big" "math/bits" "net/url" "strings" "golang.org/x/exp/constraints" ) const ( MaxUint16 = ^uint16(0) MinUint16 = 0 MaxInt16 = int16(MaxUint16 >> 1) MinInt16 = -MaxInt16 - 1 ) const ( MaxUint32 = ^uint32(0) MinUint32 = 0 MaxInt32 = int32(MaxUint32 >> 1) MinInt32 = -MaxInt32 - 1 ) const ( MaxUint64 = ^uint64(0) MinUint64 = 0 MaxInt64 = int64(MaxUint64 >> 1) MinInt64 = -MaxInt64 - 1 ) // Max returns the biggest of two integer numbers. func Max[T constraints.Integer](a, b T) T { if a > b { return a } return b } // Min returns the smallest of two integer numbers. func Min[T constraints.Integer](a, b T) T { if a < b { return a } return b } // RandInt16 returns a random int16 in between 0 and max. // If max set to zero or negative, the max will set to MaxInt16. func RandInt16(max int16) int16 { return int16(RandUint64(uint64(max))) } // RandUint16 returns a random uint16 in between 0 and max. // If max set to zero or negative, the max will set to MaxUint16. func RandUint16(max uint32) uint16 { return uint16(RandUint64(uint64(max))) } // RandInt32 returns a random int32 in between 0 and max. // If max set to zero or negative, the max will set to MaxInt32. func RandInt32(max int32) int32 { return int32(RandUint64(uint64(max))) } // RandUint32 returns a random uint32 in between 0 and max. // If max set to zero or negative, the max will set to MaxUint32. func RandUint32(max uint32) uint32 { return uint32(RandUint64(uint64(max))) } // RandInt64 returns a random int64 in between 0 and max. // If max set to zero or negative, the max will set to MaxInt64. func RandInt64(max int64) int64 { return int64(RandUint64(uint64(max))) } // RandUint64 returns a random uint64 in between 0 and max. // If max set to zero or negative, the max will set to MaxUint64. func RandUint64(max uint64) uint64 { if max <= 0 { max = MaxUint64 } bigMax := &big.Int{} bigMax.SetUint64(max) bigRnd, _ := crand.Int(crand.Reader, bigMax) return bigRnd.Uint64() } // SetFlag applies mask to the flags. func SetFlag[T constraints.Integer](flags, mask T) T { return flags | mask } // UnsetFlag removes mask from the flags. func UnsetFlag[T constraints.Integer](flags, mask T) T { return flags & ^mask } // IsFlagSet checks if the mask is set for the given flags. func IsFlagSet[T constraints.Integer](flags, mask T) bool { return flags&mask == mask } // OS2IP converts an octet string to a nonnegative integer. // OS2IP: https://datatracker.ietf.org/doc/html/rfc8017#section-4.2 func OS2IP(x []byte) *big.Int { return new(big.Int).SetBytes(x) } // I2OSP converts a nonnegative integer to an octet string of a specified length. // https://datatracker.ietf.org/doc/html/rfc8017#section-4.1 func I2OSP(num *big.Int, len int) []byte { if num.Sign() == -1 { return nil } buf := make([]byte, len) return num.FillBytes(buf) } // LogScale computes 2^⌈log₂(val)⌉, where ⌈x⌉ represents the ceiling of x. // For more information, refer to: https://en.wikipedia.org/wiki/Logarithmic_scale func LogScale(val int) int { bitlen := bits.Len(uint(val - 1)) return 1 << bitlen } func FormatBytesToHumanReadable(bytes uint64) string { const ( _ = iota KiloBYte = 1 << (10 * iota) MegaBYte GigaByte TeraByte ) unit := "Bytes" value := float64(bytes) switch { case bytes >= TeraByte: unit = "TB" value /= TeraByte case bytes >= GigaByte: unit = "GB" value /= GigaByte case bytes >= MegaBYte: unit = "MB" value /= MegaBYte case bytes >= KiloBYte: unit = "KB" value /= KiloBYte } return fmt.Sprintf("%.2f %s", value, unit) } func ParseGRPCAddr(addr string, insecureCredentials bool) (target, prefix string, err error) { if insecureCredentials { if strings.HasPrefix(addr, "https://") { return "", "", errors.New("insecure credentials are not supported for HTTPS addresses") } addr = strings.TrimPrefix(addr, "http://") return addr, "", nil } if strings.HasPrefix(addr, "http://") { return "", "", errors.New("insecure credentials are not supported for HTTP addresses") } if !strings.HasPrefix(addr, "https://") { addr = "https://" + addr } parsed, err := url.Parse(addr) if err != nil { return "", "", err } target = parsed.Host prefix = parsed.Path if parsed.Port() == "" { if parsed.Scheme == "https" { target = parsed.Host + ":443" } } return target, prefix, nil } ================================================ FILE: util/utils_test.go ================================================ package util import ( "math/big" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUtils(t *testing.T) { assert.Equal(t, int32(1), Min(int32(1), 1)) assert.Equal(t, int32(1), Min(int32(1), 2)) assert.Equal(t, int32(1), Min(2, int32(1))) assert.Equal(t, int32(2), Max(int32(2), 2)) assert.Equal(t, int32(2), Max(1, int32(2))) assert.Equal(t, int32(2), Max(int32(2), 1)) assert.Equal(t, uint32(1), Min(uint32(1), 1)) assert.Equal(t, uint32(1), Min(uint32(1), 2)) assert.Equal(t, uint32(1), Min(2, uint32(1))) assert.Equal(t, uint32(2), Max(uint32(2), 2)) assert.Equal(t, uint32(2), Max(1, uint32(2))) assert.Equal(t, uint32(2), Max(uint32(2), 1)) assert.Equal(t, MaxUint32, uint32(0xffffffff)) assert.Equal(t, MaxUint64, uint64(0xffffffffffffffff)) assert.Equal(t, MaxInt32, int32(0x7fffffff)) assert.Equal(t, MaxInt64, int64(0x7fffffffffffffff)) assert.Equal(t, MaxInt64, Max(MaxInt64, 1)) assert.Equal(t, MaxInt64, Max(MinInt64, MaxInt64)) assert.Equal(t, int64(1), Min(MaxInt64, 1)) assert.Equal(t, MinInt64, Min(MinInt64, MaxInt64)) } func TestSetFlags(t *testing.T) { flags := 0 flags = SetFlag(flags, 0x2) flags = SetFlag(flags, 0x8) assert.Equal(t, 0xa, flags) assert.True(t, IsFlagSet(flags, 0x2)) assert.False(t, IsFlagSet(flags, 0x4)) flags = UnsetFlag(flags, 0x2) assert.False(t, IsFlagSet(flags, 0x2)) assert.Equal(t, 0x8, flags) } func TestRandUint16(t *testing.T) { rnd := RandUint16(4) assert.LessOrEqual(t, rnd, uint16(4)) } func TestRandInt16(t *testing.T) { rnd := RandInt16(4) assert.GreaterOrEqual(t, rnd, int16(0)) assert.LessOrEqual(t, rnd, int16(4)) } func TestRandUint32(t *testing.T) { rnd := RandUint32(4) assert.LessOrEqual(t, rnd, uint32(4)) } func TestRandInt32(t *testing.T) { rnd := RandInt32(4) assert.GreaterOrEqual(t, rnd, int32(0)) assert.LessOrEqual(t, rnd, int32(4)) } func TestRandInt64(t *testing.T) { rnd := RandInt64(4) assert.GreaterOrEqual(t, rnd, int64(0)) assert.LessOrEqual(t, rnd, int64(4)) } func TestRandUint64(t *testing.T) { rnd1 := RandUint64(4) assert.LessOrEqual(t, rnd1, uint64(4)) rnd2 := RandUint64(0) assert.NotZero(t, rnd2) } func TestI2OSP(t *testing.T) { assert.Nil(t, I2OSP(big.NewInt(int64(-1)), 2)) assert.Equal(t, []byte{0, 0}, I2OSP(big.NewInt(int64(0)), 2)) assert.Equal(t, []byte{0, 1}, I2OSP(big.NewInt(int64(1)), 2)) assert.Equal(t, []byte{0, 255}, I2OSP(big.NewInt(int64(255)), 2)) assert.Equal(t, []byte{1, 0}, I2OSP(big.NewInt(int64(256)), 2)) assert.Equal(t, []byte{255, 255}, I2OSP(big.NewInt(int64(65535)), 2)) } func TestIS2OP(t *testing.T) { assert.Equal(t, int64(0), OS2IP([]byte{0, 0}).Int64()) assert.Equal(t, int64(1), OS2IP([]byte{0, 1}).Int64()) assert.Equal(t, int64(255), OS2IP([]byte{0, 255}).Int64()) assert.Equal(t, int64(256), OS2IP([]byte{1, 0}).Int64()) assert.Equal(t, int64(65535), OS2IP([]byte{255, 255}).Int64()) } func TestLogScale(t *testing.T) { tests := []struct { input int expected int }{ {1, 1}, {2, 2}, {3, 4}, {7, 8}, {8, 8}, } for _, tt := range tests { result := LogScale(tt.input) assert.Equal(t, tt.expected, result, "LogScale(%d) failed", tt.input) } } func TestFormatBytesToHumanReadable(t *testing.T) { tests := []struct { bytes uint64 expected string }{ {1048576, "1.00 MB"}, {3145728, "3.00 MB"}, {1024, "1.00 KB"}, {512, "512.00 Bytes"}, {1_073_741_824, "1.00 GB"}, {1_099_511_627_776, "1.00 TB"}, } for _, tt := range tests { result := FormatBytesToHumanReadable(tt.bytes) if result != tt.expected { t.Errorf("FormatBytesToHumanReadable(%d) returned %s, expected %s", tt.bytes, result, tt.expected) } } } func TestParseGRPCAddr(t *testing.T) { tests := []struct { addr string insecure bool wantTarget string wantPrefix string wantError bool }{ { addr: "localhost:50051", insecure: true, wantTarget: "localhost:50051", wantPrefix: "", wantError: false, }, { addr: "example.com:50051", insecure: true, wantTarget: "example.com:50051", wantPrefix: "", wantError: false, }, { addr: "http://example.com:50051", insecure: true, wantTarget: "example.com:50051", wantPrefix: "", wantError: false, }, { addr: "https://example.com:50051", insecure: false, wantTarget: "example.com:50051", wantPrefix: "", wantError: false, }, { addr: "https://example.com:50051/path", insecure: false, wantTarget: "example.com:50051", wantPrefix: "/path", wantError: false, }, { addr: "https://example.com/path", insecure: false, wantTarget: "example.com:443", wantPrefix: "/path", wantError: false, }, { addr: "https://example.com/path1/path2", insecure: false, wantTarget: "example.com:443", wantPrefix: "/path1/path2", wantError: false, }, { addr: "example.com/path", insecure: false, wantTarget: "example.com:443", wantPrefix: "/path", wantError: false, }, { addr: "https://example.com:50051", insecure: true, wantTarget: "", wantPrefix: "", wantError: true, }, { addr: "http://example.com:50051", insecure: false, wantTarget: "", wantPrefix: "", wantError: true, }, { addr: "\x00", insecure: false, wantTarget: "", wantPrefix: "", wantError: true, }, } for _, tt := range tests { t.Run(tt.addr, func(t *testing.T) { if tt.wantError { _, _, err := ParseGRPCAddr(tt.addr, tt.insecure) require.Error(t, err) } else { target, prefix, err := ParseGRPCAddr(tt.addr, tt.insecure) require.NoError(t, err) assert.Equal(t, tt.wantTarget, target) assert.Equal(t, tt.wantPrefix, prefix) } }) } } ================================================ FILE: version/agent.go ================================================ package version import ( "errors" "fmt" "runtime" "strings" "github.com/pactus-project/pactus/types/protocol" ) var NodeAgent = Agent{ Version: NodeVersion(), ProtocolVersion: protocol.ProtocolVersionLatest, OS: runtime.GOOS, Arch: runtime.GOARCH, } type Agent struct { AppType string Version Version ProtocolVersion protocol.Version OS string Arch string } // ParseAgent parses a string into an Agent struct. func ParseAgent(agentStr string) (Agent, error) { var agent Agent parts := strings.SplitSeq(agentStr, "/") for part := range parts { fields := strings.Split(part, "=") if len(fields) != 2 { return agent, errors.New("invalid field format in agent string") } key := fields[0] value := fields[1] switch key { case "node": agent.AppType = value case "node-version": v, err := ParseVersion(value) if err != nil { return agent, fmt.Errorf("failed to parse version: %w", err) } agent.Version = v case "protocol-version": protocolVersion, err := protocol.ParseVersion(value) if err != nil { return agent, fmt.Errorf("failed to parse protocol version: %w", err) } agent.ProtocolVersion = protocolVersion case "os": agent.OS = value case "arch": agent.Arch = value default: return agent, fmt.Errorf("unknown key in agent string: %s", key) } } return agent, nil } func (a *Agent) String() string { return fmt.Sprintf("node=%s/node-version=%s/protocol-version=%d/os=%s/arch=%s", a.AppType, a.Version.String(), a.ProtocolVersion, a.OS, a.Arch) } ================================================ FILE: version/agent_test.go ================================================ package version_test import ( "testing" "github.com/pactus-project/pactus/version" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAgentString(t *testing.T) { agent := version.Agent{ AppType: "gui", Version: version.Version{Major: 1, Minor: 2, Patch: 3, Meta: "beta"}, ProtocolVersion: 2, OS: "linux", Arch: "amd64", } expected := "node=gui/node-version=1.2.3-beta/protocol-version=2/os=linux/arch=amd64" result := agent.String() assert.Equal(t, expected, result) } func TestParseAgent(t *testing.T) { tests := []struct { name string agentStr string expected version.Agent expectedErr bool }{ { name: "Valid Agent String", agentStr: "node=gui/node-version=1.2.3-beta/protocol-version=2/os=linux/arch=amd64", expected: version.Agent{ AppType: "gui", Version: version.Version{ Major: 1, Minor: 2, Patch: 3, Meta: "beta", }, ProtocolVersion: 2, OS: "linux", Arch: "amd64", }, expectedErr: false, }, { name: "Invalid Agent String (Invalid Protocol Version)", agentStr: "node=gui/node-version=1.2.3-beta/protocol-version=abc/os=linux/arch=amd64", expected: version.Agent{}, expectedErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { agent, err := version.ParseAgent(tt.agentStr) if tt.expectedErr { require.Error(t, err) } else { require.NoError(t, err) assert.Equal(t, tt.expected, agent) } }) } } ================================================ FILE: version/version.go ================================================ package version import ( _ "embed" "encoding/json" "errors" "fmt" "strconv" "strings" ) //go:embed version.json var versionData []byte // Version defines the version of the Pactus software. // It follows the Semantic Versioning 2.0.0 spec: http://semver.org/. // // Update this struct with each new release by adjusting the Major, Minor, or Patch numbers. // For major releases, clear the Meta field (set to an empty string). // Use the Meta field to indicate pre-release stages, such as "rc1", "rc2", or "beta" during development. type Version struct { Major uint `json:"major"` // Major version number Minor uint `json:"minor"` // Minor version number Patch uint `json:"patch"` // Patch version number Meta string `json:"meta"` // Metadata for version (e.g., "beta", "rc1") Alias string `json:"alias"` // Alias for version (e.g., "London") } var nodeVersion *Version // NodeVersion represents the current version of the node software. func NodeVersion() Version { if nodeVersion == nil { // Initialize the version from the embedded version.json. nodeVersion = new(Version) if err := json.Unmarshal(versionData, nodeVersion); err != nil { panic(err) } } return *nodeVersion } // ParseVersion parses a version string into a Version struct. // The format should be "Major.Minor.Patch-Meta", where Meta is optional. // Returns the parsed Version struct and an error if parsing fails. func ParseVersion(versionStr string) (Version, error) { var ver Version if versionStr[0] == 'v' { versionStr = versionStr[1:] } // Split the version string into parts parts := strings.Split(versionStr, ".") if len(parts) != 3 { return ver, errors.New("invalid version format") } // Parse Major version major, err := strconv.ParseUint(parts[0], 10, 64) if err != nil { return ver, fmt.Errorf("failed to parse Major version: %w", err) } ver.Major = uint(major) // Parse Minor version minor, err := strconv.ParseUint(parts[1], 10, 64) if err != nil { return ver, fmt.Errorf("failed to parse Minor version: %w", err) } ver.Minor = uint(minor) // Parse Patch version and Meta (if present) patchMeta := strings.Split(parts[2], "-") if len(patchMeta) > 2 { return ver, errors.New("invalid Patch and Meta format") } patch, err := strconv.ParseUint(patchMeta[0], 10, 64) if err != nil { return ver, fmt.Errorf("failed to parse Patch version: %w", err) } ver.Patch = uint(patch) if len(patchMeta) == 2 { ver.Meta = patchMeta[1] } return ver, nil } // StringWithAlias returns a string representation of the Version object with the alias. func (v Version) StringWithAlias() string { if v.Alias == "" { return v.String() } return fmt.Sprintf("%s (%s)", v.String(), v.Alias) } // String returns a string representation of the Version object. func (v Version) String() string { ver := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch) if v.Meta != "" { ver = fmt.Sprintf("%s-%s", ver, v.Meta) } return ver } // Compare compares the current version (v) with another version (other) // and returns: // // -1 if v < other // 0 if v == other // 1 if v > other func (v Version) Compare(other Version) int { if v.Major != other.Major { return compareInt(v.Major, other.Major) } if v.Minor != other.Minor { return compareInt(v.Minor, other.Minor) } return compareInt(v.Patch, other.Patch) } func compareInt(a, b uint) int { if a < b { return -1 } else if a > b { return 1 } return 0 } var _ = NodeVersion() ================================================ FILE: version/version.json ================================================ { "major": 1, "minor": 14, "patch": 0, "meta": "beta", "alias": "" } ================================================ FILE: version/version_test.go ================================================ package version_test import ( "testing" "github.com/pactus-project/pactus/version" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestVersionString(t *testing.T) { tests := []struct { name string version version.Version expected string }{ { name: "Version with Meta", version: version.Version{Major: 1, Minor: 2, Patch: 3, Meta: "beta"}, expected: "1.2.3-beta", }, { name: "Version without Meta", version: version.Version{Major: 2, Minor: 0, Patch: 0, Meta: ""}, expected: "2.0.0", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.version.String() assert.Equal(t, tt.expected, result) }) } } func TestParseVersion(t *testing.T) { tests := []struct { name string input string expected version.Version expectedErr bool }{ { name: "Valid Version String starts with 'v'", input: "v1.2.3", expected: version.Version{Major: 1, Minor: 2, Patch: 3, Meta: ""}, expectedErr: false, }, { name: "Valid Version String with Meta", input: "1.2.3-beta", expected: version.Version{Major: 1, Minor: 2, Patch: 3, Meta: "beta"}, expectedErr: false, }, { name: "Valid Version String without Meta", input: "2.0.0", expected: version.Version{Major: 2, Minor: 0, Patch: 0, Meta: ""}, expectedErr: false, }, { name: "Invalid Version String", input: "1.2", expected: version.Version{}, expectedErr: true, }, { name: "Invalid Major number", input: "one.2.3", expected: version.Version{}, expectedErr: true, }, { name: "Invalid Minor number", input: "1.two.3", expected: version.Version{}, expectedErr: true, }, { name: "Invalid Patch number", input: "1.2.three", expected: version.Version{}, expectedErr: true, }, { name: "Invalid Patch-Meta Format", input: "1.2.3-rc1-dev", expected: version.Version{}, expectedErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ver, err := version.ParseVersion(tt.input) if tt.expectedErr { require.Error(t, err) } else { require.NoError(t, err) assert.Equal(t, tt.expected, ver) } }) } } func TestVersionComparison(t *testing.T) { tests := []struct { name string v1Input string v2Input string expectedSign int }{ { name: "Equal Versions", v1Input: "1.2.3", v2Input: "1.2.3", expectedSign: 0, }, { name: "Equal Versions", v1Input: "1.2.3-beta", v2Input: "1.2.3", expectedSign: 0, }, { name: "Equal Versions", v1Input: "1.2.3-beta", v2Input: "1.2.3-rc1", expectedSign: 0, }, { name: "Lesser Patch Version", v1Input: "1.2.2", v2Input: "1.2.3", expectedSign: -1, }, { name: "Lesser Minor Version", v1Input: "2.1.0", v2Input: "2.2.0", expectedSign: -1, }, { name: "Greater Major Version", v1Input: "2.1.0", v2Input: "1.2.3", expectedSign: 1, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ver1, err := version.ParseVersion(tt.v1Input) require.NoError(t, err) ver2, err := version.ParseVersion(tt.v2Input) require.NoError(t, err) expectedSign := tt.expectedSign actualSign := ver1.Compare(ver2) assert.Equalf(t, expectedSign, actualSign, "Comparison result mismatch for %s vs %s", tt.v1Input, tt.v2Input) }) } } // TestCheckVersionString checks if the current version string is valid and parsable. func TestCheckVersionString(t *testing.T) { curVer := version.NodeVersion() parsedVer, err := version.ParseVersion(curVer.String()) require.NoError(t, err) assert.Equal(t, curVer.Major, parsedVer.Major) assert.Equal(t, curVer.Minor, parsedVer.Minor) assert.Equal(t, curVer.Patch, parsedVer.Patch) assert.Equal(t, curVer.Meta, parsedVer.Meta) } ================================================ FILE: wallet/addresses.go ================================================ package wallet import ( "cmp" "slices" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/storage" "github.com/pactus-project/pactus/wallet/types" ) type addresses struct { storage storage.IStorage } func newAddresses(storage storage.IStorage) addresses { return addresses{ storage: storage, } } func (a *addresses) AddressInfo(addr string) (*types.AddressInfo, error) { return a.storage.AddressInfo(addr) } // listAddressConfig contains options for filtering addresses. type listAddressConfig struct { addressTypes []crypto.AddressType } var defaultListAddressConfig = listAddressConfig{ addressTypes: []crypto.AddressType{}, } // ListAddressOption is a functional option for ListAddresses. type ListAddressOption func(*listAddressConfig) // WithAddressTypes filters addresses by the specified type. func WithAddressTypes(addressTypes []crypto.AddressType) ListAddressOption { return func(cfg *listAddressConfig) { cfg.addressTypes = addressTypes } } // WithAddressType filters addresses by the specified type. func WithAddressType(addressType crypto.AddressType) ListAddressOption { return func(cfg *listAddressConfig) { cfg.addressTypes = []crypto.AddressType{addressType} } } // OnlyValidatorAddresses filters to show only validator addresses. func OnlyValidatorAddresses() ListAddressOption { return func(cfg *listAddressConfig) { cfg.addressTypes = []crypto.AddressType{crypto.AddressTypeValidator} } } // OnlyAccountAddresses filters to show only account addresses (BLS and Ed25519). func OnlyAccountAddresses() ListAddressOption { return func(cfg *listAddressConfig) { cfg.addressTypes = []crypto.AddressType{ crypto.AddressTypeBLSAccount, crypto.AddressTypeEd25519Account, } } } func (a *addresses) ListAddresses(opts ...ListAddressOption) []types.AddressInfo { cfg := defaultListAddressConfig for _, opt := range opts { opt(&cfg) } infos := make([]types.AddressInfo, 0) for _, info := range a.storage.AllAddresses() { if len(cfg.addressTypes) == 0 { infos = append(infos, info) continue } addr, err := crypto.AddressFromString(info.Address) if err != nil { return nil } for _, addrType := range cfg.addressTypes { if addr.Type() == addrType { infos = append(infos, info) break } } } a.sortAddressesByAddressIndex(infos...) a.sortAddressesByAddressType(infos...) a.sortAddressesByPurpose(infos...) return infos } func (*addresses) sortAddressesByPurpose(addrs ...types.AddressInfo) { slices.SortStableFunc(addrs, func(a, b types.AddressInfo) int { pathA, _ := addresspath.FromString(a.Path) pathB, _ := addresspath.FromString(b.Path) return cmp.Compare(pathA.Purpose(), pathB.Purpose()) }) } func (*addresses) sortAddressesByAddressType(addrs ...types.AddressInfo) { slices.SortStableFunc(addrs, func(a, b types.AddressInfo) int { pathA, _ := addresspath.FromString(a.Path) pathB, _ := addresspath.FromString(b.Path) return cmp.Compare(pathA.AddressType(), pathB.AddressType()) }) } func (*addresses) sortAddressesByAddressIndex(addrs ...types.AddressInfo) { slices.SortStableFunc(addrs, func(a, b types.AddressInfo) int { pathA, _ := addresspath.FromString(a.Path) pathB, _ := addresspath.FromString(b.Path) return cmp.Compare(pathA.AddressIndex(), pathB.AddressIndex()) }) } // AddressCount returns the number of addresses inside the wallet. func (a *addresses) AddressCount() int { return a.storage.AddressCount() } func (a *addresses) ImportBLSPrivateKey(password string, prv *bls.PrivateKey) error { pub := prv.PublicKeyNative() accAddr := pub.AccountAddress() if a.HasAddress(accAddr.String()) { return ErrAddressExists } vault := a.storage.Vault() accInfo, valInfo, err := vault.ImportBLSPrivateKey(password, prv) if err != nil { return err } err = a.storage.InsertAddress(accInfo) if err != nil { return err } err = a.storage.InsertAddress(valInfo) if err != nil { return err } return a.storage.UpdateVault(vault) } func (a *addresses) ImportEd25519PrivateKey(password string, prv *ed25519.PrivateKey) error { pub := prv.PublicKeyNative() accAddr := pub.AccountAddress() if a.HasAddress(accAddr.String()) { return ErrAddressExists } vault := a.storage.Vault() accInfo, err := vault.ImportEd25519PrivateKey(password, prv) if err != nil { return err } err = a.storage.InsertAddress(accInfo) if err != nil { return err } return a.storage.UpdateVault(vault) } func (a *addresses) PrivateKey(password, addr string) (crypto.PrivateKey, error) { keys, err := a.PrivateKeys(password, []string{addr}) if err != nil { return nil, err } return keys[0], nil } func (a *addresses) PrivateKeys(password string, addrs []string) ([]crypto.PrivateKey, error) { paths := make([]addresspath.Path, len(addrs)) for i, addr := range addrs { info, err := a.AddressInfo(addr) if err != nil { return nil, err } hdPath, err := addresspath.FromString(info.Path) if err != nil { return nil, err } paths[i] = hdPath } return a.storage.Vault().PrivateKeys(password, paths) } // newAddressConfig contains options for creating new addresses. type newAddressConfig struct { password string } var defaultNewAddressConfig = newAddressConfig{ password: "", } // NewAddressOption is a functional option for NewAddresa. type NewAddressOption func(*newAddressConfig) // WithPassword sets the password for address creation required for Ed25519 accounta. func WithPassword(password string) NewAddressOption { return func(cfg *newAddressConfig) { cfg.password = password } } func (a *addresses) NewAddress(addressType crypto.AddressType, label string, opts ...NewAddressOption, ) (*types.AddressInfo, error) { cfg := defaultNewAddressConfig for _, opt := range opts { opt(&cfg) } vault := a.storage.Vault() var info *types.AddressInfo var err error switch addressType { case crypto.AddressTypeValidator: info, err = vault.NewValidatorAddress(label) case crypto.AddressTypeBLSAccount: info, err = vault.NewBLSAccountAddress(label) case crypto.AddressTypeEd25519Account: info, err = vault.NewEd25519AccountAddress(label, cfg.password) case crypto.AddressTypeTreasury: return nil, ErrInvalidAddressType default: return nil, ErrInvalidAddressType } if err != nil { return nil, err } err = a.storage.InsertAddress(info) if err != nil { return nil, err } err = a.storage.UpdateVault(vault) if err != nil { return nil, err } return info, nil } // NewBLSAccountAddress create a new BLS-based account address and // associates it with the given label. func (a *addresses) NewBLSAccountAddress(label string) (*types.AddressInfo, error) { return a.NewAddress(crypto.AddressTypeBLSAccount, label) } // NewEd25519AccountAddress create a new Ed25519-based account address and // associates it with the given label. // The password is required to access the master private key needed for address generation. func (a *addresses) NewEd25519AccountAddress(label, password string) (*types.AddressInfo, error) { return a.NewAddress(crypto.AddressTypeEd25519Account, label, WithPassword(password)) } // NewValidatorAddress creates a new BLS validator address and // associates it with the given label. func (a *addresses) NewValidatorAddress(label string) (*types.AddressInfo, error) { return a.NewAddress(crypto.AddressTypeValidator, label) } func (a *addresses) HasAddress(addr string) bool { return a.storage.HasAddress(addr) } // AddressLabel returns label of the given addresa. func (a *addresses) AddressLabel(addr string) string { info, err := a.AddressInfo(addr) if err != nil { return "" } return info.Label } // SetAddressLabel updates the label of the given addresa. func (a *addresses) SetAddressLabel(addr, label string) error { info, err := a.AddressInfo(addr) if err != nil { return err } info.Label = label return a.storage.UpdateAddress(info) } ================================================ FILE: wallet/addresses_test.go ================================================ package wallet import ( "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/wallet/encrypter" "github.com/pactus-project/pactus/wallet/storage" "github.com/pactus-project/pactus/wallet/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) func TestPrivateKey(t *testing.T) { td := setup(t) t.Run("Unknown address", func(t *testing.T) { addr := td.RandAccAddress().String() td.mockStorage.EXPECT().AddressInfo(addr).Return(nil, storage.ErrNotFound) _, err := td.wallet.PrivateKey(td.password, addr) require.ErrorIs(t, err, storage.ErrNotFound) }) } func TestAddressCount(t *testing.T) { td := setup(t) count := td.RandIntMax(100) td.mockStorage.EXPECT().AddressCount().Return(count) assert.Equal(t, count, td.wallet.AddressCount()) } func TestHasAddress(t *testing.T) { td := setup(t) knownAddr := td.RandAccAddress().String() td.mockStorage.EXPECT().HasAddress(knownAddr).Return(true) td.mockStorage.EXPECT().HasAddress(gomock.Any()).Return(false) t.Run("Known address", func(t *testing.T) { assert.True(t, td.wallet.HasAddress(knownAddr)) }) t.Run("Unknown address", func(t *testing.T) { unknownAddr := td.RandAccAddress().String() assert.False(t, td.wallet.HasAddress(unknownAddr)) }) } func TestListAddresses(t *testing.T) { td := setup(t) valInfo, _ := td.testVault.NewValidatorAddress("addr-1") accInfo, _ := td.testVault.NewBLSAccountAddress("addr-2") edInfo, _ := td.testVault.NewEd25519AccountAddress("addr-3", td.password) _, prv1 := td.RandBLSKeyPair() impAcc, impVal, _ := td.testVault.ImportBLSPrivateKey(td.password, prv1) _, prv2 := td.RandEd25519KeyPair() impEd, _ := td.testVault.ImportEd25519PrivateKey(td.password, prv2) existing := []types.AddressInfo{ *impAcc, *impVal, *impEd, *valInfo, *accInfo, *edInfo, } td.mockStorage.EXPECT().AllAddresses().Return(existing).AnyTimes() t.Run("List should be sorted", func(t *testing.T) { listed := td.wallet.ListAddresses() assert.Equal(t, "m/44'/21888'/3'/0'", listed[0].Path) assert.Equal(t, "m/12381'/21888'/1'/0", listed[1].Path) assert.Equal(t, "m/12381'/21888'/2'/0", listed[2].Path) assert.Equal(t, "m/65535'/21888'/1'/0'", listed[3].Path) assert.Equal(t, "m/65535'/21888'/2'/0'", listed[4].Path) assert.Equal(t, "m/65535'/21888'/3'/1'", listed[5].Path) }) t.Run("Only account addresses", func(t *testing.T) { infos := td.wallet.ListAddresses(OnlyAccountAddresses()) for _, i := range infos { addr, _ := crypto.AddressFromString(i.Address) assert.True(t, addr.IsAccountAddress()) } }) t.Run("Only validator addresses", func(t *testing.T) { infos := td.wallet.ListAddresses(OnlyValidatorAddresses()) for _, i := range infos { addr, _ := crypto.AddressFromString(i.Address) assert.True(t, addr.IsValidatorAddress()) } }) } func TestNewValidatorAddress(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) label := td.RandString(16) addressInfo, err := td.wallet.NewValidatorAddress(label) require.NoError(t, err) assert.NotEmpty(t, addressInfo.Address) assert.NotEmpty(t, addressInfo.PublicKey) assert.Equal(t, label, addressInfo.Label) assert.Equal(t, "m/12381'/21888'/1'/0", addressInfo.Path) pub, _ := bls.PublicKeyFromString(addressInfo.PublicKey) assert.Equal(t, pub.ValidatorAddress().String(), addressInfo.Address) } func TestNewBLSAccountAddress(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) label := td.RandString(16) addressInfo, err := td.wallet.NewBLSAccountAddress(label) require.NoError(t, err) assert.NotEmpty(t, addressInfo.Address) assert.NotEmpty(t, addressInfo.PublicKey) assert.Equal(t, label, addressInfo.Label) assert.Equal(t, "m/12381'/21888'/2'/0", addressInfo.Path) pub, _ := bls.PublicKeyFromString(addressInfo.PublicKey) assert.Equal(t, pub.AccountAddress().String(), addressInfo.Address) } func TestNewE225519AccountAddress(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) label := td.RandString(16) addressInfo, err := td.wallet.NewEd25519AccountAddress(label, td.password) require.NoError(t, err) assert.NotEmpty(t, addressInfo.Address) assert.NotEmpty(t, addressInfo.PublicKey) assert.Equal(t, label, addressInfo.Label) assert.Equal(t, "m/44'/21888'/3'/0'", addressInfo.Path) pub, _ := ed25519.PublicKeyFromString(addressInfo.PublicKey) assert.Equal(t, pub.AccountAddress().String(), addressInfo.Address) } func TestImportBLSPrivateKey(t *testing.T) { td := setup(t) pub, prv := td.RandBLSKeyPair() t.Run("Invalid password", func(t *testing.T) { td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(false) err := td.wallet.ImportBLSPrivateKey("invalid-password", prv) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Ok", func(t *testing.T) { td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(false) td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil).Times(2) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) err := td.wallet.ImportBLSPrivateKey(td.password, prv) require.NoError(t, err) td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(true) td.mockStorage.EXPECT().HasAddress(pub.ValidatorAddress().String()).Return(true) assert.True(t, td.wallet.HasAddress(pub.AccountAddress().String())) assert.True(t, td.wallet.HasAddress(pub.ValidatorAddress().String())) }) t.Run("Reimporting private key", func(t *testing.T) { td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(true) err := td.wallet.ImportBLSPrivateKey(td.password, prv) require.ErrorIs(t, err, ErrAddressExists) }) } func TestImportEd25519PrivateKey(t *testing.T) { td := setup(t) pub, prv := td.RandEd25519KeyPair() t.Run("Invalid password", func(t *testing.T) { td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(false) err := td.wallet.ImportEd25519PrivateKey("invalid-password", prv) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Ok", func(t *testing.T) { td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(false) td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) err := td.wallet.ImportEd25519PrivateKey(td.password, prv) require.NoError(t, err) td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(true) assert.True(t, td.wallet.HasAddress(pub.AccountAddress().String())) }) t.Run("Reimporting private key", func(t *testing.T) { td.mockStorage.EXPECT().HasAddress(pub.AccountAddress().String()).Return(true) err := td.wallet.ImportEd25519PrivateKey(td.password, prv) require.ErrorIs(t, err, ErrAddressExists) }) } func TestSetAddressLabel(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) testAddr, err := td.wallet.NewBLSAccountAddress("test") require.NoError(t, err) t.Run("Set label for unknown address", func(t *testing.T) { invAddr := td.RandAccAddress().String() td.mockStorage.EXPECT().AddressInfo(invAddr).Return(nil, storage.ErrNotFound).AnyTimes() err := td.wallet.SetAddressLabel(invAddr, "i have label") require.ErrorIs(t, err, storage.ErrNotFound) assert.Empty(t, td.wallet.AddressLabel(invAddr)) }) t.Run("Update label", func(t *testing.T) { updatedInfo := *testAddr updatedInfo.Label = "I have a label" td.mockStorage.EXPECT().AddressInfo(testAddr.Address).Return(testAddr, nil) td.mockStorage.EXPECT().UpdateAddress(&updatedInfo).Return(nil) td.mockStorage.EXPECT().AddressInfo(testAddr.Address).Return(&updatedInfo, nil) err := td.wallet.SetAddressLabel(testAddr.Address, "I have a label") require.NoError(t, err) assert.Equal(t, "I have a label", td.wallet.AddressLabel(testAddr.Address)) }) t.Run("Remove label", func(t *testing.T) { noLabelInfo := *testAddr noLabelInfo.Label = "" td.mockStorage.EXPECT().AddressInfo(testAddr.Address).Return(testAddr, nil) td.mockStorage.EXPECT().UpdateAddress(&noLabelInfo).Return(nil) td.mockStorage.EXPECT().AddressInfo(testAddr.Address).Return(&noLabelInfo, nil) err := td.wallet.SetAddressLabel(testAddr.Address, "") require.NoError(t, err) assert.Empty(t, td.wallet.AddressLabel(testAddr.Address)) }) } ================================================ FILE: wallet/addresspath/errors.go ================================================ package addresspath import "errors" // ErrInvalidPath describes an error in which the key path is invalid. var ErrInvalidPath = errors.New("the key path is invalid") ================================================ FILE: wallet/addresspath/path.go ================================================ package addresspath import ( "fmt" "strconv" "strings" "github.com/pactus-project/pactus/crypto" "golang.org/x/exp/constraints" ) type Purpose uint32 const ( PurposeBLS12381 Purpose = 12381 PurposeBIP44 Purpose = 44 PurposeImportPrivateKey Purpose = 65535 ) type CoinType uint32 const ( CoinTypePactusMainnet CoinType = 21888 CoinTypePactusTestnet CoinType = 21777 ) const hardenedKeyStart = uint32(0x80000000) // 2^31 // Harden hardens the integer value 'i' by adding 0x80000000 (2^31) to it. // This function does not check if 'i' is already hardened. func Harden[T constraints.Integer](i T) uint32 { return uint32(i) + hardenedKeyStart } // UnHarden unhardens the integer value 'i' by subtracting 0x80000000 (2^31) from it. // This function does not check if 'i' is already non-hardened. func UnHarden[T constraints.Integer](i T) uint32 { return uint32(i) - hardenedKeyStart } type Path []uint32 func NewPath(indexes ...uint32) Path { p := make([]uint32, 0, len(indexes)) p = append(p, indexes...) return p } func FromString(str string) (Path, error) { sub := strings.Split(str, "/") if sub[0] != "m" { return nil, ErrInvalidPath } // TODO: check the path should exactly 4 levels. var path []uint32 for i := 1; i < len(sub); i++ { indexStr := sub[i] added := uint32(0) if indexStr[len(indexStr)-1] == '\'' { added = hardenedKeyStart indexStr = indexStr[:len(indexStr)-1] } val, err := strconv.ParseInt(indexStr, 10, 32) if err != nil { return nil, err } path = append(path, uint32(val)+added) } return path, nil } func (p Path) String() string { var builder strings.Builder builder.WriteString("m") for _, i := range p { if i >= hardenedKeyStart { fmt.Fprintf(&builder, "/%d'", i-hardenedKeyStart) } else { fmt.Fprintf(&builder, "/%d", i) } } return builder.String() } // TODO: we can add IsBLSPurpose or IsImportedPurpose functions func (p Path) Purpose() Purpose { return Purpose(UnHarden(p[0])) } func (p Path) CoinType() CoinType { return CoinType(UnHarden(p[len(p)-3])) } func (p Path) AddressType() crypto.AddressType { return crypto.AddressType(UnHarden(p[len(p)-2])) } func (p Path) AddressIndex() uint32 { return p[len(p)-1] } ================================================ FILE: wallet/addresspath/path_test.go ================================================ package addresspath import ( "strconv" "testing" "github.com/pactus-project/pactus/crypto" "github.com/stretchr/testify/assert" ) func TestHardenedKey(t *testing.T) { num := uint32(12345) hardenedNum := Harden(num) unhardenedNum := UnHarden(hardenedNum) assert.Equal(t, num, unhardenedNum) } func TestPathToString(t *testing.T) { h := hardenedKeyStart tests := []struct { path Path wantStr string }{ {NewPath(), "m"}, {NewPath(0), "m/0"}, {NewPath(0, 1), "m/0/1"}, {NewPath(0, 1, 1000000000), "m/0/1/1000000000"}, {NewPath(h), "m/0'"}, {NewPath(h, h+1), "m/0'/1'"}, {NewPath(h, h+1, h+1000000000), "m/0'/1'/1000000000'"}, } for no, tt := range tests { assert.Equal(t, tt.wantStr, tt.path.String(), "case %d failed", no) } } func TestStringToPath(t *testing.T) { h := hardenedKeyStart tests := []struct { str string wantPath Path wantErr error }{ {"m", nil, nil}, {"m/0", Path{0}, nil}, {"m/0/1", Path{0, 1}, nil}, {"m/0/1/1000000000", Path{0, 1, 1000000000}, nil}, {"m/0'", Path{h}, nil}, {"m/0'/1'", Path{h, h + 1}, nil}, {"m/0'/1'/1000000000'", Path{h, h + 1, h + 1000000000}, nil}, {"i", nil, ErrInvalidPath}, {"m/'", nil, strconv.ErrSyntax}, {"m/abc'", nil, strconv.ErrSyntax}, } for no, tt := range tests { path, err := FromString(tt.str) assert.Equal(t, tt.wantPath, path, "case %d failed", no) assert.ErrorIsf(t, err, tt.wantErr, "case %d failed", no) } } func TestPathHelpers(t *testing.T) { path := Path{ 12381 + hardenedKeyStart, 21888 + hardenedKeyStart, 2 + hardenedKeyStart, 1, } assert.Equal(t, PurposeBLS12381, path.Purpose()) assert.Equal(t, CoinTypePactusMainnet, path.CoinType()) assert.Equal(t, crypto.AddressTypeBLSAccount, path.AddressType()) assert.Equal(t, uint32(1), path.AddressIndex()) } ================================================ FILE: wallet/encrypter/encrypter.go ================================================ package encrypter import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/base64" "fmt" "strings" "github.com/pactus-project/pactus/util" "golang.org/x/crypto/argon2" ) // Parameters are set based on the spec recommendation // Read more here https://datatracker.ietf.org/doc/html/rfc9106#section-4 type argon2dParameters struct { iterations uint32 memory uint32 parallelism uint8 keyLen uint32 } type Option func(p *argon2dParameters) func OptionIteration(iterations uint32) func(p *argon2dParameters) { return func(p *argon2dParameters) { p.iterations = iterations } } func OptionMemory(memory uint32) func(p *argon2dParameters) { return func(p *argon2dParameters) { p.memory = memory } } func OptionParallelism(parallelism uint8) func(p *argon2dParameters) { return func(p *argon2dParameters) { p.parallelism = parallelism } } const ( nameParamIterations = "iterations" nameParamMemory = "memory" nameParamParallelism = "parallelism" nameParamKeyLen = "keylen" nameFuncNope = "" nameFuncArgon2ID = "ARGON2ID" nameFuncAES256CTR = "AES_256_CTR" nameFuncAES256CBC = "AES_256_CBC" nameFuncMACv1 = "MACV1" // Parameter Choice // https://www.rfc-editor.org/rfc/rfc9106.html#section-4 defaultIterations = 3 defaultMemory = 65536 // 2 ^ 16 defaultParallelism = 4 defaultKeyLen = 48 ) // Encrypter keeps the method and parameters for the cipher algorithm. type Encrypter struct { Method string `json:"method,omitempty"` Params params `json:"params,omitempty"` } // NopeEncrypter creates a nope encrypter instance. // // The nope encrypter doesn't encrypt the message and the cipher message is same // as original message. func NopeEncrypter() Encrypter { return Encrypter{ Method: nameFuncNope, Params: nil, } } // DefaultEncrypter creates a new encrypter instance. // If no option sets it uses the default parameters. // // The default encrypter uses Argon2ID as password hasher and AES_256_CTR as // encryption algorithm. func DefaultEncrypter(opts ...Option) Encrypter { argon2dParameters := &argon2dParameters{ iterations: defaultIterations, memory: defaultMemory, parallelism: defaultParallelism, keyLen: defaultKeyLen, } for _, opt := range opts { opt(argon2dParameters) } method := fmt.Sprintf("%s-%s-%s", nameFuncArgon2ID, nameFuncAES256CTR, nameFuncMACv1) encParams := newParams() encParams.SetUint32(nameParamIterations, argon2dParameters.iterations) encParams.SetUint32(nameParamMemory, argon2dParameters.memory) encParams.SetUint8(nameParamParallelism, argon2dParameters.parallelism) encParams.SetUint32(nameParamKeyLen, argon2dParameters.keyLen) return Encrypter{ Method: method, Params: encParams, } } func (e *Encrypter) IsEncrypted() bool { return e.Method != nameFuncNope } // Encrypt encrypts the `message` using give `password` and returns the cipher message. func (e *Encrypter) Encrypt(message, password string) (string, error) { if e.Method == nameFuncNope { if password != "" { return "", ErrInvalidPassword } return message, nil } // Check if password is empty if password == "" { return "", ErrInvalidPassword } funcs := strings.Split(e.Method, "-") if len(funcs) != 3 { return "", ErrMethodNotSupported } // Password hasher method salt := make([]byte, 16) _, err := rand.Read(salt) if err != nil { return "", err } iterations := e.Params.GetUint32(nameParamIterations) memory := e.Params.GetUint32(nameParamMemory) parallelism := e.Params.GetUint8(nameParamParallelism) keyLen := e.Params.GetUint32(nameParamKeyLen) if keyLen == 32 { // Legacy encryption methods where the same salt is reused as the IV. // Update to 48 byes key length. keyLen = 48 e.Params.SetUint32(nameParamKeyLen, 48) } // Password hasher method var passwordHash []byte switch funcs[0] { case nameFuncArgon2ID: // Argon2 currently has three modes: // - data-dependent Argon2d, // - data-independent Argon2i, // - a mix of the two, Argon2id. passwordHash = argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, keyLen) default: return "", ErrMethodNotSupported } // Encrypter method // The first 32 bytes are used as the encryption key, and the last 16 bytes are used as the IV. cipherKey := passwordHash[:32] initVec := passwordHash[32:] var cipher []byte switch funcs[1] { case nameFuncAES256CTR: cipher = aes256CTRCrypt([]byte(message), initVec, cipherKey) case nameFuncAES256CBC: cipher = aes256CBCEncrypt([]byte(message), initVec, cipherKey) default: return "", ErrMethodNotSupported } // MAC method data := make([]byte, 0) switch funcs[2] { case nameFuncMACv1: // Calculate the MAC // We use the MAC to check if the password is correct. // Use Cipher key as the key for the MAC. // https: //en.wikipedia.org/wiki/Authenticated_encryption#Encrypt-then-MAC_(EtM) mac := calcMACv1(cipherKey[16:32], cipher) data = append(data, salt...) data = append(data, cipher...) data = append(data, mac...) default: return "", ErrMethodNotSupported } cipherText := base64.StdEncoding.EncodeToString(data) return cipherText, nil } // Decrypt decrypts the `cipher` using give `password` and returns the original message. func (e *Encrypter) Decrypt(cipherText, password string) (string, error) { if e.Method == nameFuncNope { if password != "" { return "", ErrInvalidPassword } return cipherText, nil } funcs := strings.Split(e.Method, "-") if len(funcs) != 3 { return "", ErrMethodNotSupported } data, err := base64.StdEncoding.DecodeString(cipherText) if err != nil { return "", ErrInvalidCipher } // Minimum length of data should be 20 (16 salt + 4 bytes mac) if len(data) < 20 { return "", ErrInvalidCipher } iterations := e.Params.GetUint32(nameParamIterations) memory := e.Params.GetUint32(nameParamMemory) parallelism := e.Params.GetUint8(nameParamParallelism) keyLen := e.Params.GetUint32(nameParamKeyLen) // Password hasher method salt := data[0:16] var passwordHash []byte switch funcs[0] { case nameFuncArgon2ID: passwordHash = argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, keyLen) default: return "", ErrMethodNotSupported } // Encrypter method var initVec, cipherKey []byte switch keyLen { case 32: // This case supports legacy encryption methods where the same salt is reused as the IV. cipherKey = passwordHash initVec = salt case 48: // The first 32 bytes are used as the encryption key, and the last 16 bytes are used as the IV. cipherKey = passwordHash[:32] initVec = passwordHash[32:] default: return "", ErrInvalidParam } cipher := data[16 : len(data)-4] var msg []byte switch funcs[1] { case nameFuncAES256CTR: msg = aes256CTRCrypt(cipher, initVec, cipherKey) case nameFuncAES256CBC: msg = aes256CBCDecrypt(cipher, initVec, cipherKey) default: return "", ErrMethodNotSupported } // MAC method switch funcs[2] { case nameFuncMACv1: mac := data[len(data)-4:] if !util.SafeCmp(mac, calcMACv1(cipherKey[16:32], cipher)) { return "", ErrInvalidPassword } default: return "", ErrMethodNotSupported } return string(msg), nil } // aes256CTRCrypt encrypts or decrypts a message using AES-256-CTR mode. // It requires a 32-byte (256-bit) cipher key and a 16-byte (128-bit) initialization vector (IV). // Returns the encrypted or decrypted output. func aes256CTRCrypt(input, initVec, cipherKey []byte) []byte { aesCipher, _ := aes.NewCipher(cipherKey) output := make([]byte, len(input)) stream := cipher.NewCTR(aesCipher, initVec) stream.XORKeyStream(output, input) return output } // aes256CBCEncrypt encrypts a plain message using AES-256-CBC mode. // It requires a 32-byte (256-bit) cipher key and a 16-byte (128-bit) initialization vector (IV). // Returns the encrypted cipher message. func aes256CBCEncrypt(plainMsg, initVec, cipherKey []byte) []byte { aesCipher, _ := aes.NewCipher(cipherKey) plainMsg = pkcs7Padding(plainMsg, aes.BlockSize) cipherMsg := make([]byte, len(plainMsg)) enc := cipher.NewCBCEncrypter(aesCipher, initVec) enc.CryptBlocks(cipherMsg, plainMsg) return cipherMsg } // aes256CBCDecrypt decrypts a cipher message using AES-256-CBC mode. // It requires a 32-byte (256-bit) cipher key and a 16-byte (128-bit) initialization vector (IV). // Returns the decrypted plain message. func aes256CBCDecrypt(cipherMsg, initVec, cipherKey []byte) []byte { aesCipher, _ := aes.NewCipher(cipherKey) plainMsg := make([]byte, len(cipherMsg)) dec := cipher.NewCBCDecrypter(aesCipher, initVec) dec.CryptBlocks(plainMsg, cipherMsg) plainMsg = pkcs7UnPadding(plainMsg) return plainMsg } func pkcs7Padding(cipherMsg []byte, blockSize int) []byte { padding := blockSize - len(cipherMsg)%blockSize padMsg := bytes.Repeat([]byte{byte(padding)}, padding) return append(cipherMsg, padMsg...) } func pkcs7UnPadding(plainMsg []byte) []byte { length := len(plainMsg) unpadding := int(plainMsg[length-1]) if length-unpadding <= 0 { return plainMsg } return plainMsg[:(length - unpadding)] } // calcMACv1 calculates the 4 bytes MAC of the given slices base on SHA-256. func calcMACv1(data ...[]byte) []byte { hasher := sha256.New() for _, d := range data { _, _ = hasher.Write(d) } return hasher.Sum(nil)[:4] } ================================================ FILE: wallet/encrypter/encrypter_test.go ================================================ package encrypter import ( "testing" "github.com/pactus-project/pactus/util/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNopeEncrypterParams(t *testing.T) { enc := NopeEncrypter() assert.Empty(t, enc.Method) assert.Nil(t, enc.Params) assert.False(t, enc.IsEncrypted()) } func TestNopeEncrypter(t *testing.T) { enc := NopeEncrypter() msg := "foo" _, err := enc.Encrypt(msg, "password") require.ErrorIs(t, err, ErrInvalidPassword) cipher, err := enc.Encrypt(msg, "") require.NoError(t, err) assert.Equal(t, msg, cipher) _, err = enc.Decrypt(cipher, "password") require.ErrorIs(t, err, ErrInvalidPassword) decipher, err := enc.Decrypt(cipher, "") require.NoError(t, err) assert.Equal(t, msg, decipher) } func TestDefaultEncrypterParams(t *testing.T) { opts := []Option{ OptionIteration(3), OptionMemory(4), OptionParallelism(5), } enc := DefaultEncrypter(opts...) assert.Equal(t, "ARGON2ID-AES_256_CTR-MACV1", enc.Method) assert.Equal(t, "3", enc.Params["iterations"]) assert.Equal(t, "4", enc.Params["memory"]) assert.Equal(t, "5", enc.Params["parallelism"]) assert.Equal(t, "48", enc.Params["keylen"]) assert.True(t, enc.IsEncrypted()) } func TestDefaultEncrypter(t *testing.T) { ts := testsuite.NewTestSuite(t) enc := &Encrypter{ Method: "ARGON2ID-AES_256_CTR-MACV1", Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "48", }, } msg := ts.RandString(ts.RandIntNonZero(100)) password := ts.RandString(ts.RandIntNonZero(100)) _, err := enc.Encrypt(msg, "") require.ErrorIs(t, err, ErrInvalidPassword) cipher, err := enc.Encrypt(msg, password) require.NoError(t, err) dec, err := enc.Decrypt(cipher, password) require.NoError(t, err) assert.Equal(t, msg, dec) _, err = enc.Decrypt(cipher, "invalid-password") require.ErrorIs(t, err, ErrInvalidPassword) } func TestInvalidMethod(t *testing.T) { tests := []struct { method string }{ {"XXX-AES_256_CTR-MACV1"}, {"ARGON2ID-XXX-MACV1"}, {"ARGON2ID-AES_256_CTR-XXX"}, {"XXX"}, } for _, tt := range tests { enc := &Encrypter{ Method: tt.method, Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "48", }, } _, err := enc.Encrypt("foo", "password") require.ErrorIs(t, err, ErrMethodNotSupported) _, err = enc.Decrypt("AJFPsGu6bDMJ5iuMWDJS/87xVs7r", "password") require.ErrorIs(t, err, ErrMethodNotSupported) } } func TestInvalidDecrypt(t *testing.T) { enc := &Encrypter{ Method: "ARGON2ID-AES_256_CTR-MACV1", Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "48", }, } _, err := enc.Decrypt("", "password") require.ErrorIs(t, err, ErrInvalidCipher) _, err = enc.Decrypt("invalid-base64", "password") require.ErrorIs(t, err, ErrInvalidCipher) enc.Params.SetUint32(nameParamKeyLen, 64) _, err = enc.Decrypt("AJFPsGu6bDMJ5iuMWDJS/87xVs7r", "password") require.ErrorIs(t, err, ErrInvalidParam) } func TestAES256CBC(t *testing.T) { enc := &Encrypter{ Method: "ARGON2ID-AES_256_CBC-MACV1", Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "48", }, } msg := "foo" password := "cowboy" _, err := enc.Encrypt(msg, "") require.ErrorIs(t, err, ErrInvalidPassword) cipher, err := enc.Encrypt(msg, password) require.NoError(t, err) dec, err := enc.Decrypt(cipher, password) require.NoError(t, err) assert.Equal(t, msg, dec) _, err = enc.Decrypt(cipher, "invalid-password") require.ErrorIs(t, err, ErrInvalidPassword) } func TestDecrypt(t *testing.T) { msg := "foo" password := "cowboy" tests := []struct { name string enc Encrypter cipher string }{ { name: "Legacy cipher with keylen 32", enc: Encrypter{ Method: "ARGON2ID-AES_256_CTR-MACV1", Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "32", }, }, // 854fe79513661e1297075b6fdf6124b7 872da0 fec644bc cipher: "hU/nlRNmHhKXB1tv32Ekt4ctoP7GRLw=", }, { name: "Stream Cipher with keylen 48", enc: Encrypter{ Method: "ARGON2ID-AES_256_CTR-MACV1", Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "48", }, }, // f000c3271de35c14162b0ddceeac0492 b4da66 b04cae34 cipher: "8ADDJx3jXBQWKw3c7qwEkrTaZrBMrjQ=", }, { name: "Block Cipher with keylen 48", enc: Encrypter{ Method: "ARGON2ID-AES_256_CBC-MACV1", Params: params{ nameParamIterations: "1", nameParamMemory: "8", nameParamParallelism: "1", nameParamKeyLen: "48", }, }, // b14b280a9e5f7907671a405b8b8c918a 639f113cef2b6d37e7d590678b5d5a45 b422f34e cipher: "sUsoCp5feQdnGkBbi4yRimOfETzvK20359WQZ4tdWkW0IvNO", }, } for _, tt := range tests { dec, err := tt.enc.Decrypt(tt.cipher, password) require.NoError(t, err) assert.Equal(t, msg, dec) } } ================================================ FILE: wallet/encrypter/error.go ================================================ package encrypter import ( "errors" ) // ErrInvalidPassword describes an error in which the password is invalid. var ErrInvalidPassword = errors.New("invalid password") // ErrInvalidParam describes an error in which the encryption parameter is invalid. var ErrInvalidParam = errors.New("invalid param") // ErrInvalidCipher describes an error in which the cipher message is invalid. var ErrInvalidCipher = errors.New("invalid cipher message") // ErrMethodNotSupported describes an error in which the cipher method is not known. var ErrMethodNotSupported = errors.New("cipher method is not supported") ================================================ FILE: wallet/encrypter/params.go ================================================ package encrypter import ( "encoding/base64" "strconv" ) type params map[string]string func newParams() params { return make(map[string]string) } func (p params) SetUint8(key string, val uint8) { p.SetUint64(key, uint64(val)) } func (p params) SetUint32(key string, val uint32) { p.SetUint64(key, uint64(val)) } func (p params) SetUint64(key string, val uint64) { p[key] = strconv.FormatUint(val, 10) } func (p params) SetBytes(key string, val []byte) { p[key] = base64.StdEncoding.EncodeToString(val) } func (p params) SetString(key, val string) { p[key] = val } func (p params) GetUint8(key string) uint8 { return uint8(p.GetUint64(key)) } func (p params) GetUint32(key string) uint32 { return uint32(p.GetUint64(key)) } func (p params) GetUint64(key string) uint64 { val, err := strconv.ParseUint(p[key], 10, 64) if err != nil { return 0 } return val } func (p params) GetBytes(key string) []byte { val, err := base64.StdEncoding.DecodeString(p[key]) if err != nil { return []byte{} } return val } func (p params) GetString(key string) string { return p[key] } ================================================ FILE: wallet/encrypter/params_test.go ================================================ package encrypter import ( "testing" "github.com/stretchr/testify/assert" ) func TestParamsUint8(t *testing.T) { tests := []struct { key string val uint8 }{ {"k1", uint8(0)}, {"k2", uint8(0xFF)}, } p := params{} for _, tt := range tests { p.SetUint8(tt.key, tt.val) assert.Equal(t, tt.val, p.GetUint8(tt.key)) } } func TestParamsUint32(t *testing.T) { tests := []struct { key string val uint32 }{ {"k1", uint32(0)}, {"k2", uint32(0xFFFFFFFF)}, } p := params{} for _, tt := range tests { p.SetUint32(tt.key, tt.val) assert.Equal(t, tt.val, p.GetUint32(tt.key)) } } func TestParamsUint64(t *testing.T) { tests := []struct { key string val uint64 }{ {"k1", uint64(0)}, {"k2", uint64(0xFFFFFFFFFFFFFFFF)}, } p := params{} for _, tt := range tests { p.SetUint64(tt.key, tt.val) assert.Equal(t, tt.val, p.GetUint64(tt.key)) } } func TestParamsBytes(t *testing.T) { tests := []struct { key string val []byte base64 string }{ {"k1", []byte{0, 0}, "AAA="}, {"k2", []byte{0xff, 0xff}, "//8="}, {"k2", []byte{}, ""}, } p := params{} for _, tt := range tests { p.SetBytes(tt.key, tt.val) assert.Equal(t, tt.val, p.GetBytes(tt.key)) assert.Equal(t, tt.base64, p.GetString(tt.key)) } } func TestParamsString(t *testing.T) { tests := []struct { key string val string }{ {"k1", "foo"}, {"k2", "bar"}, {"k3", ""}, } p := params{} for _, tt := range tests { p.SetString(tt.key, tt.val) assert.Equal(t, tt.val, p.GetString(tt.key)) } } ================================================ FILE: wallet/errors.go ================================================ package wallet import ( "errors" "fmt" ) var ( // ErrInvalidAddressType describes an error in which the address type is invalid. ErrInvalidAddressType = errors.New("invalid address type") // ErrAddressExists describes an error in which the address already exist // in wallet. ErrAddressExists = errors.New("address already exists") // ErrTransactionExists indicates the transaction already exists in the wallet. ErrTransactionExists = errors.New("transaction already exists") ) // ExitsError describes an error in which a wallet exists in the // given path. type ExitsError struct { Path string } func (e ExitsError) Error() string { return fmt.Sprintf("a wallet exists at: %s", e.Path) } ================================================ FILE: wallet/manager/config.go ================================================ package manager import ( "github.com/pactus-project/pactus/genesis" ) // Config defines parameters for the wallet module. type Config struct { LockMode bool `toml:"lock_mode"` // private config ChainType genesis.ChainType `toml:"-"` WalletsDir string `toml:"-"` } func DefaultConfig() *Config { return &Config{ LockMode: true, } } func (*Config) BasicCheck() error { return nil } ================================================ FILE: wallet/manager/config_test.go ================================================ package manager import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConfig(t *testing.T) { conf := DefaultConfig() assert.True(t, conf.LockMode) require.NoError(t, conf.BasicCheck()) } ================================================ FILE: wallet/manager/errors.go ================================================ package manager import ( "errors" ) var ( // ErrWalletAlreadyExists indicates a wallet already exists on disk. ErrWalletAlreadyExists = errors.New("wallet already exists") // ErrWalletNotLoaded indicates a wallet is not loaded in memory. ErrWalletNotLoaded = errors.New("wallet is not loaded") ) ================================================ FILE: wallet/manager/interface.go ================================================ package manager import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/types" ) // IManager defines the public API of the wallet manager. type IManager interface { Start() error Stop() GetValidatorAddress(publicKey string) (string, error) CreateWallet(walletName, password string) (string, error) RestoreWallet(walletName, mnemonic, password string) error ListWallets() ([]string, error) WalletInfo(walletName string) (*types.WalletInfo, error) UpdatePassword(walletName, oldPassword, newPassword string) error TotalBalance(walletName string) (amount.Amount, error) TotalStake(walletName string) (amount.Amount, error) SetDefaultFee(walletName string, fee amount.Amount) error SignRawTransaction(walletName, password string, rawTx []byte) (txID, data []byte, err error) SignMessage(walletName, password, addr, msg string) (string, error) PrivateKey(walletName, password, addr string) (crypto.PrivateKey, error) Mnemonic(walletName, password string) (string, error) NewAddress(walletName string, addressType crypto.AddressType, label string, opts ...wallet.NewAddressOption) (*types.AddressInfo, error) ListAddresses(walletName string, opts ...wallet.ListAddressOption) ([]types.AddressInfo, error) AddressInfo(walletName, address string) (*types.AddressInfo, error) AddressLabel(walletName, addr string) (string, error) SetAddressLabel(walletName, addr, label string) error Balance(walletName, addr string) (amount.Amount, error) Stake(walletName, addr string) (amount.Amount, error) // Transaction creation / signing / broadcast MakeTransferTx(walletName, sender, receiver string, amt amount.Amount, opts ...wallet.TxOption) (*tx.Tx, error) MakeBondTx(walletName, sender, receiver, publicKey string, amt amount.Amount, opts ...wallet.TxOption) (*tx.Tx, error) MakeUnbondTx(walletName, validator string, opts ...wallet.TxOption) (*tx.Tx, error) MakeWithdrawTx(walletName, sender, receiver string, amt amount.Amount, opts ...wallet.TxOption) (*tx.Tx, error) SignTransaction(walletName, password string, trx *tx.Tx) error BroadcastTransaction(walletName string, trx *tx.Tx) (string, error) ListTransactions(walletName string, opts ...wallet.ListTransactionsOption) ([]*types.TransactionInfo, error) } ================================================ FILE: wallet/manager/manager.go ================================================ package manager import ( "context" "fmt" "path/filepath" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/provider" "github.com/pactus-project/pactus/wallet/types" ) var _ IManager = (*Manager)(nil) type Manager struct { ctx context.Context wallets map[string]*wallet.Wallet chainType genesis.ChainType walletDirectory string DefaultWalletName string provider provider.IBlockchainProvider eventPipe pipeline.Pipeline[any] } func NewManager(ctx context.Context, conf *Config, provider provider.IBlockchainProvider, eventPipe pipeline.Pipeline[any], ) (IManager, error) { wallets := make(map[string]*wallet.Wallet) files, err := util.ListFilesInDir(conf.WalletsDir) if err != nil { return nil, err } for _, file := range files { opts := []wallet.OpenWalletOption{ wallet.WithBlockchainProvider(provider), wallet.WithEventPipe(eventPipe), wallet.WithLockMode(conf.LockMode), } wlt, err := wallet.Open(ctx, file, opts...) if err != nil { return nil, fmt.Errorf("failed to open wallet %s: %w", file, err) } wallets[filepath.Base(file)] = wlt } return &Manager{ ctx: ctx, wallets: wallets, chainType: conf.ChainType, walletDirectory: conf.WalletsDir, provider: provider, eventPipe: eventPipe, }, nil } func (*Manager) Start() error { return nil } func (wm *Manager) Stop() { for _, wlt := range wm.wallets { wlt.Close() } } func (wm *Manager) getWalletPath(walletName string) string { return util.MakeAbs(filepath.Join(wm.walletDirectory, walletName)) } func (wm *Manager) createWalletWithMnemonic( walletName, mnemonic, password string, ) error { walletPath := wm.getWalletPath(walletName) if isExists := util.PathExists(walletPath); isExists { return ErrWalletAlreadyExists } wlt, err := wallet.Create(wm.ctx, walletPath, mnemonic, password, wm.chainType, wallet.WithBlockchainProvider(wm.provider), wallet.WithEventPipe(wm.eventPipe)) if err != nil { return err } wm.wallets[walletName] = wlt return nil } // Deprecated: Move it to the utils service. func (*Manager) GetValidatorAddress( publicKey string, ) (string, error) { pubKey, err := bls.PublicKeyFromString(publicKey) if err != nil { return "", err } return pubKey.ValidatorAddress().String(), nil } func (wm *Manager) CreateWallet( walletName, password string, ) (string, error) { mnemonic, err := wallet.GenerateMnemonic(128) if err != nil { return "", err } if err := wm.createWalletWithMnemonic(walletName, mnemonic, password); err != nil { return "", err } return mnemonic, nil } func (wm *Manager) RestoreWallet(walletName, mnemonic, password string) error { return wm.createWalletWithMnemonic(walletName, mnemonic, password) } func (wm *Manager) NewAddress(walletName string, addressType crypto.AddressType, label string, opts ...wallet.NewAddressOption, ) (*types.AddressInfo, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.NewAddress(addressType, label, opts...) } func (wm *Manager) PrivateKey(walletName, password, addr string) (crypto.PrivateKey, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.PrivateKey(password, addr) } func (wm *Manager) Mnemonic(walletName, password string) (string, error) { wlt, ok := wm.wallets[walletName] if !ok { return "", ErrWalletNotLoaded } return wlt.Mnemonic(password) } func (wm *Manager) AddressLabel(walletName, addr string) (string, error) { wlt, ok := wm.wallets[walletName] if !ok { return "", ErrWalletNotLoaded } return wlt.AddressLabel(addr), nil } func (wm *Manager) SetAddressLabel(walletName, addr, label string) error { wlt, ok := wm.wallets[walletName] if !ok { return ErrWalletNotLoaded } return wlt.SetAddressLabel(addr, label) } func (wm *Manager) Balance(walletName, addr string) (amount.Amount, error) { wlt, ok := wm.wallets[walletName] if !ok { return 0, ErrWalletNotLoaded } return wlt.Balance(addr) } func (wm *Manager) Stake(walletName, addr string) (amount.Amount, error) { wlt, ok := wm.wallets[walletName] if !ok { return 0, ErrWalletNotLoaded } return wlt.Stake(addr) } func (wm *Manager) SetDefaultFee(walletName string, fee amount.Amount) error { wlt, ok := wm.wallets[walletName] if !ok { return ErrWalletNotLoaded } return wlt.SetDefaultFee(fee) } func (wm *Manager) MakeTransferTx( walletName, sender, receiver string, amt amount.Amount, opts ...wallet.TxOption, ) (*tx.Tx, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.MakeTransferTx(sender, receiver, amt, opts...) } func (wm *Manager) MakeBondTx( walletName, sender, receiver, publicKey string, amt amount.Amount, opts ...wallet.TxOption, ) (*tx.Tx, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.MakeBondTx(sender, receiver, publicKey, amt, opts...) } func (wm *Manager) MakeUnbondTx(walletName, validatorAddr string, opts ...wallet.TxOption) (*tx.Tx, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.MakeUnbondTx(validatorAddr, opts...) } func (wm *Manager) MakeWithdrawTx( walletName, sender, receiver string, amt amount.Amount, opts ...wallet.TxOption, ) (*tx.Tx, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.MakeWithdrawTx(sender, receiver, amt, opts...) } func (wm *Manager) SignTransaction(walletName, password string, trx *tx.Tx) error { wlt, ok := wm.wallets[walletName] if !ok { return ErrWalletNotLoaded } return wlt.SignTransaction(password, trx) } func (wm *Manager) BroadcastTransaction(walletName string, trx *tx.Tx) (string, error) { wlt, ok := wm.wallets[walletName] if !ok { return "", ErrWalletNotLoaded } return wlt.BroadcastTransaction(trx) } func (wm *Manager) TotalBalance(walletName string) (amount.Amount, error) { wlt, ok := wm.wallets[walletName] if !ok { return 0, ErrWalletNotLoaded } return wlt.TotalBalance() } func (wm *Manager) TotalStake(walletName string) (amount.Amount, error) { wlt, ok := wm.wallets[walletName] if !ok { return 0, ErrWalletNotLoaded } return wlt.TotalStake() } func (wm *Manager) SignRawTransaction( walletName, password string, rawTx []byte, ) (txID, data []byte, err error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, nil, ErrWalletNotLoaded } trx, err := tx.FromBytes(rawTx) if err != nil { return nil, nil, err } if err := wlt.SignTransaction(password, trx); err != nil { return nil, nil, err } data, err = trx.Bytes() if err != nil { return nil, nil, err } return trx.ID().Bytes(), data, nil } func (wm *Manager) SignMessage(walletName, password, addr, msg string) (string, error) { wlt, ok := wm.wallets[walletName] if !ok { return "", ErrWalletNotLoaded } return wlt.SignMessage(password, addr, msg) } func (wm *Manager) AddressInfo(walletName, address string) (*types.AddressInfo, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.AddressInfo(address) } func (wm *Manager) WalletInfo(walletName string) (*types.WalletInfo, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.Info(), nil } func (wm *Manager) ListWallets() ([]string, error) { wallets := make([]string, 0, len(wm.wallets)) for name := range wm.wallets { wallets = append(wallets, name) } return wallets, nil } func (wm *Manager) ListAddresses(walletName string, opts ...wallet.ListAddressOption) ([]types.AddressInfo, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.ListAddresses(opts...), nil } func (wm *Manager) ListTransactions(walletName string, opts ...wallet.ListTransactionsOption, ) ([]*types.TransactionInfo, error) { wlt, ok := wm.wallets[walletName] if !ok { return nil, ErrWalletNotLoaded } return wlt.ListTransactions(opts...), nil } func (wm *Manager) UpdatePassword(walletName, oldPassword, newPassword string) error { wlt, ok := wm.wallets[walletName] if !ok { return ErrWalletNotLoaded } return wlt.UpdatePassword(oldPassword, newPassword) } ================================================ FILE: wallet/manager/manager_mock.go ================================================ // Code generated by MockGen. DO NOT EDIT. // Source: wallet/manager/interface.go // // Generated by this command: // // mockgen -source=wallet/manager/interface.go -destination=wallet/manager/manager_mock.go -package=manager // // Package manager is a generated GoMock package. package manager import ( reflect "reflect" crypto "github.com/pactus-project/pactus/crypto" amount "github.com/pactus-project/pactus/types/amount" tx "github.com/pactus-project/pactus/types/tx" wallet "github.com/pactus-project/pactus/wallet" types "github.com/pactus-project/pactus/wallet/types" gomock "go.uber.org/mock/gomock" ) // MockIManager is a mock of IManager interface. type MockIManager struct { ctrl *gomock.Controller recorder *MockIManagerMockRecorder isgomock struct{} } // MockIManagerMockRecorder is the mock recorder for MockIManager. type MockIManagerMockRecorder struct { mock *MockIManager } // NewMockIManager creates a new mock instance. func NewMockIManager(ctrl *gomock.Controller) *MockIManager { mock := &MockIManager{ctrl: ctrl} mock.recorder = &MockIManagerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIManager) EXPECT() *MockIManagerMockRecorder { return m.recorder } // AddressInfo mocks base method. func (m *MockIManager) AddressInfo(walletName, address string) (*types.AddressInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddressInfo", walletName, address) ret0, _ := ret[0].(*types.AddressInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // AddressInfo indicates an expected call of AddressInfo. func (mr *MockIManagerMockRecorder) AddressInfo(walletName, address any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddressInfo", reflect.TypeOf((*MockIManager)(nil).AddressInfo), walletName, address) } // AddressLabel mocks base method. func (m *MockIManager) AddressLabel(walletName, addr string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddressLabel", walletName, addr) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // AddressLabel indicates an expected call of AddressLabel. func (mr *MockIManagerMockRecorder) AddressLabel(walletName, addr any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddressLabel", reflect.TypeOf((*MockIManager)(nil).AddressLabel), walletName, addr) } // Balance mocks base method. func (m *MockIManager) Balance(walletName, addr string) (amount.Amount, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Balance", walletName, addr) ret0, _ := ret[0].(amount.Amount) ret1, _ := ret[1].(error) return ret0, ret1 } // Balance indicates an expected call of Balance. func (mr *MockIManagerMockRecorder) Balance(walletName, addr any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Balance", reflect.TypeOf((*MockIManager)(nil).Balance), walletName, addr) } // BroadcastTransaction mocks base method. func (m *MockIManager) BroadcastTransaction(walletName string, trx *tx.Tx) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BroadcastTransaction", walletName, trx) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // BroadcastTransaction indicates an expected call of BroadcastTransaction. func (mr *MockIManagerMockRecorder) BroadcastTransaction(walletName, trx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastTransaction", reflect.TypeOf((*MockIManager)(nil).BroadcastTransaction), walletName, trx) } // CreateWallet mocks base method. func (m *MockIManager) CreateWallet(walletName, password string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateWallet", walletName, password) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // CreateWallet indicates an expected call of CreateWallet. func (mr *MockIManagerMockRecorder) CreateWallet(walletName, password any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateWallet", reflect.TypeOf((*MockIManager)(nil).CreateWallet), walletName, password) } // GetValidatorAddress mocks base method. func (m *MockIManager) GetValidatorAddress(publicKey string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetValidatorAddress", publicKey) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetValidatorAddress indicates an expected call of GetValidatorAddress. func (mr *MockIManagerMockRecorder) GetValidatorAddress(publicKey any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidatorAddress", reflect.TypeOf((*MockIManager)(nil).GetValidatorAddress), publicKey) } // ListAddresses mocks base method. func (m *MockIManager) ListAddresses(walletName string, opts ...wallet.ListAddressOption) ([]types.AddressInfo, error) { m.ctrl.T.Helper() varargs := []any{walletName} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "ListAddresses", varargs...) ret0, _ := ret[0].([]types.AddressInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // ListAddresses indicates an expected call of ListAddresses. func (mr *MockIManagerMockRecorder) ListAddresses(walletName any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListAddresses", reflect.TypeOf((*MockIManager)(nil).ListAddresses), varargs...) } // ListTransactions mocks base method. func (m *MockIManager) ListTransactions(walletName string, opts ...wallet.ListTransactionsOption) ([]*types.TransactionInfo, error) { m.ctrl.T.Helper() varargs := []any{walletName} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "ListTransactions", varargs...) ret0, _ := ret[0].([]*types.TransactionInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // ListTransactions indicates an expected call of ListTransactions. func (mr *MockIManagerMockRecorder) ListTransactions(walletName any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTransactions", reflect.TypeOf((*MockIManager)(nil).ListTransactions), varargs...) } // ListWallets mocks base method. func (m *MockIManager) ListWallets() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListWallets") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListWallets indicates an expected call of ListWallets. func (mr *MockIManagerMockRecorder) ListWallets() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWallets", reflect.TypeOf((*MockIManager)(nil).ListWallets)) } // MakeBondTx mocks base method. func (m *MockIManager) MakeBondTx(walletName, sender, receiver, publicKey string, amt amount.Amount, opts ...wallet.TxOption) (*tx.Tx, error) { m.ctrl.T.Helper() varargs := []any{walletName, sender, receiver, publicKey, amt} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "MakeBondTx", varargs...) ret0, _ := ret[0].(*tx.Tx) ret1, _ := ret[1].(error) return ret0, ret1 } // MakeBondTx indicates an expected call of MakeBondTx. func (mr *MockIManagerMockRecorder) MakeBondTx(walletName, sender, receiver, publicKey, amt any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName, sender, receiver, publicKey, amt}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeBondTx", reflect.TypeOf((*MockIManager)(nil).MakeBondTx), varargs...) } // MakeTransferTx mocks base method. func (m *MockIManager) MakeTransferTx(walletName, sender, receiver string, amt amount.Amount, opts ...wallet.TxOption) (*tx.Tx, error) { m.ctrl.T.Helper() varargs := []any{walletName, sender, receiver, amt} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "MakeTransferTx", varargs...) ret0, _ := ret[0].(*tx.Tx) ret1, _ := ret[1].(error) return ret0, ret1 } // MakeTransferTx indicates an expected call of MakeTransferTx. func (mr *MockIManagerMockRecorder) MakeTransferTx(walletName, sender, receiver, amt any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName, sender, receiver, amt}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeTransferTx", reflect.TypeOf((*MockIManager)(nil).MakeTransferTx), varargs...) } // MakeUnbondTx mocks base method. func (m *MockIManager) MakeUnbondTx(walletName, validator string, opts ...wallet.TxOption) (*tx.Tx, error) { m.ctrl.T.Helper() varargs := []any{walletName, validator} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "MakeUnbondTx", varargs...) ret0, _ := ret[0].(*tx.Tx) ret1, _ := ret[1].(error) return ret0, ret1 } // MakeUnbondTx indicates an expected call of MakeUnbondTx. func (mr *MockIManagerMockRecorder) MakeUnbondTx(walletName, validator any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName, validator}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeUnbondTx", reflect.TypeOf((*MockIManager)(nil).MakeUnbondTx), varargs...) } // MakeWithdrawTx mocks base method. func (m *MockIManager) MakeWithdrawTx(walletName, sender, receiver string, amt amount.Amount, opts ...wallet.TxOption) (*tx.Tx, error) { m.ctrl.T.Helper() varargs := []any{walletName, sender, receiver, amt} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "MakeWithdrawTx", varargs...) ret0, _ := ret[0].(*tx.Tx) ret1, _ := ret[1].(error) return ret0, ret1 } // MakeWithdrawTx indicates an expected call of MakeWithdrawTx. func (mr *MockIManagerMockRecorder) MakeWithdrawTx(walletName, sender, receiver, amt any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName, sender, receiver, amt}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeWithdrawTx", reflect.TypeOf((*MockIManager)(nil).MakeWithdrawTx), varargs...) } // Mnemonic mocks base method. func (m *MockIManager) Mnemonic(walletName, password string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Mnemonic", walletName, password) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // Mnemonic indicates an expected call of Mnemonic. func (mr *MockIManagerMockRecorder) Mnemonic(walletName, password any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Mnemonic", reflect.TypeOf((*MockIManager)(nil).Mnemonic), walletName, password) } // NewAddress mocks base method. func (m *MockIManager) NewAddress(walletName string, addressType crypto.AddressType, label string, opts ...wallet.NewAddressOption) (*types.AddressInfo, error) { m.ctrl.T.Helper() varargs := []any{walletName, addressType, label} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "NewAddress", varargs...) ret0, _ := ret[0].(*types.AddressInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // NewAddress indicates an expected call of NewAddress. func (mr *MockIManagerMockRecorder) NewAddress(walletName, addressType, label any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{walletName, addressType, label}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAddress", reflect.TypeOf((*MockIManager)(nil).NewAddress), varargs...) } // PrivateKey mocks base method. func (m *MockIManager) PrivateKey(walletName, password, addr string) (crypto.PrivateKey, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PrivateKey", walletName, password, addr) ret0, _ := ret[0].(crypto.PrivateKey) ret1, _ := ret[1].(error) return ret0, ret1 } // PrivateKey indicates an expected call of PrivateKey. func (mr *MockIManagerMockRecorder) PrivateKey(walletName, password, addr any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrivateKey", reflect.TypeOf((*MockIManager)(nil).PrivateKey), walletName, password, addr) } // RestoreWallet mocks base method. func (m *MockIManager) RestoreWallet(walletName, mnemonic, password string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RestoreWallet", walletName, mnemonic, password) ret0, _ := ret[0].(error) return ret0 } // RestoreWallet indicates an expected call of RestoreWallet. func (mr *MockIManagerMockRecorder) RestoreWallet(walletName, mnemonic, password any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RestoreWallet", reflect.TypeOf((*MockIManager)(nil).RestoreWallet), walletName, mnemonic, password) } // SetAddressLabel mocks base method. func (m *MockIManager) SetAddressLabel(walletName, addr, label string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetAddressLabel", walletName, addr, label) ret0, _ := ret[0].(error) return ret0 } // SetAddressLabel indicates an expected call of SetAddressLabel. func (mr *MockIManagerMockRecorder) SetAddressLabel(walletName, addr, label any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAddressLabel", reflect.TypeOf((*MockIManager)(nil).SetAddressLabel), walletName, addr, label) } // SetDefaultFee mocks base method. func (m *MockIManager) SetDefaultFee(walletName string, fee amount.Amount) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetDefaultFee", walletName, fee) ret0, _ := ret[0].(error) return ret0 } // SetDefaultFee indicates an expected call of SetDefaultFee. func (mr *MockIManagerMockRecorder) SetDefaultFee(walletName, fee any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDefaultFee", reflect.TypeOf((*MockIManager)(nil).SetDefaultFee), walletName, fee) } // SignMessage mocks base method. func (m *MockIManager) SignMessage(walletName, password, addr, msg string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SignMessage", walletName, password, addr, msg) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // SignMessage indicates an expected call of SignMessage. func (mr *MockIManagerMockRecorder) SignMessage(walletName, password, addr, msg any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SignMessage", reflect.TypeOf((*MockIManager)(nil).SignMessage), walletName, password, addr, msg) } // SignRawTransaction mocks base method. func (m *MockIManager) SignRawTransaction(walletName, password string, rawTx []byte) ([]byte, []byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SignRawTransaction", walletName, password, rawTx) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].([]byte) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // SignRawTransaction indicates an expected call of SignRawTransaction. func (mr *MockIManagerMockRecorder) SignRawTransaction(walletName, password, rawTx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SignRawTransaction", reflect.TypeOf((*MockIManager)(nil).SignRawTransaction), walletName, password, rawTx) } // SignTransaction mocks base method. func (m *MockIManager) SignTransaction(walletName, password string, trx *tx.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SignTransaction", walletName, password, trx) ret0, _ := ret[0].(error) return ret0 } // SignTransaction indicates an expected call of SignTransaction. func (mr *MockIManagerMockRecorder) SignTransaction(walletName, password, trx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SignTransaction", reflect.TypeOf((*MockIManager)(nil).SignTransaction), walletName, password, trx) } // Stake mocks base method. func (m *MockIManager) Stake(walletName, addr string) (amount.Amount, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Stake", walletName, addr) ret0, _ := ret[0].(amount.Amount) ret1, _ := ret[1].(error) return ret0, ret1 } // Stake indicates an expected call of Stake. func (mr *MockIManagerMockRecorder) Stake(walletName, addr any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stake", reflect.TypeOf((*MockIManager)(nil).Stake), walletName, addr) } // Start mocks base method. func (m *MockIManager) Start() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Start") ret0, _ := ret[0].(error) return ret0 } // Start indicates an expected call of Start. func (mr *MockIManagerMockRecorder) Start() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockIManager)(nil).Start)) } // Stop mocks base method. func (m *MockIManager) Stop() { m.ctrl.T.Helper() m.ctrl.Call(m, "Stop") } // Stop indicates an expected call of Stop. func (mr *MockIManagerMockRecorder) Stop() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockIManager)(nil).Stop)) } // TotalBalance mocks base method. func (m *MockIManager) TotalBalance(walletName string) (amount.Amount, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TotalBalance", walletName) ret0, _ := ret[0].(amount.Amount) ret1, _ := ret[1].(error) return ret0, ret1 } // TotalBalance indicates an expected call of TotalBalance. func (mr *MockIManagerMockRecorder) TotalBalance(walletName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TotalBalance", reflect.TypeOf((*MockIManager)(nil).TotalBalance), walletName) } // TotalStake mocks base method. func (m *MockIManager) TotalStake(walletName string) (amount.Amount, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TotalStake", walletName) ret0, _ := ret[0].(amount.Amount) ret1, _ := ret[1].(error) return ret0, ret1 } // TotalStake indicates an expected call of TotalStake. func (mr *MockIManagerMockRecorder) TotalStake(walletName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TotalStake", reflect.TypeOf((*MockIManager)(nil).TotalStake), walletName) } // UpdatePassword mocks base method. func (m *MockIManager) UpdatePassword(walletName, oldPassword, newPassword string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdatePassword", walletName, oldPassword, newPassword) ret0, _ := ret[0].(error) return ret0 } // UpdatePassword indicates an expected call of UpdatePassword. func (mr *MockIManagerMockRecorder) UpdatePassword(walletName, oldPassword, newPassword any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdatePassword", reflect.TypeOf((*MockIManager)(nil).UpdatePassword), walletName, oldPassword, newPassword) } // WalletInfo mocks base method. func (m *MockIManager) WalletInfo(walletName string) (*types.WalletInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WalletInfo", walletName) ret0, _ := ret[0].(*types.WalletInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // WalletInfo indicates an expected call of WalletInfo. func (mr *MockIManagerMockRecorder) WalletInfo(walletName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WalletInfo", reflect.TypeOf((*MockIManager)(nil).WalletInfo), walletName) } ================================================ FILE: wallet/manager/manager_test.go ================================================ package manager_test ================================================ FILE: wallet/provider/interface.go ================================================ package provider import ( "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" ) type IBlockchainProvider interface { LastBlockHeight() (types.Height, error) GetAccount(addrStr string) (*account.Account, error) GetValidator(addrStr string) (*validator.Validator, error) GetTransaction(txID string) (*tx.Tx, types.Height, error) CheckTransaction(data []byte) error SendTx(trx *tx.Tx) (string, error) Close() error } ================================================ FILE: wallet/provider/local/local.go ================================================ package local import ( "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/wallet/provider" ) var _ provider.IBlockchainProvider = (*LocalBlockchainProvider)(nil) type LocalBlockchainProvider struct { state state.Facade } func NewLocalBlockchainProvider(state state.Facade) *LocalBlockchainProvider { return &LocalBlockchainProvider{ state: state, } } func (p *LocalBlockchainProvider) LastBlockHeight() (types.Height, error) { return p.state.LastBlockHeight(), nil } func (p *LocalBlockchainProvider) GetAccount(addrStr string) (*account.Account, error) { addr, err := crypto.AddressFromString(addrStr) if err != nil { return nil, err } return p.state.AccountByAddress(addr) } func (p *LocalBlockchainProvider) GetValidator(addrStr string) (*validator.Validator, error) { addr, err := crypto.AddressFromString(addrStr) if err != nil { return nil, err } return p.state.ValidatorByAddress(addr) } func (p *LocalBlockchainProvider) GetTransaction(txID string) (*tx.Tx, types.Height, error) { idHash, err := hash.FromString(txID) if err != nil { return nil, 0, err } cTrx, err := p.state.CommittedTx(idHash) if err != nil { return nil, 0, err } trx, err := cTrx.ToTx() if err != nil { return nil, 0, err } return trx, cTrx.Height, nil } func (p *LocalBlockchainProvider) SendTx(trx *tx.Tx) (string, error) { if err := p.state.AddPendingTxAndBroadcast(trx); err != nil { return "", err } return trx.ID().String(), nil } func (*LocalBlockchainProvider) Close() error { return nil } func (p *LocalBlockchainProvider) CheckTransaction(data []byte) error { trx, err := tx.FromBytes(data) if err != nil { return err } return p.state.CheckTransaction(trx) } ================================================ FILE: wallet/provider/offline/offline.go ================================================ package offline import ( "errors" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/wallet/provider" ) var _ provider.IBlockchainProvider = (*OfflineBlockchainProvider)(nil) // ErrOffline describes an error in which the wallet is offline. var ErrOffline = errors.New("wallet is in offline mode") type OfflineBlockchainProvider struct{} func NewOfflineBlockchainProvider() *OfflineBlockchainProvider { return &OfflineBlockchainProvider{} } func (*OfflineBlockchainProvider) LastBlockHeight() (types.Height, error) { return 0, ErrOffline } func (*OfflineBlockchainProvider) GetAccount(string) (*account.Account, error) { return nil, ErrOffline } func (*OfflineBlockchainProvider) GetValidator(string) (*validator.Validator, error) { return nil, ErrOffline } func (*OfflineBlockchainProvider) GetTransaction(string) (*tx.Tx, types.Height, error) { return nil, 0, ErrOffline } func (*OfflineBlockchainProvider) SendTx(*tx.Tx) (string, error) { return "", ErrOffline } func (*OfflineBlockchainProvider) Close() error { return nil } func (*OfflineBlockchainProvider) CheckTransaction([]byte) error { return ErrOffline } ================================================ FILE: wallet/provider/provider_mock.go ================================================ // Code generated by MockGen. DO NOT EDIT. // Source: wallet/provider/interface.go // // Generated by this command: // // mockgen -source=wallet/provider/interface.go -destination=wallet/provider/provider_mock.go -package=provider // // Package provider is a generated GoMock package. package provider import ( reflect "reflect" types "github.com/pactus-project/pactus/types" account "github.com/pactus-project/pactus/types/account" tx "github.com/pactus-project/pactus/types/tx" validator "github.com/pactus-project/pactus/types/validator" gomock "go.uber.org/mock/gomock" ) // MockIBlockchainProvider is a mock of IBlockchainProvider interface. type MockIBlockchainProvider struct { ctrl *gomock.Controller recorder *MockIBlockchainProviderMockRecorder isgomock struct{} } // MockIBlockchainProviderMockRecorder is the mock recorder for MockIBlockchainProvider. type MockIBlockchainProviderMockRecorder struct { mock *MockIBlockchainProvider } // NewMockIBlockchainProvider creates a new mock instance. func NewMockIBlockchainProvider(ctrl *gomock.Controller) *MockIBlockchainProvider { mock := &MockIBlockchainProvider{ctrl: ctrl} mock.recorder = &MockIBlockchainProviderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIBlockchainProvider) EXPECT() *MockIBlockchainProviderMockRecorder { return m.recorder } // CheckTransaction mocks base method. func (m *MockIBlockchainProvider) CheckTransaction(data []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CheckTransaction", data) ret0, _ := ret[0].(error) return ret0 } // CheckTransaction indicates an expected call of CheckTransaction. func (mr *MockIBlockchainProviderMockRecorder) CheckTransaction(data any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckTransaction", reflect.TypeOf((*MockIBlockchainProvider)(nil).CheckTransaction), data) } // Close mocks base method. func (m *MockIBlockchainProvider) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) return ret0 } // Close indicates an expected call of Close. func (mr *MockIBlockchainProviderMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockIBlockchainProvider)(nil).Close)) } // GetAccount mocks base method. func (m *MockIBlockchainProvider) GetAccount(addrStr string) (*account.Account, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", addrStr) ret0, _ := ret[0].(*account.Account) ret1, _ := ret[1].(error) return ret0, ret1 } // GetAccount indicates an expected call of GetAccount. func (mr *MockIBlockchainProviderMockRecorder) GetAccount(addrStr any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockIBlockchainProvider)(nil).GetAccount), addrStr) } // GetTransaction mocks base method. func (m *MockIBlockchainProvider) GetTransaction(txID string) (*tx.Tx, types.Height, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTransaction", txID) ret0, _ := ret[0].(*tx.Tx) ret1, _ := ret[1].(types.Height) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // GetTransaction indicates an expected call of GetTransaction. func (mr *MockIBlockchainProviderMockRecorder) GetTransaction(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTransaction", reflect.TypeOf((*MockIBlockchainProvider)(nil).GetTransaction), txID) } // GetValidator mocks base method. func (m *MockIBlockchainProvider) GetValidator(addrStr string) (*validator.Validator, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetValidator", addrStr) ret0, _ := ret[0].(*validator.Validator) ret1, _ := ret[1].(error) return ret0, ret1 } // GetValidator indicates an expected call of GetValidator. func (mr *MockIBlockchainProviderMockRecorder) GetValidator(addrStr any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidator", reflect.TypeOf((*MockIBlockchainProvider)(nil).GetValidator), addrStr) } // LastBlockHeight mocks base method. func (m *MockIBlockchainProvider) LastBlockHeight() (types.Height, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LastBlockHeight") ret0, _ := ret[0].(types.Height) ret1, _ := ret[1].(error) return ret0, ret1 } // LastBlockHeight indicates an expected call of LastBlockHeight. func (mr *MockIBlockchainProviderMockRecorder) LastBlockHeight() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastBlockHeight", reflect.TypeOf((*MockIBlockchainProvider)(nil).LastBlockHeight)) } // SendTx mocks base method. func (m *MockIBlockchainProvider) SendTx(trx *tx.Tx) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendTx", trx) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // SendTx indicates an expected call of SendTx. func (mr *MockIBlockchainProviderMockRecorder) SendTx(trx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendTx", reflect.TypeOf((*MockIBlockchainProvider)(nil).SendTx), trx) } ================================================ FILE: wallet/provider/remote/errors.go ================================================ package remote import "errors" // ErrInvalidNetwork describes an error in which the network is invalid. var ErrInvalidNetwork = errors.New("invalid network") ================================================ FILE: wallet/provider/remote/remote.go ================================================ package remote import ( "context" "encoding/hex" "encoding/json" "errors" "net" "time" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet/provider" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) var _ provider.IBlockchainProvider = (*RemoteBlockchainProvider)(nil) type remoteProviderConfig struct { timeout time.Duration servers []string } var defaultOpenWalletConfig = remoteProviderConfig{ timeout: 5 * time.Second, servers: nil, } type RemoteProviderOption func(*remoteProviderConfig) func WithTimeout(timeout time.Duration) RemoteProviderOption { return func(cfg *remoteProviderConfig) { cfg.timeout = timeout } } func WithCustomServers(servers []string) RemoteProviderOption { return func(cfg *remoteProviderConfig) { cfg.servers = servers } } // RemoteBlockchainProvider is a blockchain provider that connects to a remote gRPC server. // It randomly selects a server from a predefined list. type RemoteBlockchainProvider struct { ctx context.Context servers []string conn *grpc.ClientConn timeout time.Duration blockchainClient pactus.BlockchainClient transactionClient pactus.TransactionClient } func NewRemoteBlockchainProvider(ctx context.Context, network genesis.ChainType, opts ...RemoteProviderOption, ) (*RemoteBlockchainProvider, error) { cfg := defaultOpenWalletConfig for _, opt := range opts { opt(&cfg) } if cfg.servers == nil { var servers []string serversData := map[string][]ServerInfo{} err := json.Unmarshal(serversJSON, &serversData) if err != nil { return nil, err } switch network { case genesis.Mainnet: for _, srv := range serversData["mainnet"] { servers = append(servers, srv.Address) } case genesis.Testnet: for _, srv := range serversData["testnet"] { servers = append(servers, srv.Address) } case genesis.Localnet: servers = []string{"localhost:50052"} default: return nil, ErrInvalidNetwork } util.Shuffle(servers) cfg.servers = servers } return &RemoteBlockchainProvider{ ctx: ctx, servers: cfg.servers, timeout: cfg.timeout, }, nil } func (p *RemoteBlockchainProvider) connect() error { if p.conn != nil { return nil } for _, server := range p.servers { conn, err := grpc.NewClient(server, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, address string) (net.Conn, error) { return util.NetworkDialTimeout(ctx, "tcp", address, p.timeout) })) if err != nil { continue } blockchainClient := pactus.NewBlockchainClient(conn) transactionClient := pactus.NewTransactionClient(conn) // Check if client is responding // TODO: Use Ping API in version 1.11.0 _, err = blockchainClient.GetBlockchainInfo(p.ctx, &pactus.GetBlockchainInfoRequest{}) if err != nil { _ = conn.Close() continue } p.conn = conn p.blockchainClient = blockchainClient p.transactionClient = transactionClient return nil } return errors.New("unable to connect to the servers") } func (p *RemoteBlockchainProvider) Close() error { if p.conn != nil { return p.conn.Close() } return nil } func (p *RemoteBlockchainProvider) LastBlockHeight() (types.Height, error) { if err := p.connect(); err != nil { return 0, err } ctx, cancel := context.WithTimeout(p.ctx, p.timeout) defer cancel() res, err := p.blockchainClient.GetBlockchainInfo(ctx, &pactus.GetBlockchainInfoRequest{}) if err != nil { return 0, err } return types.Height(res.LastBlockHeight), nil } func (p *RemoteBlockchainProvider) GetAccount(addrStr string) (*account.Account, error) { if err := p.connect(); err != nil { return nil, err } ctx, cancel := context.WithTimeout(p.ctx, p.timeout) defer cancel() res, err := p.blockchainClient.GetAccount(ctx, &pactus.GetAccountRequest{Address: addrStr}) if err != nil { return nil, err } data, err := hex.DecodeString(res.Account.Data) if err != nil { return nil, err } return account.FromBytes(data) } func (p *RemoteBlockchainProvider) GetValidator(addrStr string) (*validator.Validator, error) { if err := p.connect(); err != nil { return nil, err } ctx, cancel := context.WithTimeout(p.ctx, p.timeout) defer cancel() res, err := p.blockchainClient.GetValidator(ctx, &pactus.GetValidatorRequest{Address: addrStr}) if err != nil { return nil, err } data, err := hex.DecodeString(res.Validator.Data) if err != nil { return nil, err } return validator.FromBytes(data) } func (p *RemoteBlockchainProvider) SendTx(trx *tx.Tx) (string, error) { if err := p.connect(); err != nil { return "", err } data, err := trx.Bytes() if err != nil { return "", err } ctx, cancel := context.WithTimeout(p.ctx, p.timeout) defer cancel() res, err := p.transactionClient.BroadcastTransaction(ctx, &pactus.BroadcastTransactionRequest{SignedRawTransaction: hex.EncodeToString(data)}) if err != nil { return "", err } return res.Id, nil } func (p *RemoteBlockchainProvider) GetTransaction(txID string) (*tx.Tx, types.Height, error) { if err := p.connect(); err != nil { return nil, 0, err } ctx, cancel := context.WithTimeout(p.ctx, p.timeout) defer cancel() res, err := p.transactionClient.GetTransaction(ctx, &pactus.GetTransactionRequest{ Id: txID, Verbosity: pactus.TransactionVerbosity_TRANSACTION_VERBOSITY_DATA, }) if err != nil { return nil, 0, err } data, err := hex.DecodeString(res.Transaction.Data) if err != nil { return nil, 0, err } tx, err := tx.FromBytes(data) if err != nil { return nil, 0, err } return tx, types.Height(res.BlockHeight), nil } func (p *RemoteBlockchainProvider) CheckTransaction(data []byte) error { if err := p.connect(); err != nil { return err } ctx, cancel := context.WithTimeout(p.ctx, p.timeout) defer cancel() _, err := p.transactionClient.CheckTransaction(ctx, &pactus.CheckTransactionRequest{RawTransaction: hex.EncodeToString(data)}) if err != nil { return err } return nil } ================================================ FILE: wallet/provider/remote/servers.go ================================================ package remote import _ "embed" //go:embed servers.json var serversJSON []byte type ServerInfo struct { Name string `json:"name"` Email string `json:"email"` Website string `json:"website"` Address string `json:"address"` } ================================================ FILE: wallet/provider/remote/servers.json ================================================ { "mainnet": [ { "name": "Pactus Bootstrap 1", "email": "info@pactus.org", "website": "https://pactus.org", "address": "bootstrap1.pactus.org:50051" }, { "name": "Pactus Bootstrap 2", "email": "info@pactus.org", "website": "https://pactus.org", "address": "bootstrap2.pactus.org:50051" }, { "name": "Pactus Bootstrap 3", "email": "info@pactus.org", "website": "https://pactus.org", "address": "bootstrap3.pactus.org:50051" }, { "name": "Pactus Bootstrap 4", "email": "info@pactus.org", "website": "https://pactus.org", "address": "bootstrap4.pactus.org:50051" } ], "testnet": [ { "address": "localhost:50052" }, { "address": "testnet1.pactus.org:50052" }, { "address": "testnet2.pactus.org:50052" }, { "address": "testnet3.pactus.org:50052" }, { "address": "testnet4.pactus.org:50052" } ] } ================================================ FILE: wallet/storage/errors.go ================================================ package storage import "errors" var ( // ErrNotFound indicates that a requested resource was not found. ErrNotFound = errors.New("resource not found") // ErrDuplicateEntry indicates that a duplicate entry was attempted to be inserted. ErrDuplicateEntry = errors.New("duplicate entry") // ErrInvalidInput indicates that the input provided is invalid. ErrInvalidInput = errors.New("invalid input") ) ================================================ FILE: wallet/storage/interface.go ================================================ package storage import ( "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" wtypes "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" ) // QueryParams specifies filters for querying stored transactions. type QueryParams struct { Address string Direction wtypes.TxDirection Count int Skip int } type IStorage interface { WalletInfo() *wtypes.WalletInfo Vault() *vault.Vault UpdateVault(vault *vault.Vault) error SetDefaultFee(fee amount.Amount) error AllAddresses() []wtypes.AddressInfo AddressInfo(address string) (*wtypes.AddressInfo, error) HasAddress(address string) bool AddressCount() int InsertAddress(info *wtypes.AddressInfo) error UpdateAddress(info *wtypes.AddressInfo) error InsertTransaction(info *wtypes.TransactionInfo) error GetPendingTransactions() (map[string]*wtypes.TransactionInfo, error) UpdateTransactionStatus(no int64, status wtypes.TransactionStatus, blockHeight types.Height) error GetTransaction(no int64) (*wtypes.TransactionInfo, error) HasTransaction(txID string) bool QueryTransactions(params QueryParams) ([]*wtypes.TransactionInfo, error) Close() error Clone(path string) (IStorage, error) IsLegacy() bool } ================================================ FILE: wallet/storage/jsonstorage/errors.go ================================================ package jsonstorage import ( "errors" "fmt" ) var ErrUnsupported = errors.New("operation not supported") // CRCNotMatchError describes an error in which the wallet CRC is not matched. type CRCNotMatchError struct { Expected uint32 Got uint32 } func (e CRCNotMatchError) Error() string { return fmt.Sprintf("crc not matched, expected: %d, got: %d", e.Expected, e.Got) } // UnsupportedVersionError indicates the wallet version is incompatible with the software's supported version. type UnsupportedVersionError struct { WalletVersion int SupportedVersion int } func (e UnsupportedVersionError) Error() string { return fmt.Sprintf("wallet version %d is not supported, latest supported version is %d", e.WalletVersion, e.SupportedVersion) } ================================================ FILE: wallet/storage/jsonstorage/storage.go ================================================ package jsonstorage import ( "encoding/json" "github.com/google/uuid" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet/storage" wtypes "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" ) type Storage struct { path string store store } func Create(path string, network genesis.ChainType, vault *vault.Vault) (*Storage, error) { store := store{ Version: VersionLatest, UUID: uuid.New(), CreatedAt: util.RoundNow(1), Network: network, DefaultFee: amount.Amount(10_000_000), Vault: *vault, Addresses: make(map[string]wtypes.AddressInfo), } if err := store.Save(path); err != nil { return nil, err } return Open(path) } func Open(path string) (*Storage, error) { data, err := util.ReadFile(path) if err != nil { return nil, err } var store store if err := json.Unmarshal(data, &store); err != nil { return nil, err } if err := store.ValidateCRC(); err != nil { return nil, err } return &Storage{ path: path, store: store, }, nil } func (*Storage) Close() error { return nil } func (s *Storage) save() error { return s.store.Save(s.path) } func (s *Storage) WalletInfo() *wtypes.WalletInfo { return &wtypes.WalletInfo{ Path: s.path, Driver: "JSON (legacy)", Version: s.store.Version, Network: s.store.Network, DefaultFee: s.store.DefaultFee, UUID: s.store.UUID.String(), Encrypted: s.store.Vault.IsEncrypted(), Neutered: s.store.Vault.IsNeutered(), CreatedAt: s.store.CreatedAt, } } func (s *Storage) Vault() *vault.Vault { return &s.store.Vault } func (s *Storage) UpdateVault(vault *vault.Vault) error { s.store.Vault = *vault return s.save() } func (s *Storage) SetDefaultFee(fee amount.Amount) error { s.store.DefaultFee = fee return s.save() } func (s *Storage) AllAddresses() []wtypes.AddressInfo { addrs := make([]wtypes.AddressInfo, 0, len(s.store.Addresses)) for _, info := range s.store.Addresses { addrs = append(addrs, info) } return addrs } func (s *Storage) AddressInfo(address string) (*wtypes.AddressInfo, error) { info, exists := s.store.Addresses[address] if !exists { return nil, storage.ErrNotFound } return &info, nil } func (s *Storage) InsertAddress(info *wtypes.AddressInfo) error { s.store.Addresses[info.Address] = *info return s.save() } func (s *Storage) HasAddress(address string) bool { _, exists := s.store.Addresses[address] return exists } func (s *Storage) AddressCount() int { return len(s.store.Addresses) } func (s *Storage) UpdateAddress(info *wtypes.AddressInfo) error { s.store.Addresses[info.Address] = *info return s.save() } func (*Storage) InsertTransaction(_ *wtypes.TransactionInfo) error { return ErrUnsupported } func (*Storage) UpdateTransactionStatus(_ int64, _ wtypes.TransactionStatus, _ types.Height) error { return ErrUnsupported } func (*Storage) HasTransaction(_ string) bool { return false } func (*Storage) GetTransaction(_ int64) (*wtypes.TransactionInfo, error) { return nil, ErrUnsupported } func (*Storage) GetPendingTransactions() (map[string]*wtypes.TransactionInfo, error) { return nil, ErrUnsupported } func (*Storage) QueryTransactions(_ storage.QueryParams) ([]*wtypes.TransactionInfo, error) { return nil, ErrUnsupported } func (s *Storage) Clone(path string) (storage.IStorage, error) { cloned := store{ Version: s.store.Version, UUID: uuid.New(), CreatedAt: util.RoundNow(1), Network: s.store.Network, DefaultFee: s.store.DefaultFee, Vault: s.store.Vault, Addresses: s.store.Addresses, } strg := &Storage{ path: path, store: cloned, } err := strg.save() if err != nil { return nil, err } return strg, nil } func (*Storage) IsLegacy() bool { return true } ================================================ FILE: wallet/storage/jsonstorage/storage_test.go ================================================ package jsonstorage import ( "testing" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet/vault" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) //nolint:dupword // duplicated seed phrase words var testMnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon cactus" func TestCreate(t *testing.T) { tempPath := util.TempFilePath() vlt, err := vault.CreateVaultFromMnemonic(testMnemonic, 21888) require.NoError(t, err) strg, err := Create(tempPath, genesis.Mainnet, vlt) require.NoError(t, err) assert.Equal(t, VersionLatest, strg.WalletInfo().Version) assert.Equal(t, genesis.Mainnet, strg.WalletInfo().Network) assert.Equal(t, vlt, strg.Vault()) } func TestOpenNeuterWallet(t *testing.T) { data, err := util.ReadFile("./testdata/neuter_wallet") require.NoError(t, err) tempPath := util.TempFilePath() err = util.WriteFile(tempPath, data) require.NoError(t, err) strg, err := Open(tempPath) require.NoError(t, err) assert.False(t, strg.Vault().IsNeutered()) } ================================================ FILE: wallet/storage/jsonstorage/store.go ================================================ package jsonstorage import ( "encoding/json" "hash/crc32" "time" "github.com/google/uuid" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" ) type store struct { Version int `json:"version"` UUID uuid.UUID `json:"uuid"` CreatedAt time.Time `json:"created_at"` Network genesis.ChainType `json:"network"` VaultCRC uint32 `json:"crc"` DefaultFee amount.Amount `json:"default_fee"` Vault vault.Vault `json:"vault"` Addresses map[string]types.AddressInfo `json:"addresses"` } func (s *store) Save(path string) error { s.VaultCRC = s.calcVaultCRC() data, err := json.MarshalIndent(s, " ", " ") if err != nil { return err } return util.WriteFile(path, data) } func (s *store) ValidateCRC() error { crc := s.calcVaultCRC() if s.VaultCRC != crc { return CRCNotMatchError{ Expected: crc, Got: s.VaultCRC, } } return nil } func (s *store) calcVaultCRC() uint32 { d, err := json.Marshal(s.Vault) if err != nil { return 0 } return crc32.ChecksumIEEE(d) } ================================================ FILE: wallet/storage/jsonstorage/testdata/neuter_wallet ================================================ { "version": 5, "uuid": "44156117-268a-49f0-a906-400659b7a051", "created_at": "2024-08-27T16:45:08Z", "network": 0, "crc": 2985143697, "default_fee": 20000000, "vault": { "type": 1, "coin_type": 21888, "encrypter": null, "key_store": "", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 0, "next_validator_index": 0 } } }, "addresses": { }, "history": { "transactions": null, "activities": null, "pendings": null } } ================================================ FILE: wallet/storage/jsonstorage/testdata/testnet_wallet ================================================ { "version": 1, "uuid": "a72f03c0-2f77-4401-afac-16d2ccbf129f", "created_at": "2025-12-24T03:07:00Z", "network": 1, "crc": 885152871, "vault": { "type": 1, "coin_type": 21777, "addresses": { "tpc1zft4nhnr3r7467kzkyay9sm7kydrs7unypgwqtw": { "address": "tpc1zft4nhnr3r7467kzkyay9sm7kydrs7unypgwqtw", "public_key": "tpublic1pnyyphf30dpufuqprmjjrqn2nwzxgpyz7l5awg5ld7qwq06xvfe9vd8zwtrvks9t93jsu09chatl0qqn2ecgxqjst7twl66209hj60m3x7dhs7cv5q3vzppl7h4w4yvwcg5ndqhv5djv0yewahx8ercn2ycx8zask", "label": "Tesnte Address 1", "path": "m/12381'/21777'/2'/0" } }, "encrypter": {}, "key_store": "{\"master_node\":{\"seed\":\"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon cactus\"},\"imported_keys\":[]}", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 1, "next_validator_index": 1 } } }, "history": { "transactions": null, "activities": null, "pendings": null } } ================================================ FILE: wallet/storage/jsonstorage/testdata/unsupported_wallet ================================================ { "version": 6 } ================================================ FILE: wallet/storage/jsonstorage/testdata/wallet_version_1 ================================================ { "version": 1, "uuid": "44156117-268a-49f0-a906-400659b7a051", "created_at": "2024-08-27T16:45:08Z", "network": 0, "crc": 885152871, "vault": { "type": 1, "coin_type": 21888, "addresses": { "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd": { "address": "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Validator Address", "path": "m/65535'/21888'/1'/0'" }, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns": { "address": "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported BLS Account Address", "path": "m/65535'/21888'/2'/0'" }, "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp": { "address": "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp", "public_key": "", "label": "Validator Address", "path": "m/12381'/21888'/1'/0" }, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf": { "address": "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", "public_key": "", "label": "BLS Account Address", "path": "m/12381'/21888'/2'/0" } }, "encrypter": { "method": "ARGON2ID-AES_256_CTR-MACV1", "params": { "iterations": "1", "memory": "8", "parallelism": "1" } }, "key_store": "/ccHYYuAAwurC8s6ZUFJAcqcwKAedRztvt6QAZ4Wj5xR5j2AwjIMutl4fYNhi4B0Pux39iQTiL5LKSl/Dh73Vn8z5M5b/juHVywYcLshki0jEzio4dakAdw3kYr1b8rTrOSLAHQhbD5RBpQNCck489LDvEzyuRfeIBTCaUj2UTDJqKUOYHFwFjUJVLqDrsTDGkm3BjzmuW5t6rUEV6PvrwH2s8dv7bFz5yHBbVovUhTJnEEK/jgH7OsojW6TH91sz8lDzyjtRGW8ZKr1sHglcfUjSOSN/OY/Pd8+Fnq2l4bMR8ZP", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 1, "next_validator_index": 1 } } }, "history": { "transactions": null, "activities": null, "pendings": null } } ================================================ FILE: wallet/storage/jsonstorage/testdata/wallet_version_2 ================================================ { "version": 2, "uuid": "44156117-268a-49f0-a906-400659b7a051", "created_at": "2024-08-27T16:45:08Z", "network": 0, "crc": 42093467, "vault": { "type": 1, "coin_type": 21888, "addresses": { "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd": { "address": "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Validator Address", "path": "m/65535'/21888'/1'/0'" }, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns": { "address": "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Reward Address", "path": "m/65535'/21888'/2'/0'" }, "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp": { "address": "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp", "public_key": "public1p3mzchmke52mghze9mlsnszvj8jueggxxa9n3va8zhpjzgys82zje93ajrhaye7flzv54g4ydhlauupr5zh4ffsem80xyflzyzkeh79prnkx9jtyxe24kvpkrtfg0f6a6rma8v6x4nsc786s4f35a8ankcueym98h", "label": "Validator Address", "path": "m/12381'/21888'/1'/0" }, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf": { "address": "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", "public_key": "public1p5dwsgfwmacjpuhaxhy0522j87qc5390v56ndh92f7flxge7vt3zfuxlvuwpnk7tdeed4s4l2r5nj5zuyjfh0uzjmvrauf4t5xfvff5cpljvpqqpk7pzhv0hxfhf9gt5896vnllsf89ux8kc7anqlu7nxvvxcclw7", "label": "BLS Account Address", "path": "m/12381'/21888'/2'/0" }, "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3": { "address": "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", "public_key": "public1rd5p573yq3j5wkvnasslqa7ne5vw87qcj5a0wlwxcj2t2xlaca9lstzm8u5", "label": "Ed25519 Account Address", "path": "m/44'/21888'/3'/0'" } }, "encrypter": { "method": "ARGON2ID-AES_256_CTR-MACV1", "params": { "iterations": "1", "memory": "8", "parallelism": "1" } }, "key_store": "/ccHYYuAAwurC8s6ZUFJAcqcwKAedRztvt6QAZ4Wj5xR5j2AwjIMutl4fYNhi4B0Pux39iQTiL5LKSl/Dh73Vn8z5M5b/juHVywYcLshki0jEzio4dakAdw3kYr1b8rTrOSLAHQhbD5RBpQNCck489LDvEzyuRfeIBTCaUj2UTDJqKUOYHFwFjUJVLqDrsTDGkm3BjzmuW5t6rUEV6PvrwH2s8dv7bFz5yHBbVovUhTJnEEK/jgH7OsojW6TH91sz8lDzyjtRGW8ZKr1sHglcfUjSOSN/OY/Pd8+Fnq2l4bMR8ZP", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 1, "next_validator_index": 1 }, "purpose_bip44": { "next_ed25519_index": 1 } } }, "history": { "transactions": null, "activities": null, "pendings": null } } ================================================ FILE: wallet/storage/jsonstorage/testdata/wallet_version_3 ================================================ { "version": 3, "uuid": "44156117-268a-49f0-a906-400659b7a051", "created_at": "2024-08-27T16:45:08Z", "network": 0, "crc": 2777809414, "vault": { "type": 1, "coin_type": 21888, "addresses": { "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd": { "address": "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Validator Address", "path": "m/65535'/21888'/1'/0'" }, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns": { "address": "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Reward Address", "path": "m/65535'/21888'/2'/0'" }, "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp": { "address": "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp", "public_key": "public1p3mzchmke52mghze9mlsnszvj8jueggxxa9n3va8zhpjzgys82zje93ajrhaye7flzv54g4ydhlauupr5zh4ffsem80xyflzyzkeh79prnkx9jtyxe24kvpkrtfg0f6a6rma8v6x4nsc786s4f35a8ankcueym98h", "label": "Validator Address", "path": "m/12381'/21888'/1'/0" }, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf": { "address": "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", "public_key": "public1p5dwsgfwmacjpuhaxhy0522j87qc5390v56ndh92f7flxge7vt3zfuxlvuwpnk7tdeed4s4l2r5nj5zuyjfh0uzjmvrauf4t5xfvff5cpljvpqqpk7pzhv0hxfhf9gt5896vnllsf89ux8kc7anqlu7nxvvxcclw7", "label": "BLS Account Address", "path": "m/12381'/21888'/2'/0" }, "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3": { "address": "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", "public_key": "public1rd5p573yq3j5wkvnasslqa7ne5vw87qcj5a0wlwxcj2t2xlaca9lstzm8u5", "label": "Ed25519 Account Address", "path": "m/44'/21888'/3'/0'" } }, "encrypter": { "method": "ARGON2ID-AES_256_CBC-MACV1", "params": { "iterations": "1", "keylen": "48", "memory": "8", "parallelism": "1" } }, "key_store": "ZQHdkrbVekwBYAAkXqU4m3TbgJsLVx1CkNdaYG035PEJlRIpc7yhc6VqaxMNZmCH1XpNbMQt97+DGX9ar8KqBauCMEgAUBMyeYqL2AMpXZcV5fVVtjHetfBmd6ywqH7/poGVjBoK8daXRz9X2tGB023FELUS93ZaVT29TX5S4f/LM9MoOsjjeXPT6tlSFgvCpeB7oiNZECUYwAFtfH1fbYLBpaPhENPXFWD8IHgC/Dd9tWm3wOCPkI2BnYy1aQZ9qqImcTJTpkM5pp/kvjTU4TmUDzmn6Y+EdWQqOjBphmXUdF8nkqJEKw51vmFGr8cp6TRAOw==", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 1, "next_validator_index": 1 }, "purpose_bip44": { "next_ed25519_index": 1 } } }, "history": { "transactions": null, "activities": null, "pendings": null } } ================================================ FILE: wallet/storage/jsonstorage/testdata/wallet_version_4 ================================================ { "version": 4, "uuid": "44156117-268a-49f0-a906-400659b7a051", "created_at": "2024-08-27T16:45:08Z", "network": 0, "crc": 3937455804, "vault": { "type": 1, "coin_type": 21888, "default_fee": 20000000, "addresses": { "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd": { "address": "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Validator Address", "path": "m/65535'/21888'/1'/0'" }, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns": { "address": "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Reward Address", "path": "m/65535'/21888'/2'/0'" }, "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp": { "address": "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp", "public_key": "public1p3mzchmke52mghze9mlsnszvj8jueggxxa9n3va8zhpjzgys82zje93ajrhaye7flzv54g4ydhlauupr5zh4ffsem80xyflzyzkeh79prnkx9jtyxe24kvpkrtfg0f6a6rma8v6x4nsc786s4f35a8ankcueym98h", "label": "Validator Address", "path": "m/12381'/21888'/1'/0" }, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf": { "address": "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", "public_key": "public1p5dwsgfwmacjpuhaxhy0522j87qc5390v56ndh92f7flxge7vt3zfuxlvuwpnk7tdeed4s4l2r5nj5zuyjfh0uzjmvrauf4t5xfvff5cpljvpqqpk7pzhv0hxfhf9gt5896vnllsf89ux8kc7anqlu7nxvvxcclw7", "label": "BLS Account Address", "path": "m/12381'/21888'/2'/0" }, "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3": { "address": "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", "public_key": "public1rd5p573yq3j5wkvnasslqa7ne5vw87qcj5a0wlwxcj2t2xlaca9lstzm8u5", "label": "Ed25519 Account Address", "path": "m/44'/21888'/3'/0'" } }, "encrypter": { "method": "ARGON2ID-AES_256_CTR-MACV1", "params": { "iterations": "1", "memory": "8", "parallelism": "1", "keylen": "48" } }, "key_store": "aLEdVCpZOJmZZz067JTxWivw/41sWooR+E2iM46WYjskjFTE3VviPzc9SQ6gba5g+8CWWcw1q1YT9x1XAg/QAt2Rd7zR2FKL+ACwCbmZ/H+lLPDBt3nlvOkD2qkxi2rjjLpbAtf2UjKrW2b3+/KxSJGuG5GPIqPvPonqHhSWrF1j0nnKqm+btD1gaeJ5IRLchi27BNorMR4qvETMeV7YjkvZlrEFdNffqpWee+o4+bnr33MwysXm4hZU1c4/zzMIODAyxsMRgbrfTDfdQ19c0yjYmDGAPDpAqNAvMmDL07nGKR2f", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 1, "next_validator_index": 1 }, "purpose_bip44": { "next_ed25519_index": 1 } } }, "history": { "transactions": null, "activities": null, "pendings": null } } ================================================ FILE: wallet/storage/jsonstorage/testdata/wallet_version_5 ================================================ { "version": 5, "uuid": "44156117-268a-49f0-a906-400659b7a051", "created_at": "2024-08-27T16:45:08Z", "network": 0, "crc": 3937455804, "default_fee": 20000000, "vault": { "type": 1, "coin_type": 21888, "encrypter": { "method": "ARGON2ID-AES_256_CTR-MACV1", "params": { "iterations": "1", "memory": "8", "parallelism": "1", "keylen": "48" } }, "key_store": "aLEdVCpZOJmZZz067JTxWivw/41sWooR+E2iM46WYjskjFTE3VviPzc9SQ6gba5g+8CWWcw1q1YT9x1XAg/QAt2Rd7zR2FKL+ACwCbmZ/H+lLPDBt3nlvOkD2qkxi2rjjLpbAtf2UjKrW2b3+/KxSJGuG5GPIqPvPonqHhSWrF1j0nnKqm+btD1gaeJ5IRLchi27BNorMR4qvETMeV7YjkvZlrEFdNffqpWee+o4+bnr33MwysXm4hZU1c4/zzMIODAyxsMRgbrfTDfdQ19c0yjYmDGAPDpAqNAvMmDL07nGKR2f", "purposes": { "purpose_bls": { "xpub_account": "xpublic1pqdwnqqyqsp2spqqpqqqgqgxj6mlduay8ase6hkefwa2lk2esz0gn2yu59tnk3w2tgnlfk5hleuqxpqdlt5q2f207qrwq9gasqscpckjv8hggc57n044gvml7u05cpzu8ra0zq2s3x3mak6xhtzga27tdx5pypnqxhlkf9aedptzcsd8l3q6m7ch6g4lphzsdv20fvc3dsu7mlj8kdy3n5fyllg07wecmpr8y6nsr95zlz", "xpub_validator": "xpublic1pqdwnqqyqsp2spqqzqqqgqgx4n38q9n6qtvgrnx5r8atntrfnj4thwj6my5tx8tfe6ex6p89y7qqxptrfzgmnu62rut65lddgxl5nujdn82tusz5w2wqpjqpdpgplj0zx3gaaz9wv93yqcls6clepehlvhsvdp2ndwphhmag3j3hgsfxxz434hduxvqq4n8njxh4x9mnal2wma4sw5kp6y680tkut62gk6trfjscmsdumc", "next_account_index": 1, "next_validator_index": 1 }, "purpose_bip44": { "next_ed25519_index": 1 } } }, "addresses": { "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd": { "address": "pc1p4xuja689hg2434yhr32clhn97x6afw58qlrcyd", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Validator Address", "path": "m/65535'/21888'/1'/0'" }, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns": { "address": "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", "public_key": "public1p3wmdecume03kehtcaks95jjyem2m7pev0da2yx7t0gws66nkgp7vaah5sdd5gv0s4d34y0nqxch0cqq7fnsy9v46kum7e46gx9dua4sss7ne57m5c776h0e9dt0dw8hv24uushps9arv0zk8dc2xe0k7pgk588tf", "label": "Imported Reward Address", "path": "m/65535'/21888'/2'/0'" }, "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp": { "address": "pc1pjneygutecly9gtandrdt8j36v8g4fl42k4y5xp", "public_key": "public1p3mzchmke52mghze9mlsnszvj8jueggxxa9n3va8zhpjzgys82zje93ajrhaye7flzv54g4ydhlauupr5zh4ffsem80xyflzyzkeh79prnkx9jtyxe24kvpkrtfg0f6a6rma8v6x4nsc786s4f35a8ankcueym98h", "label": "Validator Address", "path": "m/12381'/21888'/1'/0" }, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf": { "address": "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", "public_key": "public1p5dwsgfwmacjpuhaxhy0522j87qc5390v56ndh92f7flxge7vt3zfuxlvuwpnk7tdeed4s4l2r5nj5zuyjfh0uzjmvrauf4t5xfvff5cpljvpqqpk7pzhv0hxfhf9gt5896vnllsf89ux8kc7anqlu7nxvvxcclw7", "label": "BLS Account Address", "path": "m/12381'/21888'/2'/0" }, "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3": { "address": "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", "public_key": "public1rd5p573yq3j5wkvnasslqa7ne5vw87qcj5a0wlwxcj2t2xlaca9lstzm8u5", "label": "Ed25519 Account Address", "path": "m/44'/21888'/3'/0'" } } } ================================================ FILE: wallet/storage/jsonstorage/upgrader.go ================================================ package jsonstorage import ( "encoding/json" "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" blshdkeychain "github.com/pactus-project/pactus/crypto/bls/hdkeychain" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/encrypter" "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" ) type upgrader struct { path string data []byte } func Upgrade(path string) error { data, err := util.ReadFile(path) if err != nil { return err } u := upgrader{ path: path, data: data, } return u.upgrade() } type legacyVault struct { Encrypter encrypter.Encrypter `json:"encrypter"` Purposes vault.Purposes `json:"purposes"` // Contains Purposes of the vault DefaultFee amount.Amount `json:"default_fee"` Addresses map[string]types.AddressInfo `json:"addresses"` } type legacyStore struct { Vault legacyVault `json:"vault"` } func (u *upgrader) upgrade() error { store := new(store) err := json.Unmarshal(u.data, store) if err != nil { return err } legacyStore := new(legacyStore) err = json.Unmarshal(u.data, &legacyStore) if err != nil { return err } if !store.Network.IsMainnet() { crypto.ToTestnetHRP() } switch store.Version { case Version1: if err := u.setPublicKeys(legacyStore); err != nil { return err } logger.Info(fmt.Sprintf("wallet upgraded from version %d to version %d", Version1, Version2)) fallthrough case Version2: if legacyStore.Vault.Encrypter.IsEncrypted() { store.Vault.Encrypter.Params.SetUint32("keylen", 32) } logger.Info(fmt.Sprintf("wallet upgraded from version %d to version %d", Version2, Version3)) fallthrough case Version3: legacyStore.Vault.DefaultFee = amount.Amount(10_000_000) // Set default fee to 0.01 PAC logger.Info(fmt.Sprintf("wallet upgraded from version %d to version %d", Version3, Version4)) fallthrough case Version4: store.DefaultFee = legacyStore.Vault.DefaultFee store.Addresses = make(map[string]types.AddressInfo) store.Version = Version5 store.VaultCRC = store.calcVaultCRC() for addr, ai := range legacyStore.Vault.Addresses { store.Addresses[addr] = types.AddressInfo{ Address: ai.Address, PublicKey: ai.PublicKey, Label: ai.Label, Path: ai.Path, } } logger.Info(fmt.Sprintf("wallet upgraded from version %d to version %d", Version4, Version5)) return store.Save(u.path) case Version5: // Latest version, no need to upgrade. return nil default: return UnsupportedVersionError{ WalletVersion: store.Version, SupportedVersion: VersionLatest, } } } func (*upgrader) setPublicKeys(store *legacyStore) error { for addrKey, info := range store.Vault.Addresses { if info.PublicKey != "" { continue } // Some old wallet doesn't have public key for all addresses. addr, err := crypto.AddressFromString(info.Address) if err != nil { return err } var xPub string if addr.IsAccountAddress() { xPub = store.Vault.Purposes.PurposeBLS.XPubAccount } else if addr.IsValidatorAddress() { xPub = store.Vault.Purposes.PurposeBLS.XPubValidator } ext, err := blshdkeychain.NewKeyFromString(xPub) if err != nil { return err } p, err := addresspath.FromString(info.Path) if err != nil { return err } extendedKey, err := ext.Derive(p.AddressIndex()) if err != nil { return err } blsPubKey, err := bls.PublicKeyFromBytes(extendedKey.RawPublicKey()) if err != nil { return err } info.PublicKey = blsPubKey.String() store.Vault.Addresses[addrKey] = info } return nil } ================================================ FILE: wallet/storage/jsonstorage/upgrader_test.go ================================================ package jsonstorage import ( "testing" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUnsupportedWallet(t *testing.T) { err := Upgrade("./testdata/unsupported_wallet") require.ErrorIs(t, err, UnsupportedVersionError{ WalletVersion: 6, SupportedVersion: VersionLatest, }) } // TestUpgrade ensures that old JSON wallets can be safely upgraded to the latest version. // Encryption parameters are intentionally reduced to speed up the test. func TestUpgrade(t *testing.T) { password := "password" t.Run("Upgrade Wallet From Version 1", func(t *testing.T) { // In this upgrade, some addresses may not have a public key. // This test ensures that after the upgrade, all addresses have a public key. data, err := util.ReadFile("./testdata/wallet_version_1") require.NoError(t, err) tempPath := util.TempFilePath() err = util.WriteFile(tempPath, data) require.NoError(t, err) err = Upgrade(tempPath) require.NoError(t, err) strg, err := Open(tempPath) require.NoError(t, err) assert.Equal(t, VersionLatest, strg.WalletInfo().Version) infos := strg.AllAddresses() for _, info := range infos { assert.NotEmpty(t, info.PublicKey) } }) t.Run("Upgrade Wallet From Version 2", func(t *testing.T) { // In this upgrade, the IV for AES is generated from derived bytes using the Argon2id hasher. // This test ensures that wallet decryption works after the upgrade. data, err := util.ReadFile("./testdata/wallet_version_2") require.NoError(t, err) tempPath := util.TempFilePath() err = util.WriteFile(tempPath, data) require.NoError(t, err) err = Upgrade(tempPath) require.NoError(t, err) strg, err := Open(tempPath) require.NoError(t, err) assert.Equal(t, VersionLatest, strg.WalletInfo().Version) assert.Equal(t, "ARGON2ID-AES_256_CTR-MACV1", strg.Vault().Encrypter.Method) assert.Equal(t, uint32(32), strg.Vault().Encrypter.Params.GetUint32("keylen")) err = strg.Vault().UpdatePassword(password, password) require.NoError(t, err) assert.Equal(t, "ARGON2ID-AES_256_CTR-MACV1", strg.Vault().Encrypter.Method) assert.Equal(t, uint32(48), strg.Vault().Encrypter.Params.GetUint32("keylen")) }) t.Run("Upgrade Wallet From Version 3", func(t *testing.T) { data, err := util.ReadFile("./testdata/wallet_version_3") require.NoError(t, err) tempPath := util.TempFilePath() err = util.WriteFile(tempPath, data) require.NoError(t, err) err = Upgrade(tempPath) require.NoError(t, err) strg, err := Open(tempPath) require.NoError(t, err) assert.Equal(t, VersionLatest, strg.WalletInfo().Version) mnemonic, err := strg.Vault().Mnemonic(password) require.NoError(t, err) assert.Equal(t, "ARGON2ID-AES_256_CBC-MACV1", strg.Vault().Encrypter.Method) assert.Equal(t, testMnemonic, mnemonic) }) t.Run("Upgrade Wallet From Version 4", func(t *testing.T) { data, err := util.ReadFile("./testdata/wallet_version_4") require.NoError(t, err) tempPath := util.TempFilePath() err = util.WriteFile(tempPath, data) require.NoError(t, err) err = Upgrade(tempPath) require.NoError(t, err) strg, err := Open(tempPath) require.NoError(t, err) assert.Equal(t, VersionLatest, strg.WalletInfo().Version) assert.Equal(t, genesis.Mainnet, strg.WalletInfo().Network) assert.Equal(t, amount.Amount(2e7), strg.WalletInfo().DefaultFee) // 0.02 PAC infos := strg.AllAddresses() assert.Len(t, infos, 5) }) } func TestUpgradeTestnet(t *testing.T) { data, err := util.ReadFile("./testdata/testnet_wallet") require.NoError(t, err) tempPath := util.TempFilePath() err = util.WriteFile(tempPath, data) require.NoError(t, err) err = Upgrade(tempPath) require.NoError(t, err) strg, err := Open(tempPath) require.NoError(t, err) assert.Equal(t, VersionLatest, strg.WalletInfo().Version) assert.Equal(t, genesis.Testnet, strg.WalletInfo().Network) } ================================================ FILE: wallet/storage/jsonstorage/version.go ================================================ package jsonstorage const ( Version1 = 1 // Initial version Version2 = 2 // Supporting Ed25519 Version3 = 3 // Supporting AEC-256-CBC encryption method Version4 = 4 // Set Default Fee for the Wallet Version5 = 5 // Define Storage Interface VersionLatest = Version5 ) ================================================ FILE: wallet/storage/sqlitestorage/options.go ================================================ package sqlitestorage // SQLite settings. type settings struct { lockingMode string } func defaultSettings() settings { return settings{ lockingMode: "EXCLUSIVE", } } // Option configures SQLite settings. type Option func(*settings) // WithLockingMode sets SQLite locking mode (e.g. NORMAL, EXCLUSIVE). func WithLockingMode(lockMode bool) Option { return func(p *settings) { if lockMode { p.lockingMode = "EXCLUSIVE" } else { p.lockingMode = "NORMAL" } } } ================================================ FILE: wallet/storage/sqlitestorage/sql.go ================================================ package sqlitestorage // SQL queries and schema definitions. const ( // Schema creation queries. createWalletTableSQL = ` CREATE TABLE wallet ( name TEXT PRIMARY KEY, value TEXT NOT NULL )` createAddressesTableSQL = ` CREATE TABLE addresses ( address TEXT PRIMARY KEY, public_key TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT '', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP )` createTransactionsTableSQL = ` CREATE TABLE transactions ( no INTEGER PRIMARY KEY, -- alias for rowid, auto-incremented starting at 1 tx_id TEXT NOT NULL, -- transaction identifier sender TEXT NOT NULL, receiver TEXT NOT NULL, direction INTEGER NOT NULL, amount INTEGER NOT NULL, fee INTEGER NOT NULL, memo TEXT NOT NULL DEFAULT '', status INTEGER NOT NULL, -- status: failed=-1, pending=0, confirmed=1 block_height INTEGER NOT NULL, payload_type INTEGER NOT NULL, data BLOB NOT NULL DEFAULT X'', comment TEXT NOT NULL DEFAULT '', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE (tx_id, receiver) CHECK (direction IN (1, 2)) -- incoming=1, outgoing=2 )` createAddressesUpdatedAtTriggerSQL = ` CREATE TRIGGER IF NOT EXISTS trg_addresses_updated_at AFTER UPDATE ON addresses FOR EACH ROW BEGIN UPDATE addresses SET updated_at = CURRENT_TIMESTAMP WHERE address = OLD.address; END` createTransactionsUpdatedAtTriggerSQL = ` CREATE TRIGGER IF NOT EXISTS trg_transactions_updated_at AFTER UPDATE ON transactions FOR EACH ROW BEGIN UPDATE transactions SET updated_at = CURRENT_TIMESTAMP WHERE no = OLD.no; END` // Partial index to speed up pending-transaction queries ordered by creation time. createPendingNoIdxSQL = ` CREATE INDEX IF NOT EXISTS idx_transactions_pending_no ON transactions (no DESC) WHERE status = 0` // Indexes to speed up lookups by sender/receiver and ordering by created_at. createTxSenderNoIdxSQL = ` CREATE INDEX IF NOT EXISTS idx_tx_sender_no ON transactions(sender, no DESC)` createTxReceiverNoIdxSQL = ` CREATE INDEX IF NOT EXISTS idx_tx_receiver_no ON transactions(receiver, no DESC)` // Wallet table operations. insertWalletEntrySQL = ` INSERT INTO wallet (name, value) VALUES (?, ?)` updateWalletEntrySQL = ` UPDATE wallet SET value = ? WHERE name = ?` selectAllWalletEntriesSQL = ` SELECT name, value FROM wallet` // Address table operations. insertAddressSQL = ` INSERT INTO addresses (address, public_key, label, path) VALUES (?, ?, ?, ?)` updateAddressSQL = ` UPDATE addresses SET label = ?, public_key = ?, path = ? WHERE address = ?` selectAllAddressesSQL = ` SELECT address, public_key, label, path, created_at, updated_at FROM addresses ORDER BY created_at ASC` // Transaction table operations. insertTransactionSQL = ` INSERT INTO transactions (tx_id, sender, receiver, direction, amount, fee, memo, status, block_height, payload_type, data, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` updateTransactionStatusSQL = ` UPDATE transactions SET status = ?, block_height = ? WHERE no = ?` selectTransactionByNoSQL = ` SELECT no, tx_id, sender, receiver, direction, amount, fee, memo, status, block_height, payload_type, data, comment, created_at, updated_at FROM transactions WHERE no = ? LIMIT 1` countTransactionByTxIDSQL = ` SELECT COUNT(*) FROM transactions WHERE tx_id = ?` selectPendingTransactionsSQL = ` SELECT no, tx_id, sender, receiver, direction, amount, fee, memo, status, block_height, payload_type, data, comment, created_at, updated_at FROM transactions WHERE status = ? ORDER BY created_at DESC` ) ================================================ FILE: wallet/storage/sqlitestorage/storage.go ================================================ package sqlitestorage import ( "context" "database/sql" "encoding/json" "errors" "fmt" "path/filepath" "strings" "time" _ "github.com/glebarez/go-sqlite" // sqlite driver "github.com/google/uuid" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/wallet/storage" wtypes "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" ) // Wallet metadata keys. const ( keyVersion = "version" keyUUID = "uuid" keyCreatedAt = "created_at" keyNetwork = "network" keyDefaultFee = "default_fee" keyVault = "vault" ) // Storage represents the SQLite-based wallet storage implementing IStorage interface. type Storage struct { ctx context.Context db *sql.DB path string info *wtypes.WalletInfo vlt *vault.Vault addressMap map[string]wtypes.AddressInfo } func dbPath(path string) string { return filepath.Join(path, "wallet.db") } func configurePragmas(ctx context.Context, db *sql.DB, lockingMode string) error { pragmas := []string{ fmt.Sprintf("PRAGMA locking_mode=%s;", lockingMode), "PRAGMA journal_mode=WAL;", "PRAGMA synchronous=NORMAL;", } for _, pragma := range pragmas { if _, err := db.ExecContext(ctx, pragma); err != nil { return fmt.Errorf("failed to set pragma %q: %w", pragma, err) } } return nil } func openDB(ctx context.Context, path string, opts ...Option) (*sql.DB, error) { dsn := fmt.Sprintf("file:%s?_busy_timeout=5000", dbPath(path)) db, err := sql.Open("sqlite", dsn) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } p := defaultSettings() for _, opt := range opts { opt(&p) } if err := configurePragmas(ctx, db, p.lockingMode); err != nil { _ = db.Close() return nil, err } return db, nil } // Create creates a new SQLite storage instance and initializes the schema. func Create(ctx context.Context, path string, network genesis.ChainType, vlt *vault.Vault, opts ...Option, ) (*Storage, error) { if err := util.Mkdir(path); err != nil { return nil, err } db, err := openDB(ctx, path, opts...) if err != nil { return nil, err } // Initialize database schema tables := []string{ createWalletTableSQL, createAddressesTableSQL, createTransactionsTableSQL, createAddressesUpdatedAtTriggerSQL, createTransactionsUpdatedAtTriggerSQL, createPendingNoIdxSQL, createTxSenderNoIdxSQL, createTxReceiverNoIdxSQL, } for _, query := range tables { if _, err := db.ExecContext(ctx, query); err != nil { _ = db.Close() return nil, fmt.Errorf("failed to create table: %w", err) } } // Marshal vault to JSON vaultJSON, err := json.Marshal(vlt) if err != nil { _ = db.Close() return nil, fmt.Errorf("failed to marshal vault: %w", err) } // Store wallet metadata // KeyValue represents a key-value pair for wallet entries. type KeyValue struct { Key string Value string } entries := []KeyValue{ {Key: keyVersion, Value: fmt.Sprintf("%d", VersionLatest)}, {Key: keyUUID, Value: uuid.New().String()}, {Key: keyCreatedAt, Value: fmt.Sprintf("%d", util.RoundNow(1).Unix())}, {Key: keyNetwork, Value: fmt.Sprintf("%d", network)}, {Key: keyDefaultFee, Value: fmt.Sprintf("%d", amount.Amount(10_000_000))}, {Key: keyVault, Value: string(vaultJSON)}, } for _, entry := range entries { if _, err := db.ExecContext(ctx, insertWalletEntrySQL, entry.Key, entry.Value); err != nil { _ = db.Close() return nil, fmt.Errorf("failed to insert wallet entry %s: %w", entry.Key, err) } } return open(ctx, db, path) } // Open opens an existing SQLite storage instance without creating schema. func Open(ctx context.Context, path string, opts ...Option) (*Storage, error) { db, err := openDB(ctx, path, opts...) if err != nil { return nil, err } return open(ctx, db, path) } // open loads wallet info and returns a Storage instance. func open(ctx context.Context, db *sql.DB, path string) (*Storage, error) { strg := &Storage{ ctx: ctx, db: db, path: path, } // Load wallet info into memory if err := strg.loadWalletInfo(); err != nil { _ = db.Close() return nil, fmt.Errorf("failed to load wallet info: %w", err) } // Load addresses into memory if err := strg.loadAddresses(); err != nil { _ = db.Close() return nil, fmt.Errorf("failed to load addresses: %w", err) } return strg, nil } // Close closes the database connection. func (s *Storage) Close() error { if s.db != nil { return s.db.Close() } return nil } // WalletInfo returns the wallet information. func (s *Storage) WalletInfo() *wtypes.WalletInfo { return s.info } // loadWalletInfo loads wallet information from the database into memory. func (s *Storage) loadWalletInfo() error { // Fetch all wallet entries at once rows, err := s.db.QueryContext(s.ctx, selectAllWalletEntriesSQL) if err != nil { return fmt.Errorf("failed to query wallet entries: %w", err) } defer func() { _ = rows.Close() }() entries := make(map[string]string) for rows.Next() { var name, value string if err := rows.Scan(&name, &value); err != nil { return fmt.Errorf("failed to scan wallet entry: %w", err) } entries[name] = value } if err := rows.Err(); err != nil { return fmt.Errorf("failed to iterate wallet entries: %w", err) } version := 0 if _, err := fmt.Sscanf(entries[keyVersion], "%d", &version); err != nil { return fmt.Errorf("failed to parse version: %w", err) } var defaultFee amount.Amount if _, err := fmt.Sscanf(entries[keyDefaultFee], "%d", &defaultFee); err != nil { return fmt.Errorf("failed to parse default fee: %w", err) } var createdAtUnix int64 if _, err := fmt.Sscanf(entries[keyCreatedAt], "%d", &createdAtUnix); err != nil { return fmt.Errorf("failed to parse created_at: %w", err) } createdAt := time.Unix(createdAtUnix, 0) // Parse network type var network genesis.ChainType if _, err := fmt.Sscanf(entries[keyNetwork], "%d", &network); err != nil { return fmt.Errorf("failed to parse network: %w", err) } var vlt vault.Vault if vaultJSON, ok := entries[keyVault]; ok { if err := json.Unmarshal([]byte(vaultJSON), &vlt); err != nil { return fmt.Errorf("failed to unmarshal vault: %w", err) } } s.vlt = &vlt s.info = &wtypes.WalletInfo{ Path: s.path, Driver: "SQLite", Version: version, Network: network, DefaultFee: defaultFee, UUID: entries[keyUUID], Encrypted: s.vlt.IsEncrypted(), Neutered: s.vlt.IsNeutered(), CreatedAt: createdAt, } return nil } // loadAddresses loads addresses into memory. func (s *Storage) loadAddresses() error { rows, err := s.db.QueryContext(s.ctx, selectAllAddressesSQL) if err != nil { return fmt.Errorf("failed to query addresses: %w", err) } defer func() { _ = rows.Close() }() s.addressMap = make(map[string]wtypes.AddressInfo) for rows.Next() { addr, err := scanAddress(rows) if err != nil { return fmt.Errorf("failed to scan address: %w", err) } s.addressMap[addr.Address] = *addr } return rows.Err() } // Vault returns the vault. func (s *Storage) Vault() *vault.Vault { return s.vlt } // UpdateVault updates the vault in storage. func (s *Storage) UpdateVault(vlt *vault.Vault) error { if err := s.saveVault(vlt); err != nil { return err } s.vlt = vlt s.info.Encrypted = vlt.IsEncrypted() s.info.Neutered = vlt.IsNeutered() return nil } // SetDefaultFee sets the default fee. func (s *Storage) SetDefaultFee(fee amount.Amount) error { if err := s.updateWalletEntry(keyDefaultFee, fmt.Sprintf("%d", fee)); err != nil { return err } s.info.DefaultFee = fee return nil } // AllAddresses returns all addresses in the wallet. func (s *Storage) AllAddresses() []wtypes.AddressInfo { addresses := make([]wtypes.AddressInfo, 0, len(s.addressMap)) for _, addr := range s.addressMap { addresses = append(addresses, addr) } return addresses } // AddressCount returns the number of addresses in the wallet. func (s *Storage) AddressCount() int { return len(s.addressMap) } // AddressInfo returns the address information for the given address. func (s *Storage) AddressInfo(address string) (*wtypes.AddressInfo, error) { info, exists := s.addressMap[address] if !exists { return nil, storage.ErrNotFound } return &info, nil } // InsertAddress inserts a new address. func (s *Storage) InsertAddress(info *wtypes.AddressInfo) error { _, err := s.db.ExecContext(s.ctx, insertAddressSQL, info.Address, info.PublicKey, info.Label, info.Path) if err != nil { return err } return s.loadAddresses() } // UpdateAddress updates an existing address. func (s *Storage) UpdateAddress(info *wtypes.AddressInfo) error { _, err := s.db.ExecContext(s.ctx, updateAddressSQL, info.Label, info.PublicKey, info.Path, info.Address) if err != nil { return err } return s.loadAddresses() } // HasAddress checks if an address exists. func (s *Storage) HasAddress(address string) bool { _, exists := s.addressMap[address] return exists } // InsertTransaction inserts a new transaction. func (s *Storage) InsertTransaction(info *wtypes.TransactionInfo) error { result, err := s.db.ExecContext(s.ctx, insertTransactionSQL, info.TxID, info.Sender, info.Receiver, info.Direction, info.Amount, info.Fee, info.Memo, info.Status, info.BlockHeight, int(info.PayloadType), info.Data, info.Comment, ) if err != nil { return err } info.No, _ = result.LastInsertId() return nil } // UpdateTransactionStatus updates the status and block height for all transactions with the given primary key. func (s *Storage) UpdateTransactionStatus(no int64, status wtypes.TransactionStatus, blockHeight types.Height) error { _, err := s.db.ExecContext(s.ctx, updateTransactionStatusSQL, int(status), blockHeight, no) return err } // HasTransaction checks if a transaction exists by transaction ID. func (s *Storage) HasTransaction(txID string) bool { var count int err := s.db.QueryRowContext(s.ctx, countTransactionByTxIDSQL, txID).Scan(&count) if err != nil { return false } return count > 0 } // scanner is an interface that both *sql.Row and *sql.Rows satisfy. type scanner interface { Scan(dest ...any) error } // scanAddress scans a row into an AddressInfo struct. func scanAddress(s scanner) (*wtypes.AddressInfo, error) { var info wtypes.AddressInfo err := s.Scan( &info.Address, &info.PublicKey, &info.Label, &info.Path, &info.CreatedAt, &info.UpdatedAt, ) if err != nil { return nil, err } return &info, nil } // scanTransaction scans a row into a TransactionInfo struct. func scanTransaction(s scanner) (*wtypes.TransactionInfo, error) { var info wtypes.TransactionInfo var status, payloadType int err := s.Scan( &info.No, &info.TxID, &info.Sender, &info.Receiver, &info.Direction, &info.Amount, &info.Fee, &info.Memo, &status, &info.BlockHeight, &payloadType, &info.Data, &info.Comment, &info.CreatedAt, &info.UpdatedAt, ) if err != nil { return nil, err } info.Status = wtypes.TransactionStatus(status) info.PayloadType = payload.Type(payloadType) return &info, nil } // GetTransaction retrieves a transaction by primary key. func (s *Storage) GetTransaction(no int64) (*wtypes.TransactionInfo, error) { info, err := scanTransaction(s.db.QueryRowContext(s.ctx, selectTransactionByNoSQL, no)) if err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, storage.ErrNotFound } return nil, err } return info, nil } // QueryTransactions returns transactions matching the provided filters with pagination. // Empty or "*" address value is treated as no filter. Filters are combined with AND. func (s *Storage) QueryTransactions(params storage.QueryParams) ([]*wtypes.TransactionInfo, error) { conditions := make([]string, 0, 3) args := make([]any, 0, 6) if params.Direction != wtypes.TxDirectionAny { conditions = append(conditions, "direction = ?") args = append(args, params.Direction) } if params.Address != "*" { switch params.Direction { case wtypes.TxDirectionAny: conditions = append(conditions, "(sender = ? OR receiver = ?)") args = append(args, params.Address, params.Address) case wtypes.TxDirectionIncoming: conditions = append(conditions, "receiver = ?") args = append(args, params.Address) case wtypes.TxDirectionOutgoing: conditions = append(conditions, "sender = ?") args = append(args, params.Address) } } where := "" if len(conditions) > 0 { where = "WHERE " + strings.Join(conditions, " AND ") } // Apply pagination args = append(args, params.Count, params.Skip) var queryBuilder strings.Builder queryBuilder.WriteString(` SELECT no, tx_id, sender, receiver, direction, amount, fee, memo, status, block_height, payload_type, data, comment, created_at, updated_at FROM transactions `) if where != "" { queryBuilder.WriteString(where) queryBuilder.WriteString("\n") } queryBuilder.WriteString(`ORDER BY created_at DESC LIMIT ? OFFSET ?`) query := queryBuilder.String() rows, err := s.db.QueryContext(s.ctx, query, args...) if err != nil { return nil, err } defer func() { _ = rows.Close() }() transactions := make([]*wtypes.TransactionInfo, 0) for rows.Next() { info, err := scanTransaction(rows) if err != nil { return nil, err } transactions = append(transactions, info) } return transactions, rows.Err() } // GetPendingTransactions returns pending transactions keyed by transaction ID. func (s *Storage) GetPendingTransactions() (map[string]*wtypes.TransactionInfo, error) { rows, err := s.db.QueryContext(s.ctx, selectPendingTransactionsSQL, int(wtypes.TransactionStatusPending)) if err != nil { return nil, err } defer func() { _ = rows.Close() }() pending := make(map[string]*wtypes.TransactionInfo) for rows.Next() { info, err := scanTransaction(rows) if err != nil { return nil, err } pending[info.TxID] = info } return pending, rows.Err() } // Clone creates a copy of the storage at a new path. func (s *Storage) Clone(path string) (storage.IStorage, error) { if err := util.Mkdir(path); err != nil { return nil, err } // Use VACUUM INTO to create a backup _, err := s.db.ExecContext(s.ctx, fmt.Sprintf("VACUUM INTO '%s'", dbPath(path))) if err != nil { return nil, fmt.Errorf("failed to backup database: %w", err) } // Open the cloned database clonedStorage, err := Open(s.ctx, path) if err != nil { return nil, err } // Update UUID and CreatedAt for the cloned wallet newUUID := uuid.New().String() if err := clonedStorage.updateWalletEntry(keyUUID, newUUID); err != nil { _ = clonedStorage.Close() return nil, err } clonedStorage.info.UUID = newUUID newCreatedAt := util.RoundNow(1) if err := clonedStorage.updateWalletEntry(keyCreatedAt, fmt.Sprintf("%d", newCreatedAt.Unix())); err != nil { _ = clonedStorage.Close() return nil, err } clonedStorage.info.CreatedAt = newCreatedAt clonedStorage.info.Path = path return clonedStorage, nil } func (s *Storage) updateWalletEntry(key, value string) error { _, err := s.db.ExecContext(s.ctx, updateWalletEntrySQL, value, key) return err } func (s *Storage) saveVault(vlt *vault.Vault) error { vaultJSON, err := json.Marshal(vlt) if err != nil { return fmt.Errorf("failed to marshal vault: %w", err) } return s.updateWalletEntry(keyVault, string(vaultJSON)) } func (*Storage) IsLegacy() bool { return false } ================================================ FILE: wallet/storage/sqlitestorage/storage_test.go ================================================ package sqlitestorage import ( "testing" "time" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/storage" "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) //nolint:dupword // duplicated seed phrase words var testMnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon cactus" type testData struct { *testsuite.TestSuite storage *Storage } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) vlt, err := vault.CreateVaultFromMnemonic(testMnemonic, addresspath.CoinTypePactusTestnet) require.NoError(t, err) path := util.TempDirPath() strg, err := Create(t.Context(), path, genesis.Testnet, vlt) require.NoError(t, err) t.Cleanup(func() { _ = strg.Close() }) return &testData{ TestSuite: ts, storage: strg, } } func (td *testData) RandomAddressInfo(t *testing.T) *types.AddressInfo { t.Helper() return &types.AddressInfo{ Address: td.RandAccAddress().String(), PublicKey: td.RandString(32), Label: td.RandString(16), Path: td.RandString(16), } } func (td *testData) InsertRandomAddressInfo(t *testing.T) *types.AddressInfo { t.Helper() addrInfo := td.RandomAddressInfo(t) err := td.storage.InsertAddress(addrInfo) require.NoError(t, err) // Get the address info from the database addrInfo, err = td.storage.AddressInfo(addrInfo.Address) require.NoError(t, err) return addrInfo } func (td *testData) RandomDirection(t *testing.T) types.TxDirection { t.Helper() return types.TxDirection(td.RandIntMax(2) + 1) } func (td *testData) RandomTransactionInfo(t *testing.T, direction types.TxDirection, opts ...testsuite.TransactionMakerOption, ) *types.TransactionInfo { t.Helper() trx := td.GenerateTestTransferTx(opts...) txInfos, err := types.MakeTransactionInfos(trx, types.TransactionStatusPending, 0) require.NoError(t, err) txInfos[0].Direction = direction return txInfos[0] } func (td *testData) InsertRandomTransactionInfo(t *testing.T, direction types.TxDirection, opts ...testsuite.TransactionMakerOption, ) *types.TransactionInfo { t.Helper() txInfo := td.RandomTransactionInfo(t, direction, opts...) err := td.storage.InsertTransaction(txInfo) require.NoError(t, err) // Get the transaction info from the database txInfo, err = td.storage.GetTransaction(txInfo.No) require.NoError(t, err) return txInfo } func TestWalletInfo(t *testing.T) { td := setup(t) info := td.storage.WalletInfo() assert.Equal(t, VersionLatest, info.Version) assert.Equal(t, genesis.Testnet, info.Network) assert.Equal(t, "SQLite", info.Driver) assert.NotEmpty(t, info.UUID) assert.Equal(t, amount.Amount(10_000_000), info.DefaultFee) assert.False(t, info.CreatedAt.IsZero()) } func TestVault(t *testing.T) { td := setup(t) vlt := td.storage.Vault() require.NotNil(t, vlt) assert.False(t, vlt.IsEncrypted()) assert.False(t, vlt.IsNeutered()) } func TestUpdateVault(t *testing.T) { td := setup(t) vlt1 := td.storage.Vault() require.NotNil(t, vlt1) // Create a new address to modify the vault _, err := vlt1.NewValidatorAddress("Test Validator") require.NoError(t, err) // Update vault err = td.storage.UpdateVault(vlt1) require.NoError(t, err) // Verify update vlt2 := td.storage.Vault() assert.Equal(t, uint32(1), vlt2.Purposes.PurposeBLS.NextValidatorIndex) } func TestSetDefaultFee(t *testing.T) { td := setup(t) newFee := amount.Amount(20_000_000) err := td.storage.SetDefaultFee(newFee) require.NoError(t, err) info := td.storage.WalletInfo() assert.Equal(t, newFee, info.DefaultFee) } func TestAddressOperations(t *testing.T) { td := setup(t) addrInfo1 := td.InsertRandomAddressInfo(t) addrInfo2 := td.InsertRandomAddressInfo(t) // Test AllAddresses addresses := td.storage.AllAddresses() require.Len(t, addresses, 2) assert.Equal(t, 2, td.storage.AddressCount()) assert.True(t, td.storage.HasAddress(addrInfo1.Address)) assert.True(t, td.storage.HasAddress(addrInfo2.Address)) // Test GetAddress retrieved1, err := td.storage.AddressInfo(addrInfo1.Address) require.NoError(t, err) assert.Equal(t, addrInfo1.Address, retrieved1.Address) assert.Equal(t, addrInfo1.PublicKey, retrieved1.PublicKey) assert.Equal(t, addrInfo1.Path, retrieved1.Path) assert.Equal(t, addrInfo1.Label, retrieved1.Label) // Test UpdateAddress addrInfo2.Label = "Updated Label" err = td.storage.UpdateAddress(addrInfo2) require.NoError(t, err) retrieved2, err := td.storage.AddressInfo(addrInfo2.Address) require.NoError(t, err) assert.Equal(t, "Updated Label", retrieved2.Label) // Test GetAddress not found _, err = td.storage.AddressInfo("non_existent") require.ErrorIs(t, err, storage.ErrNotFound) } func TestInsertAddress(t *testing.T) { td := setup(t) addrInfo1 := td.InsertRandomAddressInfo(t) assert.True(t, td.storage.HasAddress(addrInfo1.Address)) addrInfo2 := td.InsertRandomAddressInfo(t) assert.True(t, td.storage.HasAddress(addrInfo2.Address)) assert.Equal(t, 2, td.storage.AddressCount()) } func TestTransactionOperations(t *testing.T) { td := setup(t) txInfo := td.InsertRandomTransactionInfo(t, td.RandomDirection(t)) // Test HasTransaction assert.True(t, td.storage.HasTransaction(txInfo.TxID)) assert.False(t, td.storage.HasTransaction("non_existing")) // Test GetTransaction retrieved, err := td.storage.GetTransaction(txInfo.No) require.NoError(t, err) assert.Equal(t, txInfo.TxID, retrieved.TxID) assert.Equal(t, txInfo.Sender, retrieved.Sender) assert.Equal(t, txInfo.Receiver, retrieved.Receiver) assert.Equal(t, txInfo.Amount, retrieved.Amount) assert.Equal(t, txInfo.Fee, retrieved.Fee) assert.Equal(t, txInfo.Memo, retrieved.Memo) assert.Equal(t, txInfo.Status, retrieved.Status) assert.Equal(t, txInfo.BlockHeight, retrieved.BlockHeight) assert.Equal(t, txInfo.PayloadType, retrieved.PayloadType) assert.Equal(t, txInfo.Comment, retrieved.Comment) // Test GetTransaction not found _, err = td.storage.GetTransaction(-1) require.ErrorIs(t, err, storage.ErrNotFound) // Test UpdateTransactionStatus err = td.storage.UpdateTransactionStatus(txInfo.No, types.TransactionStatusConfirmed, 1) require.NoError(t, err) retrieved, err = td.storage.GetTransaction(txInfo.No) require.NoError(t, err) assert.Equal(t, types.TransactionStatusConfirmed, retrieved.Status) } func TestQueryTransactions_Range(t *testing.T) { td := setup(t) // Insert multiple transactions receiver := td.RandAccAddress() for i := 0; i < 5; i++ { td.InsertRandomTransactionInfo(t, td.RandomDirection(t), testsuite.TransactionWithReceiver(receiver)) } // Test QueryTransactions with pagination transactions, err := td.storage.QueryTransactions(storage.QueryParams{ Address: receiver.String(), Direction: types.TxDirectionAny, Count: 3, Skip: 0, }) require.NoError(t, err) assert.Len(t, transactions, 3) // Test with skip transactions, err = td.storage.QueryTransactions(storage.QueryParams{ Address: receiver.String(), Direction: types.TxDirectionAny, Count: 3, Skip: 3, }) require.NoError(t, err) assert.Len(t, transactions, 2) // Test with different receiver transactions, err = td.storage.QueryTransactions(storage.QueryParams{ Address: "other_receiver", Direction: types.TxDirectionAny, Count: 10, Skip: 0, }) require.NoError(t, err) assert.Empty(t, transactions) } func TestQueryTransactions_Direction(t *testing.T) { td := setup(t) // create three tx rows: // 1) sender A -> receiver B // 2) sender A -> receiver C // 3) sender D -> receiver B pubA, signerA := td.RandEd25519KeyPair() pubD, signerD := td.RandEd25519KeyPair() addrB := td.RandAccAddress() addrC := td.RandAccAddress() td.InsertRandomTransactionInfo(t, types.TxDirectionOutgoing, testsuite.TransactionWithSigner(signerA), testsuite.TransactionWithReceiver(addrB)) td.InsertRandomTransactionInfo(t, types.TxDirectionOutgoing, testsuite.TransactionWithSigner(signerA), testsuite.TransactionWithReceiver(addrC)) td.InsertRandomTransactionInfo(t, types.TxDirectionIncoming, testsuite.TransactionWithSigner(signerD), testsuite.TransactionWithReceiver(addrB)) // Wildcard both: all 3 txs, err := td.storage.QueryTransactions(storage.QueryParams{ Address: "*", Direction: types.TxDirectionAny, Count: 10, Skip: 0, }) require.NoError(t, err) assert.Len(t, txs, 3) // Filter sender only (A): rows 1 and 2 txs, err = td.storage.QueryTransactions(storage.QueryParams{ Address: pubA.AccountAddress().String(), Direction: types.TxDirectionOutgoing, Count: 10, Skip: 0, }) require.NoError(t, err) assert.Len(t, txs, 2) // Filter sender only (D): rows 3 txs, err = td.storage.QueryTransactions(storage.QueryParams{ Address: pubD.AccountAddress().String(), Direction: types.TxDirectionOutgoing, Count: 10, Skip: 0, }) require.NoError(t, err) assert.Empty(t, txs) // Filter receiver only (B): rows with incoming to B (row 3) txs, err = td.storage.QueryTransactions(storage.QueryParams{ Address: addrB.String(), Direction: types.TxDirectionIncoming, Count: 10, Skip: 0, }) require.NoError(t, err) assert.Len(t, txs, 1) // Outgoing from A: rows 1 and 2 txs, err = td.storage.QueryTransactions(storage.QueryParams{ Address: pubA.AccountAddress().String(), Direction: types.TxDirectionOutgoing, Count: 10, Skip: 0, }) require.NoError(t, err) assert.Len(t, txs, 2) } func TestGetPendingTransactions(t *testing.T) { td := setup(t) // Insert multiple transactions txInfo1 := td.InsertRandomTransactionInfo(t, types.TxDirectionOutgoing) txInfo2 := td.InsertRandomTransactionInfo(t, types.TxDirectionOutgoing) txInfo3 := td.InsertRandomTransactionInfo(t, types.TxDirectionIncoming) pendings, err := td.storage.GetPendingTransactions() require.NoError(t, err) require.Len(t, pendings, 3) _ = td.storage.UpdateTransactionStatus(txInfo1.No, types.TransactionStatusConfirmed, td.RandHeight()) _ = td.storage.UpdateTransactionStatus(txInfo2.No, types.TransactionStatusFailed, 0) pendings, err = td.storage.GetPendingTransactions() require.NoError(t, err) require.Len(t, pendings, 1) assert.Contains(t, pendings, txInfo3.TxID) } func TestClone(t *testing.T) { td := setup(t) clonePath := util.TempDirPath() cloned, err := td.storage.Clone(clonePath) require.NoError(t, err) defer func() { _ = cloned.Close() }() // Verify cloned storage has different UUID and CreatedAt originalInfo := td.storage.WalletInfo() clonedInfo := cloned.WalletInfo() assert.NotEqual(t, originalInfo.UUID, clonedInfo.UUID) assert.NotEqual(t, originalInfo.CreatedAt, clonedInfo.CreatedAt) assert.Equal(t, originalInfo.Network, clonedInfo.Network) assert.Equal(t, originalInfo.Version, clonedInfo.Version) assert.Equal(t, originalInfo.DefaultFee, clonedInfo.DefaultFee) assert.Equal(t, originalInfo.Encrypted, clonedInfo.Encrypted) assert.Equal(t, originalInfo.Driver, clonedInfo.Driver) assert.Equal(t, td.storage.Vault(), cloned.Vault()) assert.Equal(t, td.storage.AllAddresses(), cloned.AllAddresses()) } func TestUpdatedAt(t *testing.T) { td := setup(t) addrInfo := td.InsertRandomAddressInfo(t) trxInfo := td.InsertRandomTransactionInfo(t, td.RandomDirection(t)) addrInfo1, err := td.storage.AddressInfo(addrInfo.Address) require.NoError(t, err) trxInfo1, err := td.storage.GetTransaction(trxInfo.No) require.NoError(t, err) time.Sleep(1 * time.Second) err = td.storage.UpdateAddress(addrInfo) require.NoError(t, err) err = td.storage.UpdateTransactionStatus(trxInfo.No, types.TransactionStatusConfirmed, td.RandHeight()) require.NoError(t, err) addrInfo2, err := td.storage.AddressInfo(addrInfo.Address) require.NoError(t, err) assert.NotEqual(t, addrInfo1.UpdatedAt, addrInfo2.UpdatedAt) trxInfo2, err := td.storage.GetTransaction(trxInfo.No) require.NoError(t, err) assert.NotEqual(t, trxInfo1.UpdatedAt, trxInfo2.UpdatedAt) } func TestInsertDuplicateTransaction(t *testing.T) { td := setup(t) txInfo := td.InsertRandomTransactionInfo(t, td.RandomDirection(t)) err := td.storage.InsertTransaction(txInfo) require.Error(t, err) } ================================================ FILE: wallet/storage/sqlitestorage/version.go ================================================ package sqlitestorage const ( Version1 = 1 // Initial version VersionLatest = Version1 ) ================================================ FILE: wallet/storage/storage_mock.go ================================================ // Code generated by MockGen. DO NOT EDIT. // Source: wallet/storage/interface.go // // Generated by this command: // // mockgen -source=wallet/storage/interface.go -destination=wallet/storage/storage_mock.go -package=storage // // Package storage is a generated GoMock package. package storage import ( reflect "reflect" types "github.com/pactus-project/pactus/types" amount "github.com/pactus-project/pactus/types/amount" types0 "github.com/pactus-project/pactus/wallet/types" vault "github.com/pactus-project/pactus/wallet/vault" gomock "go.uber.org/mock/gomock" ) // MockIStorage is a mock of IStorage interface. type MockIStorage struct { ctrl *gomock.Controller recorder *MockIStorageMockRecorder isgomock struct{} } // MockIStorageMockRecorder is the mock recorder for MockIStorage. type MockIStorageMockRecorder struct { mock *MockIStorage } // NewMockIStorage creates a new mock instance. func NewMockIStorage(ctrl *gomock.Controller) *MockIStorage { mock := &MockIStorage{ctrl: ctrl} mock.recorder = &MockIStorageMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIStorage) EXPECT() *MockIStorageMockRecorder { return m.recorder } // AddressCount mocks base method. func (m *MockIStorage) AddressCount() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddressCount") ret0, _ := ret[0].(int) return ret0 } // AddressCount indicates an expected call of AddressCount. func (mr *MockIStorageMockRecorder) AddressCount() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddressCount", reflect.TypeOf((*MockIStorage)(nil).AddressCount)) } // AddressInfo mocks base method. func (m *MockIStorage) AddressInfo(address string) (*types0.AddressInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddressInfo", address) ret0, _ := ret[0].(*types0.AddressInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // AddressInfo indicates an expected call of AddressInfo. func (mr *MockIStorageMockRecorder) AddressInfo(address any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddressInfo", reflect.TypeOf((*MockIStorage)(nil).AddressInfo), address) } // AllAddresses mocks base method. func (m *MockIStorage) AllAddresses() []types0.AddressInfo { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AllAddresses") ret0, _ := ret[0].([]types0.AddressInfo) return ret0 } // AllAddresses indicates an expected call of AllAddresses. func (mr *MockIStorageMockRecorder) AllAddresses() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllAddresses", reflect.TypeOf((*MockIStorage)(nil).AllAddresses)) } // Clone mocks base method. func (m *MockIStorage) Clone(path string) (IStorage, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Clone", path) ret0, _ := ret[0].(IStorage) ret1, _ := ret[1].(error) return ret0, ret1 } // Clone indicates an expected call of Clone. func (mr *MockIStorageMockRecorder) Clone(path any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Clone", reflect.TypeOf((*MockIStorage)(nil).Clone), path) } // Close mocks base method. func (m *MockIStorage) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) return ret0 } // Close indicates an expected call of Close. func (mr *MockIStorageMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockIStorage)(nil).Close)) } // GetPendingTransactions mocks base method. func (m *MockIStorage) GetPendingTransactions() (map[string]*types0.TransactionInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPendingTransactions") ret0, _ := ret[0].(map[string]*types0.TransactionInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // GetPendingTransactions indicates an expected call of GetPendingTransactions. func (mr *MockIStorageMockRecorder) GetPendingTransactions() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingTransactions", reflect.TypeOf((*MockIStorage)(nil).GetPendingTransactions)) } // GetTransaction mocks base method. func (m *MockIStorage) GetTransaction(no int64) (*types0.TransactionInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTransaction", no) ret0, _ := ret[0].(*types0.TransactionInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // GetTransaction indicates an expected call of GetTransaction. func (mr *MockIStorageMockRecorder) GetTransaction(no any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTransaction", reflect.TypeOf((*MockIStorage)(nil).GetTransaction), no) } // HasAddress mocks base method. func (m *MockIStorage) HasAddress(address string) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasAddress", address) ret0, _ := ret[0].(bool) return ret0 } // HasAddress indicates an expected call of HasAddress. func (mr *MockIStorageMockRecorder) HasAddress(address any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasAddress", reflect.TypeOf((*MockIStorage)(nil).HasAddress), address) } // HasTransaction mocks base method. func (m *MockIStorage) HasTransaction(txID string) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasTransaction", txID) ret0, _ := ret[0].(bool) return ret0 } // HasTransaction indicates an expected call of HasTransaction. func (mr *MockIStorageMockRecorder) HasTransaction(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasTransaction", reflect.TypeOf((*MockIStorage)(nil).HasTransaction), txID) } // InsertAddress mocks base method. func (m *MockIStorage) InsertAddress(info *types0.AddressInfo) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InsertAddress", info) ret0, _ := ret[0].(error) return ret0 } // InsertAddress indicates an expected call of InsertAddress. func (mr *MockIStorageMockRecorder) InsertAddress(info any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InsertAddress", reflect.TypeOf((*MockIStorage)(nil).InsertAddress), info) } // InsertTransaction mocks base method. func (m *MockIStorage) InsertTransaction(info *types0.TransactionInfo) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InsertTransaction", info) ret0, _ := ret[0].(error) return ret0 } // InsertTransaction indicates an expected call of InsertTransaction. func (mr *MockIStorageMockRecorder) InsertTransaction(info any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InsertTransaction", reflect.TypeOf((*MockIStorage)(nil).InsertTransaction), info) } // IsLegacy mocks base method. func (m *MockIStorage) IsLegacy() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsLegacy") ret0, _ := ret[0].(bool) return ret0 } // IsLegacy indicates an expected call of IsLegacy. func (mr *MockIStorageMockRecorder) IsLegacy() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsLegacy", reflect.TypeOf((*MockIStorage)(nil).IsLegacy)) } // QueryTransactions mocks base method. func (m *MockIStorage) QueryTransactions(params QueryParams) ([]*types0.TransactionInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryTransactions", params) ret0, _ := ret[0].([]*types0.TransactionInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // QueryTransactions indicates an expected call of QueryTransactions. func (mr *MockIStorageMockRecorder) QueryTransactions(params any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryTransactions", reflect.TypeOf((*MockIStorage)(nil).QueryTransactions), params) } // SetDefaultFee mocks base method. func (m *MockIStorage) SetDefaultFee(fee amount.Amount) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetDefaultFee", fee) ret0, _ := ret[0].(error) return ret0 } // SetDefaultFee indicates an expected call of SetDefaultFee. func (mr *MockIStorageMockRecorder) SetDefaultFee(fee any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDefaultFee", reflect.TypeOf((*MockIStorage)(nil).SetDefaultFee), fee) } // UpdateAddress mocks base method. func (m *MockIStorage) UpdateAddress(info *types0.AddressInfo) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateAddress", info) ret0, _ := ret[0].(error) return ret0 } // UpdateAddress indicates an expected call of UpdateAddress. func (mr *MockIStorageMockRecorder) UpdateAddress(info any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAddress", reflect.TypeOf((*MockIStorage)(nil).UpdateAddress), info) } // UpdateTransactionStatus mocks base method. func (m *MockIStorage) UpdateTransactionStatus(no int64, status types0.TransactionStatus, blockHeight types.Height) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateTransactionStatus", no, status, blockHeight) ret0, _ := ret[0].(error) return ret0 } // UpdateTransactionStatus indicates an expected call of UpdateTransactionStatus. func (mr *MockIStorageMockRecorder) UpdateTransactionStatus(no, status, blockHeight any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTransactionStatus", reflect.TypeOf((*MockIStorage)(nil).UpdateTransactionStatus), no, status, blockHeight) } // UpdateVault mocks base method. func (m *MockIStorage) UpdateVault(arg0 *vault.Vault) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateVault", arg0) ret0, _ := ret[0].(error) return ret0 } // UpdateVault indicates an expected call of UpdateVault. func (mr *MockIStorageMockRecorder) UpdateVault(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVault", reflect.TypeOf((*MockIStorage)(nil).UpdateVault), arg0) } // Vault mocks base method. func (m *MockIStorage) Vault() *vault.Vault { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Vault") ret0, _ := ret[0].(*vault.Vault) return ret0 } // Vault indicates an expected call of Vault. func (mr *MockIStorageMockRecorder) Vault() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Vault", reflect.TypeOf((*MockIStorage)(nil).Vault)) } // WalletInfo mocks base method. func (m *MockIStorage) WalletInfo() *types0.WalletInfo { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WalletInfo") ret0, _ := ret[0].(*types0.WalletInfo) return ret0 } // WalletInfo indicates an expected call of WalletInfo. func (mr *MockIStorageMockRecorder) WalletInfo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WalletInfo", reflect.TypeOf((*MockIStorage)(nil).WalletInfo)) } ================================================ FILE: wallet/transactions.go ================================================ package wallet import ( "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/block" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/wallet/provider" "github.com/pactus-project/pactus/wallet/storage" wtypes "github.com/pactus-project/pactus/wallet/types" ) type transactions struct { storage storage.IStorage provider provider.IBlockchainProvider } func newTransactions(storage storage.IStorage, provider provider.IBlockchainProvider, ) transactions { return transactions{ storage: storage, provider: provider, } } // listTransactionsConfig contains options for listing transactions. type listTransactionsConfig struct { direction wtypes.TxDirection address string count int skip int } var defaultListTransactionsConfig = listTransactionsConfig{ direction: wtypes.TxDirectionAny, address: "*", count: 10, skip: 0, } // ListTransactionsOption is a functional option for ListTransactions. type ListTransactionsOption func(*listTransactionsConfig) // WithDirection filters transactions by direction (incoming or outgoing). func WithDirection(dir wtypes.TxDirection) ListTransactionsOption { return func(cfg *listTransactionsConfig) { cfg.direction = dir } } // WithAddress filters transactions by the specified address. func WithAddress(address string) ListTransactionsOption { return func(cfg *listTransactionsConfig) { if address != "" { cfg.address = address } } } // WithCount sets the maximum number of transactions to return. func WithCount(count int) ListTransactionsOption { return func(cfg *listTransactionsConfig) { if count > 0 { cfg.count = count } } } // WithSkip sets the number of transactions to skip. func WithSkip(skip int) ListTransactionsOption { return func(cfg *listTransactionsConfig) { if skip > 0 { cfg.skip = skip } } } func (t *transactions) ListTransactions(opts ...ListTransactionsOption) []*wtypes.TransactionInfo { if t.storage.IsLegacy() { return nil } cfg := defaultListTransactionsConfig for _, opt := range opts { opt(&cfg) } params := storage.QueryParams{ Address: cfg.address, Direction: cfg.direction, Count: cfg.count, Skip: cfg.skip, } txs, _ := t.storage.QueryTransactions(params) return txs } func (t *transactions) processEvent(event any) { if t.storage.IsLegacy() { return } switch evt := event.(type) { case *block.Block: t.processBlock(evt) case *tx.Tx: t.processTransaction(evt) default: // ignore other events } } func (t *transactions) processBlock(blk *block.Block) { pendingTxs := t.getPendingTransaction() for _, trx := range blk.Transactions() { txID := trx.ID().String() if _, ok := pendingTxs[txID]; ok { pendingInfo := pendingTxs[txID] if err := t.storage.UpdateTransactionStatus(pendingInfo.No, wtypes.TransactionStatusConfirmed, blk.Height()); err != nil { logger.Warn("failed to update transaction status", "error", err, "id", txID) } logger.Info("confirmed pending transaction", "id", trx.ID()) continue } _ = t.addTransactionWithStatus(trx, wtypes.TransactionStatusConfirmed, blk.Height()) } } func (t *transactions) processTransaction(trx *tx.Tx) { _ = t.addTransactionWithStatus(trx, wtypes.TransactionStatusPending, 0) } func (t *transactions) getPendingTransaction() map[string]*wtypes.TransactionInfo { pendingTxs, err := t.storage.GetPendingTransactions() if err != nil { logger.Warn("failed to get pending transactions", "error", err) return nil } for _, pendingInfo := range pendingTxs { trx, err := tx.FromBytes(pendingInfo.Data) if err != nil { continue } err = t.provider.CheckTransaction(pendingInfo.Data) if err != nil { logger.Warn("pending transaction is invalid", "error", err, "id", pendingInfo.TxID) if err := t.storage.UpdateTransactionStatus(pendingInfo.No, wtypes.TransactionStatusFailed, 0); err != nil { logger.Warn("failed to update transaction status", "error", err, "id", pendingInfo.TxID) } continue } // Re-broadcast the transaction _, err = t.provider.SendTx(trx) if err != nil { logger.Debug("failed to re-broadcast pending transaction", "error", err, "id", pendingInfo.TxID) continue } } return pendingTxs } func (t *transactions) AddTransactionByID(txID tx.ID) error { if t.storage.IsLegacy() { return nil } idStr := txID.String() if t.storage.HasTransaction(idStr) { return ErrTransactionExists } trx, height, err := t.provider.GetTransaction(idStr) if err != nil { return err } return t.addTransactionWithStatus(trx, wtypes.TransactionStatusConfirmed, height) } func (t *transactions) addTransactionWithStatus(trx *tx.Tx, status wtypes.TransactionStatus, blockHeight types.Height, ) error { txInfos, err := wtypes.MakeTransactionInfos(trx, status, blockHeight) if err != nil { return err } for _, info := range txInfos { if t.storage.HasAddress(info.Sender) { info.Direction = wtypes.TxDirectionOutgoing } else if t.storage.HasAddress(info.Receiver) { info.Direction = wtypes.TxDirectionIncoming } else { continue } if err := t.storage.InsertTransaction(info); err != nil { logger.Warn("failed to insert transaction into storage", "error", err, "id", trx.ID()) return err } logger.Info("added outgoing transaction to wallet", "id", trx.ID(), "status", status, "blockHeight", blockHeight) } return nil } ================================================ FILE: wallet/transactions_test.go ================================================ package wallet import ( "errors" "testing" "github.com/pactus-project/pactus/types" wtypes "github.com/pactus-project/pactus/wallet/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) func TestTransactionsListOptions(t *testing.T) { tests := []struct { opts []ListTransactionsOption expDir wtypes.TxDirection expAddr string expCount int expSkip int }{ { opts: []ListTransactionsOption{}, expDir: wtypes.TxDirectionAny, expAddr: "*", expCount: 10, expSkip: 0, }, { opts: []ListTransactionsOption{ WithDirection(wtypes.TxDirectionAny), WithAddress(""), WithCount(-1), WithSkip(-1), }, expDir: wtypes.TxDirectionAny, expAddr: "*", expCount: 10, expSkip: 0, }, { opts: []ListTransactionsOption{ WithDirection(wtypes.TxDirectionOutgoing), WithAddress("*"), WithCount(0), WithSkip(0), }, expDir: wtypes.TxDirectionOutgoing, expAddr: "*", expCount: 10, expSkip: 0, }, { opts: []ListTransactionsOption{ WithDirection(wtypes.TxDirectionIncoming), WithAddress("addr1"), WithCount(5), WithSkip(2), }, expDir: wtypes.TxDirectionIncoming, expAddr: "addr1", expCount: 5, expSkip: 2, }, } for _, tt := range tests { cfg := defaultListTransactionsConfig for _, opt := range tt.opts { opt(&cfg) } assert.Equal(t, tt.expDir, cfg.direction) assert.Equal(t, tt.expAddr, cfg.address) assert.Equal(t, tt.expCount, cfg.count) assert.Equal(t, tt.expSkip, cfg.skip) } } func TestAddTransaction(t *testing.T) { td := setup(t) t.Run("add non-existent transaction returns error", func(t *testing.T) { txID := td.RandHash() td.mockStorage.EXPECT().IsLegacy().Return(false) td.mockStorage.EXPECT().HasTransaction(txID.String()).Return(false) td.mockProvider.EXPECT(). GetTransaction(txID.String()). Return(nil, types.Height(0), errors.New("not exists")) err := td.wallet.AddTransactionByID(txID) require.Error(t, err) }) t.Run("transaction already exists in storage", func(t *testing.T) { txID := td.RandHash() td.mockStorage.EXPECT().IsLegacy().Return(false) td.mockStorage.EXPECT().HasTransaction(txID.String()).Return(true) err := td.wallet.AddTransactionByID(txID) require.ErrorIs(t, err, ErrTransactionExists) }) t.Run("add new transaction successfully", func(t *testing.T) { trx := td.GenerateTestTransferTx() td.mockStorage.EXPECT().IsLegacy().Return(false) td.mockStorage.EXPECT().HasTransaction(trx.ID().String()).Return(false) td.mockProvider.EXPECT(). GetTransaction(trx.ID().String()). Return(trx, td.RandHeight(), nil) td.mockStorage.EXPECT().HasAddress(gomock.Any()).Return(true) td.mockStorage.EXPECT().InsertTransaction(gomock.Any()).Return(nil) err := td.wallet.AddTransactionByID(trx.ID()) require.NoError(t, err) }) } ================================================ FILE: wallet/tx_builder.go ================================================ package wallet import ( "errors" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/wallet/provider" ) // TxOption defines a function type used to apply options to a txBuilder. type TxOption func(builder *txBuilder) error // OptionLockTime sets the lock time for the transaction. func OptionLockTime(lockTime types.Height) func(builder *txBuilder) error { return func(builder *txBuilder) error { builder.lockTime = lockTime return nil } } // OptionFee sets the transaction fee using a string input. func OptionFee(feeStr string) func(builder *txBuilder) error { return func(builder *txBuilder) error { if feeStr == "" { return nil } fee, err := amount.FromString(feeStr) if err != nil { return err } builder.fee = fee return nil } } // OptionMemo sets a memo or note for the transaction. func OptionMemo(memo string) func(builder *txBuilder) error { return func(builder *txBuilder) error { builder.memo = memo return nil } } // OptionDelegateOwner sets delegation owner address for bond/unbond transactions. func OptionDelegateOwner(owner string) func(builder *txBuilder) error { return func(builder *txBuilder) error { if owner == "" { return nil } delegateOwner, err := crypto.AddressFromString(owner) if err != nil { return err } builder.delegateOwner = &delegateOwner return nil } } // OptionDelegateShare sets delegation owner reward share for delegated bond transactions. func OptionDelegateShare(shareStr string) func(builder *txBuilder) error { return func(builder *txBuilder) error { if shareStr == "" { return nil } share, err := amount.FromString(shareStr) if err != nil { return err } builder.delegateShare = share return nil } } // OptionDelegateExpiry sets delegation expiry height for delegated bond transactions. func OptionDelegateExpiry(expiry types.Height) func(builder *txBuilder) error { return func(builder *txBuilder) error { builder.delegateExpiry = expiry return nil } } // txBuilder helps build and configure a transaction before submitting it. type txBuilder struct { provider provider.IBlockchainProvider sender *crypto.Address receiver *crypto.Address pub *bls.PublicKey delegateOwner *crypto.Address delegateShare amount.Amount delegateExpiry types.Height typ payload.Type lockTime types.Height amount amount.Amount fee amount.Amount memo string } // setSenderAddr sets the sender's address for the transaction. func (m *txBuilder) setSenderAddr(addr string) error { sender, err := crypto.AddressFromString(addr) if err != nil { return err } m.sender = &sender return nil } // setReceiverAddress sets the recipient's address for the transaction. func (m *txBuilder) setReceiverAddress(addr string) error { receiver, err := crypto.AddressFromString(addr) if err != nil { return err } m.receiver = &receiver return nil } // setPublicKey sets the public key for the transaction, typically used in bond transactions. func (m *txBuilder) setPublicKey(pubStr string) error { pub, err := bls.PublicKeyFromString(pubStr) if err != nil { return err } m.pub = pub return nil } // build constructs and finalizes the transaction, selecting the appropriate type based on the builder's configuration. func (m *txBuilder) build() (*tx.Tx, error) { err := m.setLockTime() if err != nil { return nil, err } var trx *tx.Tx switch m.typ { case payload.TypeTransfer: trx = tx.NewTransferTx(m.lockTime, *m.sender, *m.receiver, m.amount, m.fee, tx.WithMemo(m.memo)) case payload.TypeBond: pub := m.pub val, _ := m.provider.GetValidator(m.receiver.String()) if val != nil { // validator exists pub = nil } trx = tx.NewBondTx(m.lockTime, *m.sender, *m.receiver, pub, m.amount, m.fee, tx.WithMemo(m.memo)) if m.delegateOwner != nil { bondPld := trx.Payload().(*payload.BondPayload) bondPld.DelegateOwner = *m.delegateOwner bondPld.DelegateShare = m.delegateShare bondPld.DelegateExpiry = m.delegateExpiry } case payload.TypeUnbond: trx = tx.NewUnbondTx(m.lockTime, *m.sender, tx.WithMemo(m.memo)) if m.delegateOwner != nil { unbondPld := trx.Payload().(*payload.UnbondPayload) unbondPld.DelegateOwner = *m.delegateOwner } case payload.TypeWithdraw: trx = tx.NewWithdrawTx(m.lockTime, *m.sender, *m.receiver, m.amount, m.fee, tx.WithMemo(m.memo)) case payload.TypeBatchTransfer: return nil, errors.New("BatchTransfer is not implemented yet") case payload.TypeSortition: return nil, errors.New("unable to build sortition transactions") } return trx, nil } // setLockTime assigns a lock time to the transaction. // If not provided, it retrieves the last block height and increments it. func (m *txBuilder) setLockTime() error { if m.lockTime == 0 { height, err := m.provider.LastBlockHeight() if err != nil { return err } m.lockTime = height + 1 } return nil } ================================================ FILE: wallet/types/types.go ================================================ package types import ( "fmt" "time" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" ) // WalletInfo represents the information about the wallet. type WalletInfo struct { Version int Driver string Path string Network genesis.ChainType DefaultFee amount.Amount UUID string Encrypted bool Neutered bool CreatedAt time.Time } // AddressInfo represents the information about a wallet address. type AddressInfo struct { Address string `json:"address"` PublicKey string `json:"public_key"` Label string `json:"label"` Path string `json:"path"` CreatedAt time.Time `json:"-"` UpdatedAt time.Time `json:"-"` } type TransactionStatus int const ( TransactionStatusFailed = TransactionStatus(-1) TransactionStatusPending = TransactionStatus(0) TransactionStatusConfirmed = TransactionStatus(1) ) func (ts TransactionStatus) String() string { switch ts { case TransactionStatusFailed: return "failed" case TransactionStatusPending: return "pending" case TransactionStatusConfirmed: return "confirmed" default: return "unknown" } } // TxDirection indicates whether to include incoming or outgoing transactions. type TxDirection int const ( // TxDirectionAny includes both incoming and outgoing transactions. TxDirectionAny TxDirection = 0 // TxDirectionIncoming includes only incoming transactions where the wallet receives funds. TxDirectionIncoming = 1 // TxDirectionOutgoing includes only outgoing transactions where the wallet sends funds. TxDirectionOutgoing = 2 ) func (dir TxDirection) String() string { switch dir { case TxDirectionAny: return "any" case TxDirectionIncoming: return "incoming" case TxDirectionOutgoing: return "outgoing" default: return "unknown" } } type TransactionInfo struct { No int64 TxID string Sender string Receiver string Direction TxDirection Amount amount.Amount Fee amount.Amount Memo string Status TransactionStatus BlockHeight types.Height PayloadType payload.Type Data []byte Comment string CreatedAt time.Time UpdatedAt time.Time } // MakeTransactionInfos builds one or more TransactionInfo entries from the given transaction. // // It may return multiple entries (one per recipient) to support batch transfer transactions. // Note that the caller is responsible for setting the transaction direction. func MakeTransactionInfos(trx *tx.Tx, status TransactionStatus, blockHeight types.Height) ([]*TransactionInfo, error) { data, err := trx.Bytes() if err != nil { return nil, fmt.Errorf("failed to serialize tx: %w", err) } receivers := make([]string, 0) switch pld := trx.Payload().(type) { case *payload.TransferPayload: receivers = append(receivers, pld.To.String()) case *payload.BondPayload: receivers = append(receivers, pld.To.String()) case *payload.UnbondPayload: receivers = append(receivers, pld.Validator.String()) case *payload.WithdrawPayload: receivers = append(receivers, pld.To.String()) case *payload.SortitionPayload: receivers = append(receivers, "") case *payload.BatchTransferPayload: for _, recipient := range pld.Recipients { receivers = append(receivers, recipient.To.String()) } } infos := make([]*TransactionInfo, len(receivers)) for i, receiver := range receivers { infos[i] = &TransactionInfo{ TxID: trx.ID().String(), Sender: trx.Payload().Signer().String(), Receiver: receiver, Direction: TxDirectionAny, Amount: trx.Payload().Value(), Fee: trx.Fee(), Memo: trx.Memo(), Status: status, BlockHeight: blockHeight, PayloadType: trx.Payload().Type(), Data: data, } } return infos, nil } ================================================ FILE: wallet/vault/errors.go ================================================ package vault import ( "errors" ) var ( // ErrInvalidPath describes an error in which the key path is invalid. ErrInvalidPath = errors.New("the key path is invalid") // ErrNeutered describes an error in which the wallet is neutered. ErrNeutered = errors.New("wallet is neutered") // ErrUnsupportedPurpose describes an error in which the purpose is not supported. ErrUnsupportedPurpose = errors.New("unsupported purpose") ) ================================================ FILE: wallet/vault/utils.go ================================================ package vault import ( "github.com/pactus-project/pactus/util/bip39" ) // GenerateMnemonic generates a new mnemonic (seed phrase) based on BIP-39 // https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki func GenerateMnemonic(bitSize int) (string, error) { entropy, err := bip39.NewEntropy(bitSize) if err != nil { return "", err } return bip39.NewMnemonic(entropy) } // CheckMnemonic validates a mnemonic (seed phrase) based on BIP-39. func CheckMnemonic(mnemonic string) error { _, err := bip39.EntropyFromMnemonic(mnemonic) return err } ================================================ FILE: wallet/vault/utils_test.go ================================================ package vault import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGenerateMnemonic(t *testing.T) { _, err := GenerateMnemonic(127) require.Error(t, err, "low entropy") _, err = GenerateMnemonic(128) require.NoError(t, err) _, err = GenerateMnemonic(257) require.Error(t, err, "high entropy") _, err = GenerateMnemonic(256) require.NoError(t, err) } func TestValidateMnemonic(t *testing.T) { tests := []struct { mnenomic string errStr string }{ { "", "invalid mnenomic", }, { "abandon ability able about above absent absorb abstract absurd abuse access", "invalid mnenomic", }, { "bandon ability able about above absent absorb abstract absurd abuse access ability", "word `bandon` not found in reverse map", }, { "abandon ability able about above absent absorb abstract absurd abuse access accident", "checksum incorrect", }, { "abandon ability able about above absent absorb abstract absurd abuse access ability", "", }, } for no, tt := range tests { err := CheckMnemonic(tt.mnenomic) if err != nil { assert.Equal(t, tt.errStr, err.Error(), "test %v failed", no) } } } ================================================ FILE: wallet/vault/vault.go ================================================ package vault import ( "context" "encoding/json" "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" blshdkeychain "github.com/pactus-project/pactus/crypto/bls/hdkeychain" "github.com/pactus-project/pactus/crypto/ed25519" ed25519hdkeychain "github.com/pactus-project/pactus/crypto/ed25519/hdkeychain" "github.com/pactus-project/pactus/util/bip39" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/encrypter" "github.com/pactus-project/pactus/wallet/types" ) // // Deterministic Hierarchical Derivation Path // // Overview: // // This specification defines a hierarchical derivation path for generating addresses, based on BIP32. // The path is structured into four distinct levels: // // m / purpose' / coin_type' / address_type' / address_index // // Explanation: // // `m` Denotes the master node (or root) of the tree // `'` Apostrophe in the path indicates that BIP32 hardened derivation is used. // `/` Separates the tree into depths, thus i / j signifies that j is a child of i // // Path Components: // // * `purpose`: Indicates the specific use case for the derived addresses: // - 12381: Used for the BLS12-381 curve, based on PIP-8. // - 65535: Used for imported private keys, based on PIP-13. // - 44: A comprehensive purpose for standard curves, based on BIP-44. // // * `coin_type`: Identifies the coin type: // - 21888: Pactus Mainnet // - 21777: Pactus Testnet // // * `address_type`: Specifies the type of address. // // * `address_index`: A sequential number and increase when a new address is derived. // // References: // - https://pips.pactus.org/PIPs/pip-8 // - https://pips.pactus.org/PIPs/pip-13 // - https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki // // VaultType represents the type of vault. type VaultType int const ( TypeFull VaultType = iota + 1 // Full vault with private keys. TypeNeutered // Neutered vault without private keys. ) // String returns the string representation of the VaultType. func (vt VaultType) String() string { switch vt { case TypeFull: return "Full" case TypeNeutered: return "Neutered" default: return "Unknown" } } // AddressGapLimit is the maximum number of consecutive inactive addresses before stopping recovery. const AddressGapLimit = 8 type Vault struct { Type VaultType `json:"type"` // Vault type: Full or Neutered CoinType addresspath.CoinType `json:"coin_type"` // Coin type: 21888 for Mainnet, 21777 for Testnet Encrypter encrypter.Encrypter `json:"encrypter"` // Encryption algorithm KeyStore string `json:"key_store"` // KeyStore that stores the secrets and encrypts using Encrypter Purposes Purposes `json:"purposes"` // Contains Purposes of the vault } type keyStore struct { MasterNode masterNode `json:"master_node"` // HD Root Tree (Master node) ImportedKeys []string `json:"imported_keys"` // Imported private keys } type masterNode struct { Mnemonic string `json:"seed,omitempty"` // Seed phrase or mnemonic (encrypted) } type Purposes struct { PurposeBLS purposeBLS `json:"purpose_bls"` // BLS Purpose: m/12381'/21888'/1' or 2'/0 PurposeBIP44 purposeBIP44 `json:"purpose_bip44"` // BIP44 Purpose: m/44'/21888'/3'/0' } type purposeBLS struct { XPubValidator string `json:"xpub_account"` // Extended public key for account: m/12381'/21888'/1'/0 XPubAccount string `json:"xpub_validator"` // Extended public key for validator: m/12381'/21888'/2'/0 NextAccountIndex uint32 `json:"next_account_index"` // Index of next derived account NextValidatorIndex uint32 `json:"next_validator_index"` // Index of next derived validator } type purposeBIP44 struct { NextEd25519Index uint32 `json:"next_ed25519_index"` // Index of next Ed25519 derived account: m/44'/21888/3'/0' } func CreateVaultFromMnemonic(mnemonic string, coinType addresspath.CoinType) (*Vault, error) { seed, err := bip39.NewSeedWithErrorChecking(mnemonic, "") if err != nil { return nil, err } masterKey, err := blshdkeychain.NewMaster(seed, false) if err != nil { return nil, err } enc := encrypter.NopeEncrypter() xPubValidator, err := masterKey.DerivePath([]uint32{ addresspath.Harden(addresspath.PurposeBLS12381), addresspath.Harden(coinType), addresspath.Harden(crypto.AddressTypeValidator), }) if err != nil { return nil, err } xPubAccount, err := masterKey.DerivePath([]uint32{ addresspath.Harden(addresspath.PurposeBLS12381), addresspath.Harden(coinType), addresspath.Harden(crypto.AddressTypeBLSAccount), }) if err != nil { return nil, err } store := keyStore{ MasterNode: masterNode{ Mnemonic: mnemonic, }, ImportedKeys: make([]string, 0), } storeDate, err := json.Marshal(store) if err != nil { return nil, err } return &Vault{ Type: TypeFull, CoinType: coinType, Encrypter: enc, KeyStore: string(storeDate), Purposes: Purposes{ PurposeBLS: purposeBLS{ XPubValidator: xPubValidator.Neuter().String(), XPubAccount: xPubAccount.Neuter().String(), }, }, }, nil } func (v *Vault) Neuter() { v.Type = TypeNeutered v.Encrypter = encrypter.NopeEncrypter() v.KeyStore = "" } func (v *Vault) IsNeutered() bool { return v.Type == TypeNeutered } func (v *Vault) UpdatePassword(oldPassword, newPassword string, opts ...encrypter.Option) error { if v.IsNeutered() { return ErrNeutered } keyStore, err := v.decryptKeyStore(oldPassword) if err != nil { return err } newEncrypter := encrypter.NopeEncrypter() if newPassword != "" { newEncrypter = encrypter.DefaultEncrypter(opts...) } v.Encrypter = newEncrypter err = v.encryptKeyStore(keyStore, newPassword) if err != nil { return err } v.Encrypter = newEncrypter return nil } func (v *Vault) IsEncrypted() bool { return v.Encrypter.IsEncrypted() } func (v *Vault) ImportBLSPrivateKey(password string, prv *bls.PrivateKey) ( valInfo *types.AddressInfo, accInfo *types.AddressInfo, err error, ) { if v.IsNeutered() { return nil, nil, ErrNeutered } keyStore, err := v.decryptKeyStore(password) if err != nil { return nil, nil, err } pub := prv.PublicKeyNative() addressIndex := len(keyStore.ImportedKeys) blsAccPathStr := addresspath.NewPath( addresspath.Harden(addresspath.PurposeImportPrivateKey), addresspath.Harden(v.CoinType), addresspath.Harden(crypto.AddressTypeBLSAccount), addresspath.Harden(addressIndex)).String() blsValidatorPathStr := addresspath.NewPath( addresspath.Harden(addresspath.PurposeImportPrivateKey), addresspath.Harden(v.CoinType), addresspath.Harden(crypto.AddressTypeValidator), addresspath.Harden(addressIndex)).String() accInfo = &types.AddressInfo{ Address: pub.AccountAddress().String(), PublicKey: pub.String(), Label: "Imported BLS Account Address", Path: blsAccPathStr, } valInfo = &types.AddressInfo{ Address: pub.ValidatorAddress().String(), PublicKey: pub.String(), Label: "Imported Validator Address", Path: blsValidatorPathStr, } keyStore.ImportedKeys = append(keyStore.ImportedKeys, prv.String()) err = v.encryptKeyStore(keyStore, password) if err != nil { return nil, nil, err } return valInfo, accInfo, nil } func (v *Vault) ImportEd25519PrivateKey(password string, prv *ed25519.PrivateKey) (*types.AddressInfo, error) { if v.IsNeutered() { return nil, ErrNeutered } keyStore, err := v.decryptKeyStore(password) if err != nil { return nil, err } addressIndex := len(keyStore.ImportedKeys) pub := prv.PublicKeyNative() accPathStr := addresspath.NewPath( addresspath.Harden(addresspath.PurposeImportPrivateKey), addresspath.Harden(v.CoinType), addresspath.Harden(crypto.AddressTypeEd25519Account), addresspath.Harden(addressIndex)).String() accInfo := &types.AddressInfo{ Address: pub.AccountAddress().String(), PublicKey: pub.String(), Label: "Imported Ed25519 Account Address", Path: accPathStr, } keyStore.ImportedKeys = append(keyStore.ImportedKeys, prv.String()) err = v.encryptKeyStore(keyStore, password) if err != nil { return nil, err } return accInfo, nil } // PrivateKeys retrieves the private keys for the given addresses using the provided password. func (v *Vault) PrivateKeys(password string, paths []addresspath.Path) ([]crypto.PrivateKey, error) { if v.IsNeutered() { return nil, ErrNeutered } // Decrypt the key store once to avoid decrypting for each key. keyStore, err := v.decryptKeyStore(password) if err != nil { return nil, err } seed := bip39.NewSeed(keyStore.MasterNode.Mnemonic, "") keys := make([]crypto.PrivateKey, len(paths)) for i, path := range paths { switch path.Purpose() { case addresspath.PurposeBLS12381: prvKey, err := v.deriveBLSPrivateKey(seed, path) if err != nil { return nil, err } keys[i] = prvKey case addresspath.PurposeBIP44: prvKey, err := v.deriveEd25519PrivateKey(seed, path) if err != nil { return nil, err } keys[i] = prvKey case addresspath.PurposeImportPrivateKey: index := addresspath.UnHarden(path.AddressIndex()) str := keyStore.ImportedKeys[index] var prv crypto.PrivateKey switch uint32(path.AddressType()) { case uint32(crypto.AddressTypeValidator), uint32(crypto.AddressTypeBLSAccount): prv, err = bls.PrivateKeyFromString(str) if err != nil { return nil, err } case uint32(crypto.AddressTypeEd25519Account): prv, err = ed25519.PrivateKeyFromString(str) if err != nil { return nil, err } } keys[i] = prv default: return nil, ErrUnsupportedPurpose } } return keys, nil } func (v *Vault) NewValidatorAddress(label string) (*types.AddressInfo, error) { ext, err := blshdkeychain.NewKeyFromString(v.Purposes.PurposeBLS.XPubValidator) if err != nil { return nil, err } index := v.Purposes.PurposeBLS.NextValidatorIndex ext, err = ext.DerivePath([]uint32{index}) if err != nil { return nil, err } blsPubKey, err := bls.PublicKeyFromBytes(ext.RawPublicKey()) if err != nil { return nil, err } addr := blsPubKey.ValidatorAddress().String() info := types.AddressInfo{ Address: addr, Label: label, PublicKey: blsPubKey.String(), Path: addresspath.NewPath(ext.Path()...).String(), } v.Purposes.PurposeBLS.NextValidatorIndex++ return &info, nil } func (v *Vault) NewBLSAccountAddress(label string) (*types.AddressInfo, error) { ext, err := blshdkeychain.NewKeyFromString(v.Purposes.PurposeBLS.XPubAccount) if err != nil { return nil, err } index := v.Purposes.PurposeBLS.NextAccountIndex info, err := v.deriveBLSAccountAddressAt(ext, index, label) if err != nil { return nil, err } v.Purposes.PurposeBLS.NextAccountIndex++ return info, nil } func (*Vault) deriveBLSAccountAddressAt(ext *blshdkeychain.ExtendedKey, index uint32, label string, ) (*types.AddressInfo, error) { ext, err := ext.DerivePath([]uint32{index}) if err != nil { return nil, err } blsPubKey, err := bls.PublicKeyFromBytes(ext.RawPublicKey()) if err != nil { return nil, err } addr := blsPubKey.AccountAddress().String() info := types.AddressInfo{ Address: addr, Label: label, PublicKey: blsPubKey.String(), Path: addresspath.NewPath(ext.Path()...).String(), } return &info, nil } func (v *Vault) NewEd25519AccountAddress(label, password string) (*types.AddressInfo, error) { seed, err := v.MnemonicSeed(password) if err != nil { return nil, err } masterKey, err := ed25519hdkeychain.NewMaster(seed) if err != nil { return nil, err } index := v.Purposes.PurposeBIP44.NextEd25519Index info, err := v.deriveEd25519AccountAddressAt(masterKey, index, label) if err != nil { return nil, err } v.Purposes.PurposeBIP44.NextEd25519Index++ return info, nil } func (v *Vault) deriveEd25519AccountAddressAt(masterKey *ed25519hdkeychain.ExtendedKey, index uint32, label string, ) (*types.AddressInfo, error) { ext, err := masterKey.DerivePath([]uint32{ addresspath.Harden(addresspath.PurposeBIP44), addresspath.Harden(v.CoinType), addresspath.Harden(crypto.AddressTypeEd25519Account), addresspath.Harden(index), }) if err != nil { return nil, err } ed25519PubKey, err := ed25519.PublicKeyFromBytes(ext.RawPublicKey()) if err != nil { return nil, err } addr := ed25519PubKey.AccountAddress().String() info := types.AddressInfo{ Address: addr, Label: label, PublicKey: ed25519PubKey.String(), Path: addresspath.NewPath(ext.Path()...).String(), } return &info, nil } func (v *Vault) Mnemonic(password string) (string, error) { keyStore, err := v.decryptKeyStore(password) if err != nil { return "", err } return keyStore.MasterNode.Mnemonic, nil } func (v *Vault) MnemonicSeed(password string) ([]byte, error) { mnemonic, err := v.Mnemonic(password) if err != nil { return nil, err } seed := bip39.NewSeed(mnemonic, "") return seed, nil } func (v *Vault) decryptKeyStore(password string) (*keyStore, error) { if v.IsNeutered() { return nil, ErrNeutered } keyStoreData, err := v.Encrypter.Decrypt(v.KeyStore, password) if err != nil { return nil, err } keyStore := new(keyStore) err = json.Unmarshal([]byte(keyStoreData), keyStore) if err != nil { return nil, err } return keyStore, nil } func (v *Vault) encryptKeyStore(keyStore *keyStore, password string) error { keyStoreData, err := json.Marshal(keyStore) if err != nil { return err } keyStoreEnc, err := v.Encrypter.Encrypt(string(keyStoreData), password) if err != nil { return err } v.KeyStore = keyStoreEnc return nil } func (*Vault) deriveBLSPrivateKey(mnemonicSeed []byte, path []uint32) (*bls.PrivateKey, error) { masterKey, err := blshdkeychain.NewMaster(mnemonicSeed, false) if err != nil { return nil, err } ext, err := masterKey.DerivePath(path) if err != nil { return nil, err } prvBytes, err := ext.RawPrivateKey() if err != nil { return nil, err } return bls.PrivateKeyFromBytes(prvBytes) } func (*Vault) deriveEd25519PrivateKey(mnemonicSeed []byte, path []uint32) (*ed25519.PrivateKey, error) { masterKey, err := ed25519hdkeychain.NewMaster(mnemonicSeed) if err != nil { return nil, err } ext, err := masterKey.DerivePath(path) if err != nil { return nil, err } prvBytes := ext.RawPrivateKey() return ed25519.PrivateKeyFromBytes(prvBytes) } // RecoverAddresses automatically recovers used addresses when restoring a wallet from a mnemonic phrase. // This implementation follows PIP-41 specification for address recovery. // // The function recovers both BLS and Ed25519 account addresses, with Ed25519 being the default // address type for recovery when the wallet is empty. // // An address is considered active if its public key is stored in the blockchain database. // The hasActivity function should return true if the address has been used before. // // Limitation: Users cannot automatically recover a used address if it is separated by more than 8 // inactive or empty addresses. In this case, manual address creation is required. // // Reference: https://pips.pactus.org/PIPs/pip-41 func (v *Vault) RecoverAddresses(ctx context.Context, password string, hasActivity func(addr string) (bool, error), ) ([]types.AddressInfo, error) { recovered1, err := v.recoverBLSAccountAddresses(ctx, hasActivity) if err != nil { return nil, err } recovered2, err := v.recoverEd25519AccountAddresses(ctx, password, hasActivity) if err != nil { return nil, err } recovered1 = append(recovered1, recovered2...) return recovered1, nil } // scanRecoveredCount scans derived addresses until the gap limit is exceeded and // returns how many addresses should be recovered according to PIP-41. func (*Vault) scanRecoveredCount( ctx context.Context, startIndex uint32, deriveAt func(index uint32) (*types.AddressInfo, error), hasActivity func(addr string) (bool, error), ) (int, error) { recoveredCount := 0 inactiveCount := 1 currentIndex := startIndex info, err := deriveAt(currentIndex) if err != nil { return 0, err } for { select { case <-ctx.Done(): return 0, ctx.Err() default: } isActive, err := hasActivity(info.Address) if err != nil { return 0, err } if isActive { recoveredCount += inactiveCount inactiveCount = 1 } else { inactiveCount++ if inactiveCount > AddressGapLimit { break } } currentIndex++ info, err = deriveAt(currentIndex) if err != nil { return 0, err } } return recoveredCount, nil } // recoverBLSAccountAddresses recovers BLS account addresses following the PIP-41 specification. func (v *Vault) recoverBLSAccountAddresses(ctx context.Context, hasActivity func(addrs string) (bool, error), ) ([]types.AddressInfo, error) { ext, err := blshdkeychain.NewKeyFromString(v.Purposes.PurposeBLS.XPubAccount) if err != nil { return nil, err } recoveredCount, err := v.scanRecoveredCount( ctx, v.Purposes.PurposeBLS.NextAccountIndex, func(index uint32) (*types.AddressInfo, error) { return v.deriveBLSAccountAddressAt(ext, index, "") }, hasActivity, ) if err != nil { return nil, err } recovered := make([]types.AddressInfo, 0, recoveredCount) for i := 0; i < recoveredCount; i++ { info, _ := v.NewBLSAccountAddress(fmt.Sprintf("BLS Account Address %d", i)) recovered = append(recovered, *info) } return recovered, nil } // recoverEd25519AccountAddresses recovers Ed25519 account addresses following the PIP-41 specification. func (v *Vault) recoverEd25519AccountAddresses(ctx context.Context, password string, hasActivity func(addrs string) (bool, error), ) ([]types.AddressInfo, error) { seed, err := v.MnemonicSeed(password) if err != nil { return nil, err } masterKey, err := ed25519hdkeychain.NewMaster(seed) if err != nil { return nil, err } recoveredCount, err := v.scanRecoveredCount( ctx, v.Purposes.PurposeBIP44.NextEd25519Index, func(index uint32) (*types.AddressInfo, error) { return v.deriveEd25519AccountAddressAt(masterKey, index, "") }, hasActivity, ) if err != nil { return nil, err } recovered := make([]types.AddressInfo, 0, recoveredCount) for i := 0; i < recoveredCount; i++ { info, _ := v.NewEd25519AccountAddress(fmt.Sprintf("Ed25519 Account Address %d", i), password) recovered = append(recovered, *info) } return recovered, nil } ================================================ FILE: wallet/vault/vault_test.go ================================================ package vault import ( "context" "errors" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/encrypter" "github.com/pactus-project/pactus/wallet/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite vault *Vault mnemonic string password string testAddrs []*types.AddressInfo } // setup returns an instances of vault fo testing. func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) password := ts.RandString(32) mnemonic, _ := GenerateMnemonic(128) vault, err := CreateVaultFromMnemonic(mnemonic, 21888) require.NoError(t, err) // Create some test address addr1, err := vault.NewBLSAccountAddress("bls-account-address") require.NoError(t, err) addr2, err := vault.NewEd25519AccountAddress("ed25519-account-address", "") require.NoError(t, err) addr3, err := vault.NewValidatorAddress("validator-address") require.NoError(t, err) _, importedBLSPrv := ts.RandBLSKeyPair() addr4, addr5, err := vault.ImportBLSPrivateKey("", importedBLSPrv) require.NoError(t, err) _, importedEd25519Prv := ts.RandEd25519KeyPair() addr6, err := vault.ImportEd25519PrivateKey("", importedEd25519Prv) require.NoError(t, err) testAddrs := []*types.AddressInfo{addr1, addr2, addr3, addr4, addr5, addr6} assert.False(t, vault.IsEncrypted()) // Set encryption options to minimal values for faster test execution. opts := []encrypter.Option{ encrypter.OptionIteration(1), encrypter.OptionMemory(8), encrypter.OptionParallelism(1), } err = vault.UpdatePassword("", password, opts...) require.NoError(t, err) assert.True(t, vault.IsEncrypted()) return &testData{ TestSuite: ts, vault: vault, password: password, mnemonic: mnemonic, testAddrs: testAddrs, } } func TestCreateVaultFromMnemonic(t *testing.T) { td := setup(t) t.Run("Invalid mnemonic", func(t *testing.T) { _, err := CreateVaultFromMnemonic("invalid mnemonic phrase seed", 21888) require.Error(t, err) }) t.Run("Ok", func(t *testing.T) { recovered, err := CreateVaultFromMnemonic(td.mnemonic, 21888) require.NoError(t, err) vaultMnemonic, err := recovered.Mnemonic("") require.NoError(t, err) assert.Equal(t, vaultMnemonic, td.mnemonic) assert.Zero(t, recovered.Purposes.PurposeBLS.NextAccountIndex) assert.Zero(t, recovered.Purposes.PurposeBLS.NextValidatorIndex) assert.Zero(t, recovered.Purposes.PurposeBIP44.NextEd25519Index) // Recover addresses _, err = recovered.NewBLSAccountAddress("bls-account-address") require.NoError(t, err) _, err = recovered.NewEd25519AccountAddress("ed25519-account-address", "") require.NoError(t, err) _, err = recovered.NewValidatorAddress("validator-address") require.NoError(t, err) assert.Equal(t, recovered.Purposes, td.vault.Purposes) }) } func TestGetPrivateKeys(t *testing.T) { td := setup(t) t.Run("Unknown purpose", func(t *testing.T) { path, _ := addresspath.FromString("m/0") _, err := td.vault.PrivateKeys(td.password, []addresspath.Path{path}) require.ErrorIs(t, err, ErrUnsupportedPurpose) }) t.Run("No password", func(t *testing.T) { path, _ := addresspath.FromString("m/44/21888/3/0") _, err := td.vault.PrivateKeys("", []addresspath.Path{path}) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Invalid password", func(t *testing.T) { path, _ := addresspath.FromString("m/44/21888/3/0") _, err := td.vault.PrivateKeys("wrong_password", []addresspath.Path{path}) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Check all the private keys", func(t *testing.T) { for _, info := range td.testAddrs { path, _ := addresspath.FromString(info.Path) prv, err := td.vault.PrivateKeys(td.password, []addresspath.Path{path}) require.NoError(t, err) switch path.AddressType() { case crypto.AddressTypeBLSAccount, crypto.AddressTypeValidator: pub, _ := bls.PublicKeyFromString(info.PublicKey) require.True(t, prv[0].PublicKey().EqualsTo(pub)) case crypto.AddressTypeEd25519Account: pub, _ := ed25519.PublicKeyFromString(info.PublicKey) require.True(t, prv[0].PublicKey().EqualsTo(pub)) case crypto.AddressTypeTreasury: assert.Fail(t, "not supported") } } }) } func TestImportBLSPrivateKey(t *testing.T) { td := setup(t) _, prv := td.RandBLSKeyPair() t.Run("Invalid password", func(t *testing.T) { _, _, err := td.vault.ImportBLSPrivateKey("invalid-password", prv) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Ok", func(t *testing.T) { accInfo, valInfo, err := td.vault.ImportBLSPrivateKey(td.password, prv) require.NoError(t, err) assert.Equal(t, prv.PublicKeyNative().String(), accInfo.PublicKey) assert.Equal(t, prv.PublicKeyNative().String(), valInfo.PublicKey) assert.Equal(t, "m/65535'/21888'/1'/2'", accInfo.Path) assert.Equal(t, "m/65535'/21888'/2'/2'", valInfo.Path) }) } func TestImportEd25519PrivateKey(t *testing.T) { td := setup(t) _, prv := td.RandEd25519KeyPair() t.Run("Invalid password", func(t *testing.T) { _, err := td.vault.ImportEd25519PrivateKey("invalid-password", prv) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Ok", func(t *testing.T) { info, err := td.vault.ImportEd25519PrivateKey(td.password, prv) require.NoError(t, err) assert.Equal(t, prv.PublicKeyNative().String(), info.PublicKey) assert.Equal(t, "m/65535'/21888'/3'/2'", info.Path) }) } func TestGetMnemonic(t *testing.T) { td := setup(t) t.Run("Invalid password", func(t *testing.T) { _, err := td.vault.Mnemonic("invalid-password") require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("No password", func(t *testing.T) { _, err := td.vault.Mnemonic("") require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Ok", func(t *testing.T) { m, err := td.vault.Mnemonic(td.password) require.NoError(t, err) assert.Equal(t, m, td.mnemonic) }) } func TestUpdatePassword(t *testing.T) { td := setup(t) opts := []encrypter.Option{ encrypter.OptionIteration(1), encrypter.OptionMemory(1), encrypter.OptionParallelism(1), } newPassword := "new-password" t.Run("Rejects empty current password", func(t *testing.T) { err := td.vault.UpdatePassword("", newPassword) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Rejects incorrect current password", func(t *testing.T) { err := td.vault.UpdatePassword("invalid-password", newPassword) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Updates password with valid current password", func(t *testing.T) { require.NoError(t, td.vault.UpdatePassword(td.password, newPassword, opts...)) assert.True(t, td.vault.IsEncrypted()) }) t.Run("Old password is no longer valid after update", func(t *testing.T) { err := td.vault.UpdatePassword(td.password, newPassword) require.ErrorIs(t, err, encrypter.ErrInvalidPassword) }) t.Run("Clears vault password when new password is empty", func(t *testing.T) { require.NoError(t, td.vault.UpdatePassword(newPassword, "")) assert.False(t, td.vault.IsEncrypted()) }) } func TestNeuter(t *testing.T) { td := setup(t) td.vault.Neuter() assert.True(t, td.vault.IsNeutered()) _, err := td.vault.Mnemonic(td.password) require.ErrorIs(t, err, ErrNeutered) _, err = td.vault.PrivateKeys(td.password, []addresspath.Path{}) require.ErrorIs(t, err, ErrNeutered) _, _, err = td.vault.ImportBLSPrivateKey("any", nil) require.ErrorIs(t, err, ErrNeutered) _, err = td.vault.ImportEd25519PrivateKey("any", nil) require.ErrorIs(t, err, ErrNeutered) err = td.vault.UpdatePassword("any", "any") require.ErrorIs(t, err, ErrNeutered) } // TestAddressRecovery tests the address recovery functionality according to PIP-41 specification. // This test verifies that the RecoverAddresses function correctly identifies and recovers // previously used addresses when restoring a wallet from a mnemonic phrase. // // The first 8 BLS account addresses for the test mnemonic are: // pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf (index 0) // pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns (index 1) // pc1zaj6dzh6zg8zsgzy2rrtvyyeg0l4d32p8e6xn5h (index 2) // pc1ztmex7taes23h6z4jf0awwmps0zpzmecuzcsev0 (index 3) // pc1zkry0kt7fxufqjql6zus54a397w4ukqqg0l2sz4 (index 4) // pc1zqar4tm23a3k0cyy3n86fq59psajah3wgm3hc4x (index 5) // pc1zpmxu83gp7y84ekn89rfkyf099sj6f9jlmututf (index 6) // pc1zydjhrq06ngg6nwqs8n8jkyw6u58qlqc5cqqxht (index 7) // // The first 8 Ed25519 account addresses for the test mnemonic are: // pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3 (index 0) // pc1r7aynw9urvh66ktr3fte2gskjjnxzruflkgde94 (index 1) // pc1ruumtknmwr6ns32rkezfph38tawwx7gesmykk4g (index 2) // pc1r4waddcacrxw2vg4ge8vtlnk9mnccnuv0374xuv (index 3) // pc1re5an4nasvgpmxmuptxxd8hqy6adncqy4qyhj8w (index 4) // pc1rul34wczhq44s5chtxvlgmrgf6dp0xx47zzg9ud (index 5) // pc1r77rvd98gld8vfgzfa89har678dlpm9pkxex4zf (index 6) // pc1rmzpqfhs4ekrevmwwj2gsz6m4kjym3eg99x7zk5 (index 7) // // The test uses a mock hasActivity function to simulate blockchain activity checks. func TestAddressRecovery(t *testing.T) { //nolint:dupword // has duplicated words testMnemonic := "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon cactus" t.Run("recover addresses from a fresh wallet without any active addresses", func(t *testing.T) { vault, err := CreateVaultFromMnemonic(testMnemonic, 21888) // Mainnet require.NoError(t, err) // Mock hasActivity to return false for all addresses (no active addresses) hasActivity := func(_ string) (bool, error) { return false, nil } recovered, err := vault.RecoverAddresses(t.Context(), "", hasActivity) require.NoError(t, err) assert.Empty(t, recovered) }) t.Run("recover addresses with one gap at the beginning", func(t *testing.T) { vault, err := CreateVaultFromMnemonic(testMnemonic, 21888) // Mainnet require.NoError(t, err) // Mock hasActivity to return true only for the first call (address at index 0) hasActivity := func(addr string) (bool, error) { return addr == "pc1r7aynw9urvh66ktr3fte2gskjjnxzruflkgde94" || addr == "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", nil } recovered, err := vault.RecoverAddresses(t.Context(), "", hasActivity) require.NoError(t, err) // Should have 4 addresses assert.Len(t, recovered, 4) assert.Equal(t, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", recovered[0].Address) assert.Equal(t, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", recovered[1].Address) assert.Equal(t, "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", recovered[2].Address) assert.Equal(t, "pc1r7aynw9urvh66ktr3fte2gskjjnxzruflkgde94", recovered[3].Address) }) t.Run("recover addresses with gaps in the middle of the address list", func(t *testing.T) { vault, err := CreateVaultFromMnemonic(testMnemonic, 21888) // Mainnet require.NoError(t, err) hasActivity := func(addr string) (bool, error) { return addr == "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3" || addr == "pc1r7aynw9urvh66ktr3fte2gskjjnxzruflkgde94" || addr == "pc1r4waddcacrxw2vg4ge8vtlnk9mnccnuv0374xuv" || addr == "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf" || addr == "pc1ztmex7taes23h6z4jf0awwmps0zpzmecuzcsev0", nil } recovered, err := vault.RecoverAddresses(t.Context(), "", hasActivity) require.NoError(t, err) assert.Len(t, recovered, 8) assert.Equal(t, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", recovered[0].Address) assert.Equal(t, "pc1z4xuja689hg2434yhr32clhn97x6afw58a5n9ns", recovered[1].Address) assert.Equal(t, "pc1zaj6dzh6zg8zsgzy2rrtvyyeg0l4d32p8e6xn5h", recovered[2].Address) assert.Equal(t, "pc1ztmex7taes23h6z4jf0awwmps0zpzmecuzcsev0", recovered[3].Address) assert.Equal(t, "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", recovered[4].Address) assert.Equal(t, "pc1r7aynw9urvh66ktr3fte2gskjjnxzruflkgde94", recovered[5].Address) assert.Equal(t, "pc1ruumtknmwr6ns32rkezfph38tawwx7gesmykk4g", recovered[6].Address) assert.Equal(t, "pc1r4waddcacrxw2vg4ge8vtlnk9mnccnuv0374xuv", recovered[7].Address) }) t.Run("prevent recovering existing address", func(t *testing.T) { vault, err := CreateVaultFromMnemonic(testMnemonic, 21888) // Mainnet require.NoError(t, err) _, _ = vault.NewEd25519AccountAddress("existing address", "") hasActivity := func(addr string) (bool, error) { return addr == "pc1rcx9x55nfme5juwdgxd2ksjdcmhvmvkrygmxpa3", nil } recovered, err := vault.RecoverAddresses(t.Context(), "", hasActivity) require.NoError(t, err) assert.Empty(t, recovered) }) t.Run("error handling", func(t *testing.T) { vault, err := CreateVaultFromMnemonic(testMnemonic, 21888) // Mainnet require.NoError(t, err) // Mock hasActivity to return an error hasActivity := func(_ string) (bool, error) { return false, errors.New("blockchain connection error") } _, err = vault.RecoverAddresses(t.Context(), "", hasActivity) require.Error(t, err) assert.Contains(t, err.Error(), "blockchain connection error") }) t.Run("cancel recovery with context cancel signal", func(t *testing.T) { vault, err := CreateVaultFromMnemonic(testMnemonic, 21888) // Mainnet require.NoError(t, err) // Create a cancellable context ctx, cancel := context.WithCancel(t.Context()) // Counter to track how many times hasActivity is called callCount := 0 // Mock hasActivity to cancel context after a few calls hasActivity := func(_ string) (bool, error) { callCount++ // Cancel the context after 3 calls to simulate interruption during recovery if callCount >= 3 { cancel() } return false, nil } _, err = vault.RecoverAddresses(ctx, "", hasActivity) require.Error(t, err) assert.Equal(t, context.Canceled, err) }) } ================================================ FILE: wallet/wallet.go ================================================ package wallet import ( "context" "github.com/ezex-io/gopkg/pipeline" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/encrypter" "github.com/pactus-project/pactus/wallet/provider" "github.com/pactus-project/pactus/wallet/provider/offline" "github.com/pactus-project/pactus/wallet/provider/remote" "github.com/pactus-project/pactus/wallet/storage" "github.com/pactus-project/pactus/wallet/storage/jsonstorage" "github.com/pactus-project/pactus/wallet/storage/sqlitestorage" "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type Wallet struct { addresses transactions provider provider.IBlockchainProvider storage storage.IStorage } // GenerateMnemonic is a wrapper for `vault.GenerateMnemonic`. func GenerateMnemonic(entropy int) (string, error) { return vault.GenerateMnemonic(entropy) } // CheckMnemonic is a wrapper for `vault.CheckMnemonic`. func CheckMnemonic(mnemonic string) error { return vault.CheckMnemonic(mnemonic) } // Create creates a wallet from mnemonic (seed phrase) and save it at the // given path. func Create(ctx context.Context, walletPath, mnemonic, password string, chain genesis.ChainType, opts ...OpenWalletOption, ) (*Wallet, error) { walletPath = util.MakeAbs(walletPath) if util.PathExists(walletPath) { return nil, ExitsError{ Path: walletPath, } } coinType := addresspath.CoinTypePactusMainnet if chain != genesis.Mainnet { coinType = addresspath.CoinTypePactusTestnet crypto.ToTestnetHRP() } vlt, err := vault.CreateVaultFromMnemonic(mnemonic, coinType) if err != nil { return nil, err } err = vlt.UpdatePassword("", password) if err != nil { return nil, err } cfg := defaultOpenWalletConfig for _, opt := range opts { opt(&cfg) } storage, err := sqlitestorage.Create(ctx, walletPath, chain, vlt, sqlitestorage.WithLockingMode(cfg.lockMode)) if err != nil { return nil, err } return New(ctx, storage, opts...) } // Open tries to open a wallet at the given path. // It first tries the SQLite backend; if that fails, it falls back to the legacy JSON wallet format. // A wallet can be opened in offline or online modes. // Offline wallet doesn’t have any connection to any node. // Online wallet has a connection to one of the pre-defined servers. func Open(ctx context.Context, walletPath string, opts ...OpenWalletOption) (*Wallet, error) { cfg := defaultOpenWalletConfig for _, opt := range opts { opt(&cfg) } if util.IsDir(walletPath) { sqliteStrg, err := sqlitestorage.Open(ctx, walletPath, sqlitestorage.WithLockingMode(cfg.lockMode)) if err != nil { return nil, err } return New(ctx, sqliteStrg, opts...) } // Fallback to JSON storage for legacy wallets if err := jsonstorage.Upgrade(walletPath); err != nil { return nil, err } jsonStrg, err := jsonstorage.Open(walletPath) if err != nil { return nil, err } return New(ctx, jsonStrg, opts...) } type openWalletConfig struct { eventPipe pipeline.Pipeline[any] provider provider.IBlockchainProvider lockMode bool } var defaultOpenWalletConfig = openWalletConfig{ eventPipe: nil, provider: nil, lockMode: true, } type OpenWalletOption func(*openWalletConfig) func WithEventPipe(eventPipe pipeline.Pipeline[any]) OpenWalletOption { return func(cfg *openWalletConfig) { cfg.eventPipe = eventPipe } } func WithBlockchainProvider(provider provider.IBlockchainProvider) OpenWalletOption { return func(cfg *openWalletConfig) { cfg.provider = provider } } func WithOfflineProvider() OpenWalletOption { return func(cfg *openWalletConfig) { cfg.provider = offline.NewOfflineBlockchainProvider() } } // WithLockMode configures exclusive or normal database locking. func WithLockMode(lockMode bool) OpenWalletOption { return func(cfg *openWalletConfig) { cfg.lockMode = lockMode } } func New(ctx context.Context, storage storage.IStorage, opts ...OpenWalletOption) (*Wallet, error) { if storage.Vault().CoinType != addresspath.CoinTypePactusMainnet { crypto.ToTestnetHRP() } cfg := defaultOpenWalletConfig for _, opt := range opts { opt(&cfg) } if cfg.provider == nil { provider, err := remote.NewRemoteBlockchainProvider(ctx, storage.WalletInfo().Network) if err != nil { return nil, err } cfg.provider = provider } wlt := &Wallet{ addresses: newAddresses(storage), transactions: newTransactions(storage, cfg.provider), provider: cfg.provider, storage: storage, } if cfg.eventPipe != nil { cfg.eventPipe.RegisterReceiver(wlt.transactions.processEvent) } return wlt, nil } func (w *Wallet) Close() { if err := w.provider.Close(); err != nil { logger.Warn("failed to close provider", "error", err) } if err := w.storage.Close(); err != nil { logger.Warn("failed to close storage", "error", err) } } func (w *Wallet) Version() int { return w.storage.WalletInfo().Version } func (w *Wallet) Info() *types.WalletInfo { return w.storage.WalletInfo() } func (w *Wallet) Path() string { return w.storage.WalletInfo().Path } func (w *Wallet) IsEncrypted() bool { return w.storage.WalletInfo().Encrypted } // Neuter clones the wallet and neuters it and saves it at the given path. func (w *Wallet) Neuter(path string) error { cloned, err := w.storage.Clone(path) if err != nil { return err } vault := cloned.Vault() vault.Neuter() return cloned.UpdateVault(vault) } // RecoveryAddresses recovers active addresses in the wallet. func (w *Wallet) RecoveryAddresses(ctx context.Context, password string, eventFunc func(addr string), ) error { vault := w.storage.Vault() recovered, err := vault.RecoverAddresses(ctx, password, func(addr string) (bool, error) { _, err := w.provider.GetAccount(addr) if err != nil { s, ok := status.FromError(err) if ok && s.Code() == codes.NotFound { return false, nil } return false, err } if eventFunc != nil { eventFunc(addr) } return true, nil }) if err != nil { return err } for _, info := range recovered { err := w.storage.InsertAddress(&info) if err != nil { return err } } return w.storage.UpdateVault(vault) } // Balance returns balance of the account associated with the address.. func (w *Wallet) Balance(addrStr string) (amount.Amount, error) { acc, err := w.provider.GetAccount(addrStr) if err != nil { return 0, err } return acc.Balance(), nil } // Stake returns stake of the validator associated with the address.. func (w *Wallet) Stake(addrStr string) (amount.Amount, error) { val, err := w.provider.GetValidator(addrStr) if err != nil { return 0, err } return val.Stake(), nil } // TotalBalance return the total available balance of the wallet. func (w *Wallet) TotalBalance() (amount.Amount, error) { totalBalance := amount.Amount(0) infos := w.ListAddresses(OnlyAccountAddresses()) for _, info := range infos { acc, err := w.provider.GetAccount(info.Address) if err == nil { totalBalance += acc.Balance() } } return totalBalance, nil } // TotalStake return total available stake of the wallet. func (w *Wallet) TotalStake() (amount.Amount, error) { totalStake := amount.Amount(0) infos := w.ListAddresses(OnlyValidatorAddresses()) for _, info := range infos { val, err := w.provider.GetValidator(info.Address) if err == nil { totalStake += val.Stake() } } return totalStake, nil } // MakeTransferTx creates a new transfer transaction based on the given parameters. func (w *Wallet) MakeTransferTx(sender, receiver string, amt amount.Amount, options ...TxOption, ) (*tx.Tx, error) { maker, err := w.makeTxBuilder(options...) if err != nil { return nil, err } err = maker.setSenderAddr(sender) if err != nil { return nil, err } err = maker.setReceiverAddress(receiver) if err != nil { return nil, err } maker.amount = amt maker.typ = payload.TypeTransfer return maker.build() } // MakeBondTx creates a new bond transaction based on the given parameters. func (w *Wallet) MakeBondTx(sender, receiver, pubKey string, amt amount.Amount, options ...TxOption, ) (*tx.Tx, error) { maker, err := w.makeTxBuilder(options...) if err != nil { return nil, err } err = maker.setSenderAddr(sender) if err != nil { return nil, err } err = maker.setReceiverAddress(receiver) if err != nil { return nil, err } if pubKey == "" { // Let's check if we can get public key from the wallet info, _ := w.AddressInfo(receiver) if info != nil { pubKey = info.PublicKey } } if pubKey != "" { err = maker.setPublicKey(pubKey) if err != nil { return nil, err } } maker.amount = amt maker.typ = payload.TypeBond return maker.build() } // MakeUnbondTx creates a new unbond transaction based on the given parameters. func (w *Wallet) MakeUnbondTx(addr string, opts ...TxOption) (*tx.Tx, error) { maker, err := w.makeTxBuilder(opts...) if err != nil { return nil, err } err = maker.setSenderAddr(addr) if err != nil { return nil, err } maker.typ = payload.TypeUnbond return maker.build() } // MakeWithdrawTx creates a new withdraw transaction based on the given // parameters. func (w *Wallet) MakeWithdrawTx(sender, receiver string, amt amount.Amount, options ...TxOption, ) (*tx.Tx, error) { maker, err := w.makeTxBuilder(options...) if err != nil { return nil, err } err = maker.setSenderAddr(sender) if err != nil { return nil, err } err = maker.setReceiverAddress(receiver) if err != nil { return nil, err } maker.amount = amt maker.typ = payload.TypeWithdraw return maker.build() } func (w *Wallet) SignTransaction(password string, trx *tx.Tx) error { prv, err := w.PrivateKey(password, trx.Payload().Signer().String()) if err != nil { return err } sig := prv.Sign(trx.SignBytes()) trx.SetSignature(sig) trx.SetPublicKey(prv.PublicKey()) return nil } func (w *Wallet) BroadcastTransaction(trx *tx.Tx) (string, error) { hash, err := w.provider.SendTx(trx) if err != nil { return "", err } txInfos, _ := types.MakeTransactionInfos(trx, types.TransactionStatusPending, 0) for _, info := range txInfos { info.Direction = types.TxDirectionOutgoing err := w.storage.InsertTransaction(info) if err != nil { logger.Warn("transaction broadcasted but not recorded in wallet storage", "error", err) } } return hash, nil } func (w *Wallet) UpdatePassword(oldPassword, newPassword string, opts ...encrypter.Option) error { vault := w.storage.Vault() err := vault.UpdatePassword(oldPassword, newPassword, opts...) if err != nil { return err } return w.storage.UpdateVault(vault) } func (w *Wallet) Mnemonic(password string) (string, error) { return w.storage.Vault().Mnemonic(password) } func (w *Wallet) SignMessage(password, addr, msg string) (string, error) { prv, err := w.PrivateKey(password, addr) if err != nil { return "", err } return prv.Sign([]byte(msg)).String(), nil } // makeTxBuilder initializes a txBuilder with provided options, allowing for flexible configuration of the transaction. func (w *Wallet) makeTxBuilder(options ...TxOption) (*txBuilder, error) { builder := &txBuilder{ provider: w.provider, fee: w.storage.WalletInfo().DefaultFee, } for _, op := range options { err := op(builder) if err != nil { return nil, err } } return builder, nil } func (w *Wallet) SetDefaultFee(fee amount.Amount) error { return w.storage.SetDefaultFee(fee) } // SetProvider sets the blockchain provider for the wallet. func (w *Wallet) SetProvider(provider provider.IBlockchainProvider) { w.provider = provider w.transactions.provider = provider } ================================================ FILE: wallet/wallet_test.go ================================================ package wallet import ( "errors" "strings" "testing" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" "github.com/pactus-project/pactus/wallet/addresspath" "github.com/pactus-project/pactus/wallet/provider" "github.com/pactus-project/pactus/wallet/provider/offline" "github.com/pactus-project/pactus/wallet/storage" wtypes "github.com/pactus-project/pactus/wallet/types" "github.com/pactus-project/pactus/wallet/vault" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) type testData struct { *testsuite.TestSuite wallet *Wallet password string testVault *vault.Vault mockStorage *storage.MockIStorage mockProvider *provider.MockIBlockchainProvider } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) mockStorage := storage.NewMockIStorage(ts.Ctrl) mockProvider := provider.NewMockIBlockchainProvider(ts.Ctrl) mnemonic1, _ := GenerateMnemonic(128) testVault, _ := vault.CreateVaultFromMnemonic(mnemonic1, addresspath.CoinTypePactusMainnet) mockStorage.EXPECT().Vault().Return(testVault).AnyTimes() var wlt *Wallet t.Cleanup(func() { mockProvider.EXPECT().Close().Times(1) mockStorage.EXPECT().Close().Times(1) if wlt != nil { wlt.Close() } }) wlt, err := New(t.Context(), mockStorage, WithBlockchainProvider(mockProvider)) require.NoError(t, err) return &testData{ TestSuite: ts, testVault: testVault, mockStorage: mockStorage, mockProvider: mockProvider, wallet: wlt, password: "", } } func (td *testData) RandMemo() string { return td.RandString(32) } func TestCheckMnemonic(t *testing.T) { for _, entropy := range []int{128, 160, 192, 224, 256} { mnemonic, _ := GenerateMnemonic(entropy) require.NoError(t, CheckMnemonic(mnemonic)) } } func TestOpenWallet(t *testing.T) { t.Run("Invalid wallet path", func(t *testing.T) { _, err := Open(t.Context(), util.TempFilePath()) require.Error(t, err) }) t.Run("Invalid data", func(t *testing.T) { path := util.TempFilePath() require.NoError(t, util.WriteFile(path, []byte("invalid_data"))) _, err := Open(t.Context(), path) require.Error(t, err) }) } func TestCreateWallet(t *testing.T) { mnemonic, _ := GenerateMnemonic(256) password := "" t.Run("Wallet exists", func(t *testing.T) { path := util.TempFilePath() err := util.WriteFile(path, []byte("something-here")) require.NoError(t, err) _, err = Create(t.Context(), path, mnemonic, password, genesis.Mainnet) require.Error(t, err, "%+v", ExitsError{Path: path}) }) t.Run("Invalid mnemonic", func(t *testing.T) { _, err := Create(t.Context(), util.TempFilePath(), "invalid mnemonic", password, genesis.Mainnet) require.Error(t, err) }) t.Run("Invalid path", func(t *testing.T) { _, err := Create(t.Context(), "\x00", mnemonic, password, genesis.Mainnet) require.Error(t, err) }) t.Run("Ok", func(t *testing.T) { walletPath := util.TempFilePath() _, err := Create(t.Context(), walletPath, mnemonic, password, genesis.Mainnet) require.NoError(t, err) }) } func TestSetDefaultFee(t *testing.T) { td := setup(t) fee := td.RandFee() td.mockStorage.EXPECT().SetDefaultFee(fee).Return(nil) err := td.wallet.SetDefaultFee(fee) require.NoError(t, err) } func TestMnemonic(t *testing.T) { td := setup(t) mnemonic1, err := td.testVault.Mnemonic(td.password) require.NoError(t, err) mnemonic2, err := td.wallet.Mnemonic(td.password) require.NoError(t, err) assert.Equal(t, mnemonic1, mnemonic2) } func TestSignMessage(t *testing.T) { td := setup(t) msg := "pactus" expectedSig := "8c3ba687e8e4c016293a2c369493faa565065987544a59baba7aadae3f17ada07883552b6c7d1d7eb49f46fbdf0975c4" prv, err := bls.PrivateKeyFromString("SECRET1P9QAUKRJAU7SQ7AT6ZZ6HXHYLMKPQSQYTGDL2VMH5Q5N0P5Q2QW0QL45AY3") require.NoError(t, err) _, accInfo, err := td.testVault.ImportBLSPrivateKey(td.password, prv) require.NoError(t, err) t.Run("Unexpected Error", func(t *testing.T) { td.mockStorage.EXPECT().AddressInfo(accInfo.Address).Return(nil, errors.New("unexpected error")) _, err := td.wallet.SignMessage(td.password, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", msg) require.Error(t, err) }) t.Run("Ok", func(t *testing.T) { td.mockStorage.EXPECT().AddressInfo(accInfo.Address).Return(accInfo, nil) sig, err := td.wallet.SignMessage(td.password, "pc1z0m0vw8sjfgv7f2zgq2hfxutg8rwn7gpffhe8tf", msg) require.NoError(t, err) assert.Equal(t, expectedSig, sig) }) } func TestBalance(t *testing.T) { td := setup(t) t.Run("existing account", func(t *testing.T) { acc, addr := td.GenerateTestAccount() td.mockProvider.EXPECT().GetAccount(addr.String()).Return(acc, nil) amt, err := td.wallet.Balance(addr.String()) require.NoError(t, err) assert.Equal(t, amt, acc.Balance()) }) t.Run("non-existing account", func(t *testing.T) { addr := td.RandAccAddress() td.mockProvider.EXPECT().GetAccount(addr.String()).Return(nil, errors.New("account not found")) amt, err := td.wallet.Balance(addr.String()) require.Error(t, err) assert.Zero(t, amt) }) } func TestStake(t *testing.T) { td := setup(t) t.Run("existing validator", func(t *testing.T) { val := td.GenerateTestValidator() td.mockProvider.EXPECT().GetValidator(val.Address().String()).Return(val, nil) amt, err := td.wallet.Stake(val.Address().String()) require.NoError(t, err) assert.Equal(t, amt, val.Stake()) }) t.Run("non-existing validator", func(t *testing.T) { addr := td.RandValAddress() td.mockProvider.EXPECT().GetValidator(addr.String()).Return(nil, errors.New("validator not found")) amt, err := td.wallet.Stake(addr.String()) require.Error(t, err) assert.Zero(t, amt) }) } func TestSigningTxWithBLS(t *testing.T) { td := setup(t) senderInfo, err := td.testVault.NewBLSAccountAddress("test") require.NoError(t, err) receiver := td.RandAccAddress() amt := td.RandAmount() fee := td.RandFee() lockTime := td.RandHeight() memo := td.RandMemo() opts := []TxOption{ OptionFee(fee.String()), OptionLockTime(lockTime), OptionMemo(memo), } td.mockStorage.EXPECT().WalletInfo().Return(&wtypes.WalletInfo{DefaultFee: td.RandFee()}) td.mockStorage.EXPECT().AddressInfo(senderInfo.Address).Return(senderInfo, nil) trx, err := td.wallet.MakeTransferTx(senderInfo.Address, receiver.String(), amt, opts...) require.NoError(t, err) err = td.wallet.SignTransaction(td.password, trx) require.NoError(t, err) assert.NotNil(t, trx.Signature()) require.NoError(t, trx.BasicCheck()) td.mockProvider.EXPECT().SendTx(trx).Return(trx.ID().String(), nil) td.mockStorage.EXPECT().InsertTransaction(gomock.Any()).Return(nil) id, err := td.wallet.BroadcastTransaction(trx) require.NoError(t, err) assert.Equal(t, trx.ID().String(), id) assert.Equal(t, fee, trx.Fee()) assert.Equal(t, lockTime, trx.LockTime()) assert.Equal(t, memo, trx.Memo()) } func TestSigningTxWithEd25519(t *testing.T) { td := setup(t) senderInfo, err := td.testVault.NewEd25519AccountAddress("testing addr", td.password) require.NoError(t, err) receiver := td.RandAccAddress() amt := td.RandAmount() fee := td.RandFee() lockTime := td.RandHeight() memo := td.RandMemo() opts := []TxOption{ OptionFee(fee.String()), OptionLockTime(lockTime), OptionMemo(memo), } td.mockStorage.EXPECT().WalletInfo().Return(&wtypes.WalletInfo{DefaultFee: td.RandFee()}) td.mockStorage.EXPECT().AddressInfo(senderInfo.Address).Return(senderInfo, nil) trx, err := td.wallet.MakeTransferTx(senderInfo.Address, receiver.String(), amt, opts...) require.NoError(t, err) err = td.wallet.SignTransaction(td.password, trx) require.NoError(t, err) assert.NotNil(t, trx.Signature()) require.NoError(t, trx.BasicCheck()) td.mockProvider.EXPECT().SendTx(trx).Return(trx.ID().String(), nil) td.mockStorage.EXPECT().InsertTransaction(gomock.Any()).Return(nil) id, err := td.wallet.BroadcastTransaction(trx) require.NoError(t, err) assert.Equal(t, trx.ID().String(), id) assert.Equal(t, fee, trx.Fee()) assert.Equal(t, lockTime, trx.LockTime()) assert.Equal(t, memo, trx.Memo()) } func TestMakeTransferTx(t *testing.T) { td := setup(t) sender := td.RandAccAddress() receiver := td.RandAccAddress() amt := td.RandAmount() td.mockStorage.EXPECT().WalletInfo().Return(&wtypes.WalletInfo{DefaultFee: td.RandFee()}).AnyTimes() t.Run("set parameters manually", func(t *testing.T) { fee := td.RandFee() lockTime := td.RandHeight() memo := td.RandMemo() opts := []TxOption{ OptionFee(fee.String()), OptionLockTime(lockTime), OptionMemo(memo), } trx, err := td.wallet.MakeTransferTx(sender.String(), receiver.String(), amt, opts...) require.NoError(t, err) assert.Equal(t, fee, trx.Fee()) assert.Equal(t, lockTime, trx.LockTime()) assert.Equal(t, memo, trx.Memo()) }) t.Run("query parameters from the node", func(t *testing.T) { testHeight := td.RandHeight() td.mockProvider.EXPECT().LastBlockHeight().Return(testHeight, nil) trx, err := td.wallet.MakeTransferTx(sender.String(), receiver.String(), amt) require.NoError(t, err) assert.Equal(t, testHeight+1, trx.LockTime()) assert.Equal(t, amt, trx.Payload().Value()) }) t.Run("invalid sender address", func(t *testing.T) { _, err := td.wallet.MakeTransferTx("invalid_addr_string", receiver.String(), amt) require.Error(t, err) }) t.Run("invalid receiver address", func(t *testing.T) { _, err := td.wallet.MakeTransferTx(sender.String(), "invalid_addr_string", amt) require.Error(t, err) }) t.Run("unable to get the blockchain info", func(t *testing.T) { td.mockProvider.EXPECT().LastBlockHeight().Return(types.Height(0), errors.New("not found")) _, err := td.wallet.MakeTransferTx(td.RandAccAddress().String(), receiver.String(), amt) require.Error(t, err) }) } func TestMakeBondTx(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().WalletInfo().Return(&wtypes.WalletInfo{DefaultFee: td.RandFee()}).AnyTimes() sender := td.RandAccAddress() amt := td.RandAmount() t.Run("set parameters manually", func(t *testing.T) { receiver := td.RandValKey() lockTime := td.RandHeight() fee := td.RandFee() memo := td.RandMemo() opts := []TxOption{ OptionFee(fee.String()), OptionLockTime(lockTime), OptionMemo(memo), } td.mockProvider.EXPECT().GetValidator(receiver.Address().String()).Return(nil, nil) trx, err := td.wallet.MakeBondTx(sender.String(), receiver.Address().String(), receiver.PublicKey().String(), amt, opts...) require.NoError(t, err) assert.Equal(t, fee, trx.Fee()) assert.Equal(t, lockTime, trx.LockTime()) assert.Equal(t, memo, trx.Memo()) }) t.Run("query parameters from the node", func(t *testing.T) { receiver := td.RandValKey() testHeight := td.RandHeight() td.mockProvider.EXPECT().LastBlockHeight().Return(testHeight, nil) td.mockProvider.EXPECT().GetValidator(receiver.Address().String()).Return(nil, nil) trx, err := td.wallet.MakeBondTx(sender.String(), receiver.Address().String(), receiver.PublicKey().String(), amt) require.NoError(t, err) assert.Equal(t, testHeight+1, trx.LockTime()) assert.Equal(t, amt, trx.Payload().Value()) }) t.Run("validator address is not stored in wallet", func(t *testing.T) { receiver := td.RandValKey() td.mockProvider.EXPECT().LastBlockHeight().Return(td.RandHeight(), nil).Times(4) td.mockStorage.EXPECT().AddressInfo(receiver.Address().String()).Return(nil, storage.ErrNotFound).AnyTimes() t.Run("validator doesn't exist and public key not set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiver.Address().String()).Return(nil, errors.New("not exist")) trx, err := td.wallet.MakeBondTx(sender.String(), receiver.Address().String(), "", amt) require.NoError(t, err) assert.Nil(t, trx.Payload().(*payload.BondPayload).PublicKey) }) t.Run("validator doesn't exist and public key set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiver.Address().String()).Return(nil, errors.New("not exist")) trx, err := td.wallet.MakeBondTx(sender.String(), receiver.Address().String(), receiver.PublicKey().String(), amt) require.NoError(t, err) assert.Equal(t, receiver.PublicKey().String(), trx.Payload().(*payload.BondPayload).PublicKey.String()) }) t.Run("validator exists and public key not set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiver.Address().String()).Return(td.GenerateTestValidator(), nil) trx, err := td.wallet.MakeBondTx(sender.String(), receiver.Address().String(), "", amt) require.NoError(t, err) assert.Nil(t, trx.Payload().(*payload.BondPayload).PublicKey) }) t.Run("validator exists and public key set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiver.Address().String()).Return(td.GenerateTestValidator(), nil) trx, err := td.wallet.MakeBondTx(sender.String(), receiver.Address().String(), receiver.PublicKey().String(), amt) require.NoError(t, err) assert.Nil(t, trx.Payload().(*payload.BondPayload).PublicKey) }) }) t.Run("validator address stored in wallet", func(t *testing.T) { td.mockStorage.EXPECT().InsertAddress(gomock.Any()).Return(nil) td.mockStorage.EXPECT().UpdateVault(td.testVault).Return(nil) receiverInfo, err := td.wallet.NewValidatorAddress("validator-address") require.NoError(t, err) td.mockStorage.EXPECT().AddressInfo(receiverInfo.Address).Return(receiverInfo, nil).AnyTimes() td.mockProvider.EXPECT().LastBlockHeight().Return(td.RandHeight(), nil).Times(4) t.Run("validator doesn't exist and public key not set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiverInfo.Address).Return(nil, errors.New("not exist")) trx, err := td.wallet.MakeBondTx(sender.String(), receiverInfo.Address, "", amt) require.NoError(t, err) assert.Equal(t, receiverInfo.PublicKey, trx.Payload().(*payload.BondPayload).PublicKey.String()) }) t.Run("validator doesn't exist and public key set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiverInfo.Address).Return(nil, errors.New("not exist")) trx, err := td.wallet.MakeBondTx(sender.String(), receiverInfo.Address, receiverInfo.PublicKey, amt) require.NoError(t, err) assert.Equal(t, receiverInfo.PublicKey, trx.Payload().(*payload.BondPayload).PublicKey.String()) }) t.Run("validator exists and public key not set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiverInfo.Address).Return(td.GenerateTestValidator(), nil) trx, err := td.wallet.MakeBondTx(sender.String(), receiverInfo.Address, "", amt) require.NoError(t, err) assert.Nil(t, trx.Payload().(*payload.BondPayload).PublicKey) }) t.Run("validator exists and public key set", func(t *testing.T) { td.mockProvider.EXPECT().GetValidator(receiverInfo.Address).Return(td.GenerateTestValidator(), nil) trx, err := td.wallet.MakeBondTx(sender.String(), receiverInfo.Address, receiverInfo.PublicKey, amt) require.NoError(t, err) assert.Nil(t, trx.Payload().(*payload.BondPayload).PublicKey) }) }) t.Run("invalid sender address", func(t *testing.T) { _, err := td.wallet.MakeBondTx("invalid_addr_string", td.RandValAddress().String(), "", amt) require.Error(t, err) }) t.Run("invalid receiver address", func(t *testing.T) { _, err := td.wallet.MakeBondTx(sender.String(), "invalid_addr_string", "", amt) require.Error(t, err) }) t.Run("invalid public key", func(t *testing.T) { _, err := td.wallet.MakeBondTx(sender.String(), td.RandValAddress().String(), "invalid-pub-key", amt) require.Error(t, err) }) t.Run("unable to get the blockchain info", func(t *testing.T) { td.mockStorage.EXPECT().AddressInfo(gomock.Any()).Return(nil, storage.ErrNotFound) td.mockProvider.EXPECT().LastBlockHeight().Return(types.Height(0), errors.New("unable to get height")) td.mockProvider.EXPECT().GetValidator(gomock.Any()).Return(nil, errors.New("unable to get validator info")).AnyTimes() _, err := td.wallet.MakeBondTx(td.RandAccAddress().String(), td.RandValAddress().String(), "", amt) require.Error(t, err) }) } func TestMakeUnbondTx(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().WalletInfo().Return(&wtypes.WalletInfo{DefaultFee: td.RandFee()}).AnyTimes() sender := td.RandValAddress() t.Run("set parameters manually", func(t *testing.T) { lockTime := td.RandHeight() opts := []TxOption{ OptionLockTime(lockTime), OptionMemo("test"), } trx, err := td.wallet.MakeUnbondTx(sender.String(), opts...) require.NoError(t, err) assert.Zero(t, trx.Fee()) assert.Equal(t, lockTime, trx.LockTime()) assert.Equal(t, "test", trx.Memo()) }) t.Run("query parameters from the node", func(t *testing.T) { testHeight := td.RandHeight() td.mockProvider.EXPECT().LastBlockHeight().Return(testHeight, nil) trx, err := td.wallet.MakeUnbondTx(sender.String()) require.NoError(t, err) assert.Equal(t, testHeight+1, trx.LockTime()) assert.Zero(t, trx.Payload().Value()) assert.Zero(t, trx.Fee()) }) t.Run("invalid sender address", func(t *testing.T) { _, err := td.wallet.MakeUnbondTx("invalid_addr_string") require.Error(t, err) }) t.Run("unable to get the blockchain info", func(t *testing.T) { td.mockProvider.EXPECT().LastBlockHeight().Return(types.Height(0), errors.New("unable to get height")) _, err := td.wallet.MakeUnbondTx(td.RandAccAddress().String()) require.Error(t, err) }) } func TestMakeWithdrawTx(t *testing.T) { td := setup(t) td.mockStorage.EXPECT().WalletInfo().Return(&wtypes.WalletInfo{DefaultFee: td.RandFee()}).AnyTimes() sender := td.RandValAddress() receiver := td.RandAccAddress() amt := td.RandAmount() t.Run("set parameters manually", func(t *testing.T) { lockTime := td.RandHeight() fee := td.RandFee() opts := []TxOption{ OptionFee(fee.String()), OptionLockTime(lockTime), OptionMemo("test"), } trx, err := td.wallet.MakeWithdrawTx(sender.String(), receiver.String(), amt, opts...) require.NoError(t, err) assert.Equal(t, fee, trx.Fee()) assert.Equal(t, lockTime, trx.LockTime()) assert.Equal(t, "test", trx.Memo()) }) t.Run("query parameters from the node", func(t *testing.T) { testHeight := td.RandHeight() td.mockProvider.EXPECT().LastBlockHeight().Return(testHeight, nil) trx, err := td.wallet.MakeWithdrawTx(sender.String(), receiver.String(), amt) require.NoError(t, err) assert.Equal(t, testHeight+1, trx.LockTime()) assert.Equal(t, amt, trx.Payload().Value()) }) t.Run("invalid sender address", func(t *testing.T) { _, err := td.wallet.MakeWithdrawTx("invalid_addr_string", receiver.String(), amt) require.Error(t, err) }) t.Run("unable to get the blockchain info", func(t *testing.T) { td.mockProvider.EXPECT().LastBlockHeight().Return(types.Height(0), errors.New("unable to get height")) _, err := td.wallet.MakeWithdrawTx(td.RandAccAddress().String(), receiver.String(), amt) require.Error(t, err) }) } func TestTotalBalance(t *testing.T) { td := setup(t) accInfo1, _ := td.testVault.NewBLSAccountAddress("account-1") accInfo2, _ := td.testVault.NewBLSAccountAddress("account-2") accInfo3, _ := td.testVault.NewBLSAccountAddress("account-3") addr1, err := crypto.AddressFromString(accInfo1.Address) require.NoError(t, err) addr2, err := crypto.AddressFromString(accInfo2.Address) require.NoError(t, err) acc1, _ := td.GenerateTestAccount(testsuite.AccountWithAddress(addr1)) acc2, _ := td.GenerateTestAccount(testsuite.AccountWithAddress(addr2)) td.mockStorage.EXPECT().AllAddresses().Return([]wtypes.AddressInfo{*accInfo1, *accInfo2, *accInfo3}) td.mockProvider.EXPECT().GetAccount(accInfo1.Address).Return(acc1, nil) td.mockProvider.EXPECT().GetAccount(accInfo2.Address).Return(acc2, nil) td.mockProvider.EXPECT().GetAccount(accInfo3.Address).Return(nil, errors.New("not found")) totalBalance, err := td.wallet.TotalBalance() require.NoError(t, err) assert.Equal(t, acc1.Balance()+acc2.Balance(), totalBalance) } func TestTotalStake(t *testing.T) { td := setup(t) valInfo1, _ := td.testVault.NewValidatorAddress("val-1") valInfo2, _ := td.testVault.NewValidatorAddress("val-2") valInfo3, _ := td.testVault.NewValidatorAddress("val-3") pub1, err := bls.PublicKeyFromString(valInfo1.PublicKey) require.NoError(t, err) pub2, err := bls.PublicKeyFromString(valInfo2.PublicKey) require.NoError(t, err) val1 := td.GenerateTestValidator(testsuite.ValidatorWithPublicKey(pub1)) val2 := td.GenerateTestValidator(testsuite.ValidatorWithPublicKey(pub2)) td.mockStorage.EXPECT().AllAddresses().Return([]wtypes.AddressInfo{*valInfo1, *valInfo2, *valInfo3}) td.mockProvider.EXPECT().GetValidator(valInfo1.Address).Return(val1, nil) td.mockProvider.EXPECT().GetValidator(valInfo2.Address).Return(val2, nil) td.mockProvider.EXPECT().GetValidator(valInfo3.Address).Return(nil, errors.New("not found")) stake, err := td.wallet.TotalStake() require.NoError(t, err) require.Equal(t, val1.Stake()+val2.Stake(), stake) } func TestNeuter(t *testing.T) { td := setup(t) path := util.TempFilePath() clonedStorage := storage.NewMockIStorage(td.Ctrl) td.mockStorage.EXPECT().Clone(path).Return(clonedStorage, nil) clonedStorage.EXPECT().Vault().Return(td.testVault) clonedStorage.EXPECT().UpdateVault(gomock.Any()).DoAndReturn(func(vlt *vault.Vault) error { assert.True(t, vlt.IsNeutered()) assert.False(t, vlt.IsEncrypted()) return nil }) err := td.wallet.Neuter(path) require.NoError(t, err) } func TestTestnetWallet(t *testing.T) { walletPath := util.TempFilePath() t.Run("Create Testnet wallet", func(t *testing.T) { mnemonic, _ := GenerateMnemonic(128) wlt, err := Create(t.Context(), walletPath, mnemonic, "", genesis.Testnet) require.NoError(t, err) assert.Equal(t, genesis.Testnet, wlt.Info().Network) info, err := wlt.NewBLSAccountAddress("testnet-addr-1") require.NoError(t, err) assert.Equal(t, "m/12381'/21777'/2'/0", info.Path) assert.True(t, strings.HasPrefix(info.Address, "tpc1")) wlt.Close() }) t.Run("Open Testnet wallet", func(t *testing.T) { wlt, err := Open(t.Context(), walletPath) require.NoError(t, err) assert.Equal(t, genesis.Testnet, wlt.Info().Network) info, err := wlt.NewBLSAccountAddress("testnet-addr-2") require.NoError(t, err) assert.Equal(t, "m/12381'/21777'/2'/1", info.Path) assert.True(t, strings.HasPrefix(info.Address, "tpc1")) wlt.Close() }) } func TestOfflineWallet(t *testing.T) { td := setup(t) strg := storage.NewMockIStorage(td.Ctrl) strg.EXPECT().Vault().Return(td.testVault).Times(1) strg.EXPECT().Close().Return(nil).Times(1) wlt, err := New(t.Context(), strg, WithOfflineProvider()) require.NoError(t, err) _, err = wlt.Balance(td.RandAccAddress().String()) require.ErrorIs(t, err, offline.ErrOffline) wlt.Close() } ================================================ FILE: www/grpc/README.md ================================================ # gRPC This directory contains required files for [gRPC](https://github.com/grpc-ecosystem/grpc-gateway) service. In order to compile [pactus.proto](./proto/pactus.proto) file, run this command: ```bash make proto ``` ================================================ FILE: www/grpc/basicauth/basicauth.go ================================================ package basicauth import ( "context" "encoding/base64" "fmt" ) // EncodeBasicAuth generates a Basic Authentication header value using the provided username and password // according to RFC 7617. It formats the authString as "username:password", encodes it in base64, // and returns the Basic Auth header in the format "Basic ". func EncodeBasicAuth(username, password string) string { authString := fmt.Sprintf("%s:%s", username, password) encodedAuth := base64.StdEncoding.EncodeToString([]byte(authString)) return fmt.Sprintf("Basic %s", encodedAuth) } // BasicAuth is an implementation of grpc.PerRPCCredentials based on the Basic HTTP Authentication Schema. type BasicAuth struct { Username string Password string } func New(username, password string) *BasicAuth { return &BasicAuth{ Username: username, Password: password, } } // GetRequestMetadata gets the request metadata as a map of strings. func (b *BasicAuth) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { return map[string]string{ "authorization": EncodeBasicAuth(b.Username, b.Password), }, nil } // RequireTransportSecurity indicates whether the credentials requires transport security. func (*BasicAuth) RequireTransportSecurity() bool { return false } ================================================ FILE: www/grpc/basicauth/basicauth_test.go ================================================ package basicauth import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestMakeCredentials(t *testing.T) { tests := []struct { username string password string expected string }{ {"user", "pass", "Basic dXNlcjpwYXNz"}, {"admin", "admin123", "Basic YWRtaW46YWRtaW4xMjM="}, {"", "", "Basic Og=="}, {"test", "123£", "Basic dGVzdDoxMjPCow=="}, } // Iterate over test cases for _, tt := range tests { t.Run(fmt.Sprintf("Username: %s, Password: %s", tt.username, tt.password), func(t *testing.T) { // Call basicAuth function result := EncodeBasicAuth(tt.username, tt.password) // Check if the result matches the expected output assert.Equal(t, tt.expected, result) }) } } ================================================ FILE: www/grpc/blockchain.go ================================================ package grpc import ( "context" "encoding/hex" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/account" "github.com/pactus-project/pactus/types/validator" "github.com/pactus-project/pactus/types/vote" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type blockchainServer struct { *Server } func newBlockchainServer(server *Server) *blockchainServer { return &blockchainServer{ Server: server, } } func (s *blockchainServer) GetBlockchainInfo(_ context.Context, _ *pactus.GetBlockchainInfoRequest, ) (*pactus.GetBlockchainInfoResponse, error) { chainInfo := s.state.ChainInfo() inCommittee := false committeeVals := s.state.CommitteeValidators() for _, cons := range s.consMgr.Instances() { for _, val := range committeeVals { if cons.ConsensusKey().EqualsTo(val.PublicKey()) { inCommittee = true break } } } return &pactus.GetBlockchainInfoResponse{ LastBlockHeight: uint32(chainInfo.LastBlockHeight), LastBlockHash: chainInfo.LastBlockHash.String(), LastBlockTime: chainInfo.LastBlockTime.Unix(), TotalAccounts: chainInfo.TotalAccounts, TotalValidators: chainInfo.TotalValidators, ActiveValidators: chainInfo.ActiveValidators, AverageScore: chainInfo.AverageScore, TotalPower: chainInfo.TotalPower, CommitteePower: chainInfo.CommitteePower, CommitteeSize: int32(chainInfo.CommitteeSize), IsPruned: chainInfo.IsPruned, PruningHeight: uint32(chainInfo.PruningHeight), InCommittee: inCommittee, }, nil } func (s *blockchainServer) GetCommitteeInfo(_ context.Context, _ *pactus.GetCommitteeInfoRequest, ) (*pactus.GetCommitteeInfoResponse, error) { info := s.state.CommitteeInfo() chainInfo := s.state.ChainInfo() valInfos := make([]*pactus.ValidatorInfo, 0, len(info.Validators)) for _, val := range info.Validators { valInfos = append(valInfos, s.validatorToProto(val)) } protocolVersions := make(map[int32]float64) for k, v := range info.ProtocolVersions { protocolVersions[int32(k)] = v } return &pactus.GetCommitteeInfoResponse{ Validators: valInfos, ProtocolVersions: protocolVersions, CommitteePower: info.CommitteePower, CommitteeSize: int32(len(info.Validators)), TotalPower: chainInfo.TotalPower, }, nil } func (s *blockchainServer) GetConsensusInfo(_ context.Context, _ *pactus.GetConsensusInfoRequest, ) (*pactus.GetConsensusInfoResponse, error) { consInstances := s.consMgr.Instances() instances := make([]*pactus.ConsensusInfo, 0, len(consInstances)) for _, cons := range consInstances { height, round := cons.HeightRound() votes := cons.AllVotes() voteInfos := make([]*pactus.VoteInfo, 0, len(votes)) for _, v := range votes { voteInfos = append(voteInfos, s.voteToProto(v)) } instances = append(instances, &pactus.ConsensusInfo{ Address: cons.ConsensusKey().ValidatorAddress().String(), Active: cons.IsActive(), Height: uint32(height), Round: int32(round), Votes: voteInfos, }) } var proposalInfo *pactus.ProposalInfo prop := s.consMgr.Proposal() if prop != nil { var blockData string data, err := prop.Block().Bytes() if err != nil { return nil, status.Error(codes.Internal, err.Error()) } blockData = hex.EncodeToString(data) proposalInfo = &pactus.ProposalInfo{ Height: uint32(prop.Height()), Round: int32(prop.Round()), BlockData: blockData, Signature: prop.Signature().String(), } } return &pactus.GetConsensusInfoResponse{ Instances: instances, Proposal: proposalInfo, }, nil } func (s *blockchainServer) GetBlockHash(_ context.Context, req *pactus.GetBlockHashRequest, ) (*pactus.GetBlockHashResponse, error) { height := req.GetHeight() h := s.state.BlockHash(types.Height(height)) if h.IsUndef() { return nil, status.Errorf(codes.NotFound, "block not found with this height") } return &pactus.GetBlockHashResponse{ Hash: h.String(), }, nil } func (s *blockchainServer) GetBlockHeight(_ context.Context, req *pactus.GetBlockHeightRequest, ) (*pactus.GetBlockHeightResponse, error) { h, err := hash.FromString(req.GetHash()) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err) } height := s.state.BlockHeight(h) if height == 0 { return nil, status.Errorf(codes.NotFound, "block not found with this hash") } return &pactus.GetBlockHeightResponse{ Height: uint32(height), }, nil } func (s *blockchainServer) GetBlock(_ context.Context, req *pactus.GetBlockRequest, ) (*pactus.GetBlockResponse, error) { height := req.GetHeight() cBlk, err := s.state.CommittedBlock(types.Height(height)) if err != nil { return nil, status.Errorf(codes.NotFound, "block not found") } res := &pactus.GetBlockResponse{ Height: uint32(cBlk.Height), Hash: cBlk.BlockHash.String(), } switch req.Verbosity { case pactus.BlockVerbosity_BLOCK_VERBOSITY_DATA: res.Data = hex.EncodeToString(cBlk.Data) case pactus.BlockVerbosity_BLOCK_VERBOSITY_INFO, pactus.BlockVerbosity_BLOCK_VERBOSITY_TRANSACTIONS: block, err := cBlk.ToBlock() if err != nil { return nil, status.Error(codes.Internal, err.Error()) } blockTime := block.Header().UnixTime() seed := block.Header().SortitionSeed() cert := block.PrevCertificate() var prevCert *pactus.CertificateInfo if cert != nil { committers := make([]int32, len(cert.Committers())) for i, n := range cert.Committers() { committers[i] = n } absentees := make([]int32, len(cert.Absentees())) for i, n := range cert.Absentees() { absentees[i] = n } prevCert = &pactus.CertificateInfo{ Hash: cert.Hash().String(), Round: int32(cert.Round()), Committers: committers, Absentees: absentees, Signature: cert.Signature().String(), } } header := &pactus.BlockHeaderInfo{ Version: int32(block.Header().Version()), PrevBlockHash: block.Header().PrevBlockHash().String(), StateRoot: block.Header().StateRoot().String(), SortitionSeed: hex.EncodeToString(seed[:]), ProposerAddress: block.Header().ProposerAddress().String(), } lastBlockHeight := s.state.LastBlockHeight() confirmations := int(lastBlockHeight) - int(cBlk.Height) trxs := make([]*pactus.TransactionInfo, 0, block.Transactions().Len()) for _, trx := range block.Transactions() { if req.Verbosity == pactus.BlockVerbosity_BLOCK_VERBOSITY_INFO { data, _ := trx.Bytes() trxs = append(trxs, &pactus.TransactionInfo{ Id: trx.ID().String(), Data: hex.EncodeToString(data), }) } else { trxs = append(trxs, transactionToProto(trx, cBlk.Height, confirmations)) } } res.BlockTime = blockTime res.Header = header res.Txs = trxs res.PrevCert = prevCert } return res, nil } func (s *blockchainServer) GetAccount(_ context.Context, req *pactus.GetAccountRequest, ) (*pactus.GetAccountResponse, error) { addr, err := crypto.AddressFromString(req.Address) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid address: %v", err) } acc, err := s.state.AccountByAddress(addr) if err != nil { return nil, status.Errorf(codes.NotFound, "account not found") } res := &pactus.GetAccountResponse{ Account: s.accountToProto(addr, acc), } return res, nil } func (s *blockchainServer) GetValidatorByNumber(_ context.Context, req *pactus.GetValidatorByNumberRequest, ) (*pactus.GetValidatorResponse, error) { val, err := s.state.ValidatorByNumber(req.Number) if err != nil { return nil, status.Errorf(codes.NotFound, "validator not found") } return &pactus.GetValidatorResponse{ Validator: s.validatorToProto(val), }, nil } func (s *blockchainServer) GetValidator(_ context.Context, req *pactus.GetValidatorRequest, ) (*pactus.GetValidatorResponse, error) { addr, err := crypto.AddressFromString(req.Address) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid validator address: %v", err.Error()) } val, err := s.state.ValidatorByAddress(addr) if err != nil { return nil, status.Errorf(codes.NotFound, "validator not found") } return &pactus.GetValidatorResponse{ Validator: s.validatorToProto(val), }, nil } func (s *blockchainServer) GetValidatorAddresses(_ context.Context, _ *pactus.GetValidatorAddressesRequest, ) (*pactus.GetValidatorAddressesResponse, error) { addresses := s.state.ValidatorAddresses() addressesPB := make([]string, 0, len(addresses)) for _, address := range addresses { addressesPB = append(addressesPB, address.String()) } return &pactus.GetValidatorAddressesResponse{Addresses: addressesPB}, nil } func (s *blockchainServer) GetPublicKey(_ context.Context, req *pactus.GetPublicKeyRequest, ) (*pactus.GetPublicKeyResponse, error) { addr, err := crypto.AddressFromString(req.Address) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid account address: %v", err.Error()) } publicKey, err := s.state.PublicKey(addr) if err != nil { return nil, status.Errorf(codes.NotFound, "public key not found") } return &pactus.GetPublicKeyResponse{PublicKey: publicKey.String()}, nil } func (s *blockchainServer) GetTxPoolContent(_ context.Context, req *pactus.GetTxPoolContentRequest, ) (*pactus.GetTxPoolContentResponse, error) { result := make([]*pactus.TransactionInfo, 0) for _, t := range s.state.AllPendingTxs() { if req.PayloadType == pactus.PayloadType_PAYLOAD_TYPE_UNSPECIFIED || req.PayloadType == pactus.PayloadType(t.Payload().Type()) { result = append(result, transactionToProto(t, 0, 0)) } } return &pactus.GetTxPoolContentResponse{ Txs: result, }, nil } func (s *blockchainServer) validatorToProto(val *validator.Validator) *pactus.ValidatorInfo { data, _ := val.Bytes() isDelegated := val.IsDelegated() var delegateOwner string var delegateShare int64 var delegateExpiry uint32 if isDelegated { // For non-delegated validators these fields are left empty/zero. // This makes the response consistent with the intent of PIP-49 delegation. delegateOwner = val.DelegateOwner().String() delegateShare = val.DelegateShare().ToNanoPAC() delegateExpiry = uint32(val.DelegateExpiry()) } return &pactus.ValidatorInfo{ Hash: val.Hash().String(), Data: hex.EncodeToString(data), PublicKey: val.PublicKey().String(), Address: val.Address().String(), Number: val.Number(), Stake: val.Stake().ToNanoPAC(), LastBondingHeight: uint32(val.LastBondingHeight()), LastSortitionHeight: uint32(val.LastSortitionHeight()), UnbondingHeight: uint32(val.UnbondingHeight()), AvailabilityScore: s.state.AvailabilityScore(val.Number()), ProtocolVersion: int32(val.ProtocolVersion()), IsDelegated: isDelegated, DelegateOwner: delegateOwner, DelegateShare: delegateShare, DelegateExpiry: delegateExpiry, } } func (*blockchainServer) accountToProto(addr crypto.Address, acc *account.Account) *pactus.AccountInfo { data, _ := acc.Bytes() return &pactus.AccountInfo{ Hash: acc.Hash().String(), Data: hex.EncodeToString(data), Number: acc.Number(), Balance: acc.Balance().ToNanoPAC(), Address: addr.String(), } } func (*blockchainServer) voteToProto(vte *vote.Vote) *pactus.VoteInfo { cpRound := int32(0) cpValue := int32(0) if vte.IsCPVote() { cpRound = int32(vte.CPRound()) cpValue = int32(vte.CPValue()) } return &pactus.VoteInfo{ Type: pactus.VoteType(vte.Type()), Voter: vte.Signer().String(), BlockHash: vte.BlockHash().String(), Round: int32(vte.Round()), CpRound: cpRound, CpValue: cpValue, } } ================================================ FILE: www/grpc/blockchain_test.go ================================================ package grpc import ( "encoding/hex" "testing" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/tx" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetBlock(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) height := types.Height(100) blk := td.mockState.TestStore.AddTestBlock(height) data, _ := blk.Bytes() t.Run("Should return nil for non existing block ", func(t *testing.T) { res, err := client.GetBlock(t.Context(), &pactus.GetBlockRequest{ Height: uint32(height + 1), Verbosity: pactus.BlockVerbosity_BLOCK_VERBOSITY_DATA, }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return an existing block data (verbosity: 0)", func(t *testing.T) { res, err := client.GetBlock(t.Context(), &pactus.GetBlockRequest{Height: uint32(height), Verbosity: pactus.BlockVerbosity_BLOCK_VERBOSITY_DATA}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, uint32(height), res.Height) assert.Equal(t, blk.Hash().String(), res.Hash) assert.Equal(t, hex.EncodeToString(data), res.Data) assert.Empty(t, res.Header) assert.Empty(t, res.Txs) }) t.Run("Should return object with (verbosity: 1)", func(t *testing.T) { res, err := client.GetBlock(t.Context(), &pactus.GetBlockRequest{Height: uint32(height), Verbosity: pactus.BlockVerbosity_BLOCK_VERBOSITY_INFO}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, uint32(height), res.Height) assert.Equal(t, blk.Hash().String(), res.Hash) assert.Empty(t, res.Data) assert.NotEmpty(t, res.Header) assert.Equal(t, blk.PrevCertificate().Committers(), res.PrevCert.Committers) assert.Equal(t, blk.PrevCertificate().Absentees(), res.PrevCert.Absentees) for i, trx := range res.Txs { blockTrx := blk.Transactions()[i] blk, err := blockTrx.Bytes() require.NoError(t, err) assert.Equal(t, trx.Id, blockTrx.ID().String()) assert.Equal(t, trx.Data, hex.EncodeToString(blk)) assert.Zero(t, trx.LockTime) assert.Empty(t, trx.Signature) assert.Empty(t, trx.PublicKey) } }) t.Run("Should return object with (verbosity: 2)", func(t *testing.T) { res, err := client.GetBlock(t.Context(), &pactus.GetBlockRequest{Height: uint32(height), Verbosity: pactus.BlockVerbosity_BLOCK_VERBOSITY_TRANSACTIONS}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, uint32(height), res.Height) assert.Equal(t, blk.Hash().String(), res.Hash) assert.Empty(t, res.Data) assert.NotEmpty(t, res.Header) assert.NotEmpty(t, res.Txs) for i, trx := range res.Txs { blockTrx := blk.Transactions()[i] assert.Equal(t, trx.Id, blockTrx.ID().String()) assert.Empty(t, trx.Data) assert.Equal(t, uint32(blockTrx.LockTime()), trx.LockTime) if blockTrx.IsSubsidyTx() { assert.Empty(t, trx.Signature) assert.Empty(t, trx.PublicKey) } else { assert.Equal(t, trx.Signature, blockTrx.Signature().String()) assert.Equal(t, trx.PublicKey, blockTrx.PublicKey().String()) } } }) } func TestGetBlockHash(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) height := td.RandHeight() blk := td.mockState.TestStore.AddTestBlock(height) t.Run("Should return error for non existing block", func(t *testing.T) { res, err := client.GetBlockHash(t.Context(), &pactus.GetBlockHashRequest{Height: 0}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return height of existing block", func(t *testing.T) { res, err := client.GetBlockHash(t.Context(), &pactus.GetBlockHashRequest{Height: uint32(height)}) require.NoError(t, err) assert.Equal(t, blk.Hash().String(), res.Hash) }) } func TestGetBlockHeight(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) height := td.RandHeight() blk := td.mockState.TestStore.AddTestBlock(height) t.Run("Should return error for invalid hash", func(t *testing.T) { res, err := client.GetBlockHeight(t.Context(), &pactus.GetBlockHeightRequest{Hash: ""}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return error for non existing block", func(t *testing.T) { res, err := client.GetBlockHeight(t.Context(), &pactus.GetBlockHeightRequest{Hash: td.RandHash().String()}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return height of existing block", func(t *testing.T) { res, err := client.GetBlockHeight(t.Context(), &pactus.GetBlockHeightRequest{Hash: blk.Hash().String()}) require.NoError(t, err) assert.Equal(t, uint32(height), res.Height) }) } func TestGetBlockchainInfo(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) t.Run("Should return the last block height", func(t *testing.T) { res, err := client.GetBlockchainInfo(t.Context(), &pactus.GetBlockchainInfoRequest{}) require.NoError(t, err) assert.Equal(t, uint32(td.mockState.TestStore.LastHeight), res.LastBlockHeight) assert.NotEmpty(t, res.LastBlockHash) assert.Zero(t, res.PruningHeight) assert.False(t, res.IsPruned) }) } func TestGetCommitteeInfo(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) t.Run("Should return committee info", func(t *testing.T) { res, err := client.GetCommitteeInfo(t.Context(), &pactus.GetCommitteeInfoRequest{}) require.NoError(t, err) assert.NotNil(t, res) assert.GreaterOrEqual(t, res.CommitteePower, int64(0)) assert.NotNil(t, res.Validators) assert.NotNil(t, res.ProtocolVersions) }) } func TestGetAccount(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) addr, acc := td.mockState.TestStore.AddTestAccount() t.Run("Should return error for non-parsable address ", func(t *testing.T) { res, err := client.GetAccount(t.Context(), &pactus.GetAccountRequest{Address: ""}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return nil for non existing account ", func(t *testing.T) { res, err := client.GetAccount(t.Context(), &pactus.GetAccountRequest{Address: td.RandAccAddress().String()}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return account details", func(t *testing.T) { res, err := client.GetAccount(t.Context(), &pactus.GetAccountRequest{Address: addr.String()}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, acc.Balance().ToNanoPAC(), res.Account.Balance) assert.Equal(t, acc.Number(), res.Account.Number) }) } func TestGetValidator(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) val1 := td.mockState.TestStore.AddTestValidator() t.Run("Should return nil value due to invalid address", func(t *testing.T) { res, err := client.GetValidator(t.Context(), &pactus.GetValidatorRequest{Address: ""}) require.Error(t, err, "Error should be returned") assert.Nil(t, res, "Response should be empty") }) t.Run("should return Not Found", func(t *testing.T) { res, err := client.GetValidator(t.Context(), &pactus.GetValidatorRequest{Address: td.RandAccAddress().String()}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return validator, and the public keys should match", func(t *testing.T) { res, err := client.GetValidator(t.Context(), &pactus.GetValidatorRequest{Address: val1.Address().String()}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, val1.PublicKey().String(), res.GetValidator().PublicKey) }) t.Run("Should return delegation info for delegated validators", func(t *testing.T) { dlgOwnerAddr := td.RandAccAddress() dlgOwnerShare := td.RandAmount() dlgExpiry := td.RandHeight() val1.SetDelegation(dlgOwnerAddr, dlgOwnerShare, dlgExpiry) td.mockState.TestStore.UpdateValidator(val1) res, err := client.GetValidator(t.Context(), &pactus.GetValidatorRequest{Address: val1.Address().String()}) require.NoError(t, err) assert.NotNil(t, res) v := res.GetValidator() assert.True(t, v.IsDelegated) assert.Equal(t, dlgOwnerAddr.String(), v.DelegateOwner) assert.Equal(t, dlgOwnerShare.ToNanoPAC(), v.DelegateShare) assert.Equal(t, uint32(dlgExpiry), v.DelegateExpiry) }) } func TestGetValidatorByNumber(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) val1 := td.mockState.TestStore.AddTestValidator() t.Run("Should return nil value due to invalid number", func(t *testing.T) { res, err := client.GetValidatorByNumber(t.Context(), &pactus.GetValidatorByNumberRequest{Number: -1}) require.Error(t, err) assert.Nil(t, res) }) t.Run("should return Not Found", func(t *testing.T) { res, err := client.GetValidatorByNumber(t.Context(), &pactus.GetValidatorByNumberRequest{Number: val1.Number() + 1}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return validator matching with public key and number", func(t *testing.T) { res, err := client.GetValidatorByNumber(t.Context(), &pactus.GetValidatorByNumberRequest{Number: val1.Number()}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, val1.PublicKey().String(), res.GetValidator().PublicKey) assert.Equal(t, val1.Number(), res.GetValidator().GetNumber()) }) } func TestGetValidatorAddresses(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) t.Run("should return list of validator addresses", func(t *testing.T) { td.mockState.TestStore.AddTestValidator() td.mockState.TestStore.AddTestValidator() res, err := client.GetValidatorAddresses(t.Context(), &pactus.GetValidatorAddressesRequest{}) require.NoError(t, err) assert.NotNil(t, res) assert.Len(t, res.GetAddresses(), 2) }) } func TestGetPublicKey(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) val := td.mockState.TestStore.AddTestValidator() t.Run("Should return error for non-parsable address ", func(t *testing.T) { res, err := client.GetPublicKey(t.Context(), &pactus.GetPublicKeyRequest{Address: ""}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return nil for non existing public key ", func(t *testing.T) { res, err := client.GetPublicKey(t.Context(), &pactus.GetPublicKeyRequest{Address: td.RandAccAddress().String()}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return the public key", func(t *testing.T) { res, err := client.GetPublicKey(t.Context(), &pactus.GetPublicKeyRequest{Address: val.Address().String()}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, val.PublicKey().String(), res.PublicKey) }) } func TestConsensusInfo(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) consHeight := td.RandHeight() consRound := td.RandRound() vote1, _ := td.GenerateTestPrepareVote(consHeight, consRound) vote2, _ := td.GenerateTestPrecommitVote(consHeight, consRound) prop := td.GenerateTestProposal(consHeight, consRound) td.consMocks[0].Active = true td.consMocks[0].Height = consHeight td.consMocks[0].Round = consRound td.consMocks[0].AddVote(vote1) td.consMocks[0].AddVote(vote2) td.consMocks[0].SetProposal(prop) td.consMocks[1].Active = false td.consMocks[1].Height = consHeight td.consMocks[1].Round = consRound t.Run("Should return the consensus info", func(t *testing.T) { res, err := client.GetConsensusInfo(t.Context(), &pactus.GetConsensusInfoRequest{}) require.NoError(t, err) assert.NotNil(t, res) assert.True(t, res.Instances[0].Active) assert.Equal(t, uint32(consHeight), res.Instances[0].Height) assert.Equal(t, int32(consRound), res.Instances[0].Round) assert.Len(t, res.Instances[0].Votes, 2) assert.Equal(t, pactus.VoteType_VOTE_TYPE_PREPARE, res.Instances[0].Votes[0].Type) assert.Equal(t, pactus.VoteType_VOTE_TYPE_PRECOMMIT, res.Instances[0].Votes[1].Type) assert.False(t, res.Instances[1].Active) assert.Equal(t, uint32(consHeight), res.Instances[1].Height) assert.Equal(t, int32(consRound), res.Instances[1].Round) assert.Equal(t, uint32(consHeight), res.Proposal.Height) assert.Equal(t, int32(consRound), res.Proposal.Round) assert.Equal(t, prop.Signature().String(), res.Proposal.Signature) }) } func TestGetTxPoolContent(t *testing.T) { td := setup(t, nil) client := td.blockchainClient(t) trx1 := td.GenerateTestTransferTx() trx2 := td.GenerateTestBatchTransferTx() trx3 := td.GenerateTestSubsidyTx() trx4 := td.GenerateTestBondTx() trx5 := td.GenerateTestUnbondTx() trx6 := td.GenerateTestSortitionTx() trx7 := td.GenerateTestWithdrawTx() td.mockState.MockTxPool.EXPECT().AllPendingTxs().Return([]*tx.Tx{ trx1, trx2, trx3, trx4, trx5, trx6, trx7, }).AnyTimes() t.Run("Should return all transactions", func(t *testing.T) { in := &pactus.GetTxPoolContentRequest{ PayloadType: pactus.PayloadType_PAYLOAD_TYPE_UNSPECIFIED, } resp, err := client.GetTxPoolContent(t.Context(), in) require.NoError(t, err) assert.NotNil(t, resp) assert.Len(t, resp.Txs, 7) }) t.Run("Should return transactions by type", func(t *testing.T) { payloadTypes := []pactus.PayloadType{ pactus.PayloadType_PAYLOAD_TYPE_TRANSFER, pactus.PayloadType_PAYLOAD_TYPE_BOND, pactus.PayloadType_PAYLOAD_TYPE_SORTITION, pactus.PayloadType_PAYLOAD_TYPE_UNBOND, pactus.PayloadType_PAYLOAD_TYPE_WITHDRAW, pactus.PayloadType_PAYLOAD_TYPE_BATCH_TRANSFER, } for _, payloadType := range payloadTypes { in := &pactus.GetTxPoolContentRequest{ PayloadType: payloadType, } resp, err := client.GetTxPoolContent(t.Context(), in) require.NoError(t, err) assert.NotNil(t, resp) assert.NotEmpty(t, resp.Txs) for _, tx := range resp.Txs { assert.Equal(t, payloadType, tx.PayloadType) } } }) } ================================================ FILE: www/grpc/buf/buf.gen.yaml ================================================ version: v2 plugins: - local: protoc-gen-cobra out: ./gen/go opt: paths=source_relative - local: protoc-gen-doc out: ./gen/open-rpc opt: ./buf/templates/openrpc.tmpl,pactus-openrpc.json - local: protoc-gen-doc out: ./gen/docs opt: ./buf/templates/components.tmpl;./buf/templates/grpc.md.tmpl,grpc.md - local: protoc-gen-doc out: ./gen/docs opt: ./buf/templates/components.tmpl;./buf/templates/json-rpc.md.tmpl,json-rpc.md - local: protoc-gen-jrpc-gateway out: ./gen/go - local: protoc-gen-grpc-gateway out: ./gen/go opt: - paths=source_relative - grpc_api_configuration=./buf/grpc-gateway.config.yaml - local: protoc-gen-openapiv2 out: ../http/swagger-ui opt: - grpc_api_configuration=./buf/grpc-gateway.config.yaml,allow_merge=true,merge_file_name=pactus - openapi_configuration=./buf/openapi.config.yaml # https://buf.build/protocolbuffers/go - remote: buf.build/protocolbuffers/go:v1.36.11 out: ./gen/go opt: paths=source_relative # https://buf.build/grpc/go - remote: buf.build/grpc/go:v1.6.0 out: ./gen/go opt: paths=source_relative,require_unimplemented_servers=false # https://buf.build/protocolbuffers/js - remote: buf.build/protocolbuffers/js:v4.0.1 out: ./gen/js opt: - import_style=commonjs - binary # https://buf.build/grpc/node - remote: buf.build/grpc/node:v1.13.1 out: ./gen/js opt: - import_style=commonjs - grpc_js # https://buf.build/grpc/web - remote: buf.build/grpc/web:v2.0.2 out: ./gen/js opt: - import_style=commonjs - mode=grpcweb # https://buf.build/protocolbuffers/dart - remote: buf.build/protocolbuffers/dart:v25.0.0 out: ./gen/dart # https://buf.build/protocolbuffers/java - remote: buf.build/protocolbuffers/java:v33.2 out: ./gen/java # https://buf.build/grpc/java - remote: buf.build/grpc/java:v1.77.0 out: ./gen/java # https://buf.build/protocolbuffers/python - remote: buf.build/protocolbuffers/python:v33.2 out: ./gen/python # https://buf.build/grpc/python - remote: buf.build/grpc/python:v1.76.0 out: ./gen/python # https://buf.build/protocolbuffers/pyi - remote: buf.build/protocolbuffers/pyi:v33.2 out: ./gen/python # https://buf.build/community/neoeinstein-prost # https://github.com/neoeinstein/protoc-gen-prost - remote: buf.build/community/neoeinstein-prost:v0.5.0 out: ./gen/rust opt: - flat_output_dir=true - compile_well_known_types=true # https://buf.build/community/neoeinstein-prost-serde # https://github.com/neoeinstein/protoc-gen-prost - remote: buf.build/community/neoeinstein-prost-serde:v0.4.0 out: ./gen/rust opt: - flat_output_dir=true # https://buf.build/community/neoeinstein-tonic # https://github.com/neoeinstein/protoc-gen-prost - remote: buf.build/community/neoeinstein-tonic:v0.5.0 out: ./gen/rust opt: - flat_output_dir=true - compile_well_known_types=true ================================================ FILE: www/grpc/buf/buf.yaml ================================================ # For details on buf.yaml configuration, visit https://buf.build/docs/configuration/v2/buf-yaml version: v2 modules: - path: ./proto lint: use: - STANDARD - COMMENT_ENUM - COMMENT_ENUM_VALUE - COMMENT_FIELD - COMMENT_MESSAGE - COMMENT_ONEOF - COMMENT_RPC - COMMENT_SERVICE - RPC_NO_CLIENT_STREAMING - RPC_NO_SERVER_STREAMING except: - PACKAGE_DIRECTORY_MATCH - PACKAGE_VERSION_SUFFIX - SERVICE_SUFFIX - RPC_REQUEST_RESPONSE_UNIQUE - RPC_RESPONSE_STANDARD_NAME - ENUM_ZERO_VALUE_SUFFIX disallow_comment_ignores: true ================================================ FILE: www/grpc/buf/grpc-gateway.config.yaml ================================================ type: google.api.Service config_version: 3 http: rules: # Blockchain APIs - selector: pactus.Blockchain.GetBlock get: "/pactus/blockchain/get_block" - selector: pactus.Blockchain.GetBlockHash get: "/pactus/blockchain/get_block_hash" - selector: pactus.Blockchain.GetBlockHeight get: "/pactus/blockchain/get_block_height" - selector: pactus.Blockchain.GetAccount get: "/pactus/blockchain/get_account" - selector: pactus.Blockchain.GetValidator get: "/pactus/blockchain/get_validator" - selector: pactus.Blockchain.GetValidatorByNumber get: "/pactus/blockchain/get_validator_by_number" - selector: pactus.Blockchain.GetValidatorAddresses get: "/pactus/blockchain/get_validator_addresses" - selector: pactus.Blockchain.GetBlockchainInfo get: "/pactus/blockchain/get_blockchain_info" - selector: pactus.Blockchain.GetCommitteeInfo get: "/pactus/blockchain/get_committee_info" - selector: pactus.Blockchain.GetConsensusInfo get: "/pactus/blockchain/get_consensus_info" - selector: pactus.Blockchain.GetPublicKey get: "/pactus/blockchain/get_public_key" - selector: pactus.Blockchain.GetTxPoolContent get: "/pactus/blockchain/get_txpool_content" # Transaction APIs - selector: pactus.Transaction.GetTransaction get: "/pactus/transaction/get_transaction" - selector: pactus.Transaction.BroadcastTransaction post: "/pactus/transaction/broadcast_transaction" body: "*" - selector: pactus.Transaction.CalculateFee post: "/pactus/transaction/calculate_fee" body: "*" - selector: pactus.Transaction.GetRawTransferTransaction post: "/pactus/transaction/get_raw_transfer_transaction" body: "*" - selector: pactus.Transaction.GetRawBondTransaction post: "/pactus/transaction/get_raw_bond_transaction" body: "*" - selector: pactus.Transaction.GetRawUnbondTransaction post: "/pactus/transaction/get_raw_unbond_transaction" body: "*" - selector: pactus.Transaction.GetRawWithdrawTransaction post: "/pactus/transaction/get_raw_withdraw_transaction" body: "*" - selector: pactus.Transaction.DecodeRawTransaction post: "/pactus/transaction/decode_raw_transaction" body: "*" - selector: pactus.Transaction.GetRawBatchTransferTransaction post: "/pactus/transaction/get_raw_batch_transfer_transaction" body: "*" # Network APIs - selector: pactus.Network.GetNetworkInfo get: "/pactus/network/get_network_info" - selector: pactus.Network.GetNodeInfo get: "/pactus/network/get_node_info" # Wallet APIs - selector: pactus.Wallet.GetValidatorAddress get: "/pactus/wallet/get_validator_address" - selector: pactus.Wallet.CreateWallet post: "/pactus/wallet/create_wallet" body: "*" - selector: pactus.Wallet.RestoreWallet post: "/pactus/wallet/restore_wallet" body: "*" - selector: pactus.Wallet.LoadWallet post: "/pactus/wallet/load_wallet" body: "*" - selector: pactus.Wallet.UnloadWallet post: "/pactus/wallet/unload_wallet" body: "*" - selector: pactus.Wallet.ListWallets get: "/pactus/wallet/list_wallets" - selector: pactus.Wallet.GetWalletInfo get: "/pactus/wallet/get_wallet_info" - selector: pactus.Wallet.UpdatePassword post: "/pactus/wallet/update_password" body: "*" - selector: pactus.Wallet.SignRawTransaction post: "/pactus/wallet/sign_raw_transaction" body: "*" - selector: pactus.Wallet.GetNewAddress post: "/pactus/wallet/get_new_address" body: "*" - selector: pactus.Wallet.GetTotalBalance get: "/pactus/wallet/get_total_balance" - selector: pactus.Wallet.SignMessage post: "/pactus/wallet/sign_message" body: "*" - selector: pactus.Wallet.GetTotalStake get: "/pactus/wallet/get_total_stake" - selector: pactus.Wallet.GetAddressInfo get: "/pactus/wallet/get_address_info" - selector: pactus.Wallet.SetAddressLabel patch: "/pactus/wallet/set_address_label" - selector: pactus.Wallet.ListAddresses get: "/pactus/wallet/list_addresses" - selector: pactus.Wallet.ListTransactions get: "/pactus/wallet/list_transactions" # Util APIs - selector: pactus.Utils.SignMessageWithPrivateKey post: "/pactus/Utils/sign_message_with_private_key" body: "*" - selector: pactus.Utils.VerifyMessage post: "/pactus/Utils/verify_message" body: "*" - selector: pactus.Utils.PublicKeyAggregation post: "/pactus/Utils/public_key_aggregation" body: "*" - selector: pactus.Utils.SignatureAggregation post: "/pactus/Utils/signature_aggregation" body: "*" - selector: pactus.Network.Ping get: "/pactus/network/ping" ================================================ FILE: www/grpc/buf/openapi.config.yaml ================================================ # Example # https://github.com/grpc-ecosystem/grpc-gateway/blob/main/examples/internal/proto/examplepb/unannotated_echo_service.swagger.yaml#L4 openapiOptions: file: - file: "transaction.proto" option: basePath: "/http/api" info: title: Pactus APIs version: "2.0" description: | Every node in the Pactus network can be configured to expose HTTP-APIs for communication. These APIs follow the [OpenAPI (Swagger)](https://swagger.io/specification/) specification, and a complete list of available endpoints can be found here. ## Units All the amounts are in NanoPAC units, which are atomic and the smallest unit in the Pactus blockchain. Each PAC is equivalent to 1,000,000,000 or 109 NanoPACs. contact: name: Pactus Blockchain url: https://pactus.org license: name: MIT License url: https://github.com/pactus-project/pactus/blob/main/LICENSE schemes: - HTTP - HTTPS securityDefinitions: security: BasicAuth: type: TYPE_BASIC security: - securityRequirement: BasicAuth: {} ================================================ FILE: www/grpc/buf/templates/components.tmpl ================================================ {{/* ---------- components ---------- */}} {{- define "field_desc"}} {{if .IsEnum}}(Enum){{end -}} {{if .IsOneOf}}(OneOf){{end -}} {{if (index .Options "deprecated"|default false)}}(Deprecated) {{end -}} {{.Description -}} {{if .DefaultValue}}Default: {{.DefaultValue}}{{end -}} {{with getEnum .LongType }}
Available values:
    {{range .Values -}}
  • {{.Name}} = {{.Number}} ({{ .Description }})
  • {{end -}}
{{- end -}} {{end -}} ================================================ FILE: www/grpc/buf/templates/grpc.md.tmpl ================================================ {{/* This template generates gRPC document for https://docs.pactus.org/api/grpc/ */}}--- title: GRPC API Reference weight: 1 --- Every node in the Pactus network can be configured to use the [gRPC](https://grpc.io/) protocol for communication. Here you can find the list of all gRPC methods and messages. ## Units All the amounts are in NanoPAC units, which are atomic and the smallest unit in the Pactus blockchain. Each PAC is equivalent to 1,000,000,000 or 109 NanoPACs. ## Packages For seamless integration with Pactus, you can use these client libraries: - [pactus-grpc](https://www.npmjs.com/package/pactus-grpc/) package for Javascript - [pactus-grpc](https://pypi.org/project/pactus-grpc/) package for Python - [pactus-grpc](https://crates.io/crates/pactus-grpc) package for Rust ## gRPC Services
    {{- range .Files -}} {{ range .Services }}
  • {{.Name}} Service
      {{- $service_name := .FullName -}} {{ range .Methods }}
    • {{.Name}}
    • {{- end }}
  • {{- end -}} {{- end }}
{{- range .Files -}} {{- range .Services }} ### {{.Name}} Service {{p .Description}} {{- $service_name := .FullName }} {{- range .Methods }} #### {{.Name}} {{p .Description}}

{{.RequestLongType}} Request

{{- with getMessage .RequestLongType }} {{ if .HasFields -}} {{ range .Fields -}} {{ end -}}
FieldTypeDescription
{{.Name}} {{.Label}} {{.LongType}} {{- template "field_desc" . }}
{{- else -}} Request Message has no fields. {{- end -}} {{- end }}

{{.ResponseLongType}} Response

{{- with getMessage .ResponseLongType }} {{ if .HasFields -}} {{ range .Fields -}} {{$msg0 := .}} {{with getMessage .LongType -}} {{- range .Fields -}} {{$msg1 := .}} {{with getMessage .LongType -}} {{- range .Fields -}} {{- end}}{{end}}{{end}}{{end}}{{end -}}
FieldTypeDescription
{{.Name}} {{.Label}} {{.LongType}} {{- template "field_desc" . }}
{{$msg0.Name}}{{if $msg0.IsRepeated}}[]{{end}}.{{.Name}} {{.Label}} {{.LongType}} {{- template "field_desc" . }}
{{$msg0.Name}}{{if $msg0.IsRepeated}}[]{{end}}.{{$msg1.Name}}{{if $msg1.IsRepeated}}[]{{end}}.{{.Name}} {{.Label}} {{.LongType}} {{- template "field_desc" . }}
{{- else -}} Response Message has no fields. {{- end}}{{end}}{{end}}{{end -}} {{- end -}} ## Scalar Value Types {{range .Scalars}} {{end}}
.proto TypeGoC++RustJavaPython
{{.ProtoType}} {{.GoType}} {{.CppType}} {{.RustType}} {{.JavaType}} {{.PythonType}}
================================================ FILE: www/grpc/buf/templates/json-rpc.md.tmpl ================================================ {{/* This template generates JSON-RPC document for https://docs.pactus.org/api/json-rpc/ */}}--- title: JSON-RPC API Reference weight: 2 --- Every node in the Pactus network can be configured to use the [JSON-RPC](https://www.jsonrpc.org/specification) protocol for communication. Here, you can find the list of all JSON-RPC methods, params and result. ## Units All the amounts are in NanoPAC units, which are atomic and the smallest unit in the Pactus blockchain. Each PAC is equivalent to 1,000,000,000 or 109 NanoPACs. ## Packages For seamless integration with Pactus, you can use these client libraries: - [pactus-jsonrpc](https://www.npmjs.com/package/pactus-jsonrpc/) package for Javascript - [pactus-jsonrpc](https://pypi.org/project/pactus-jsonrpc/) package for Python - [pactus-jsonrpc](https://crates.io/crates/pactus-jsonrpc) package for Rust ## Example To call JSON-RPC methods, you need to create the JSON-RPC request: ```json { "jsonrpc": "2.0", "id": 1, "method": "pactus.network.get_node_info", "params": {} } ``` > Make sure you always add the `params` field, even if no parameters are needed, and ensure you use curly braces. Then you use the `curl` command to send the request to the node: ```bash curl --location 'http://localhost:8545/' \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "pactus.network.get_node_info", "params": {} }' ``` > Before sending the request, you need to enable the JSON-RPC service inside the > [configuration](/get-started/configuration/). ### Using Basic Auth If you have enabled the [gRPC Basic Authentication](/tutorials/grpc-sign-transactions/), then you need to set the `Authorization` header. ```bash curl --location 'http://localhost:8545/' \ --header 'Content-Type: application/json' \ --header 'Authorization: Basic ' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "pactus.blockchain.get_account", "params": { "address": "pc1z2r0fmu8sg2ffa0tgrr08gnefcxl2kq7wvquf8z" } }' ``` ## JSON-RPC Methods
    {{- range .Files -}} {{ range .Services }}
  • {{.Name}} Service
      {{- $service_name := .SnakeName -}} {{ range .Methods }}
    • {{.SnakeName}}
    • {{- end }}
  • {{- end -}} {{- end }}
{{- range .Files -}} {{- range .Services }} ### {{.Name}} Service {{p .Description}} {{- $service_name := .FullName }} {{- range .Methods }} #### {{.SnakeName}} {{p .Description}}

Parameters

{{- with getMessage .RequestLongType }} {{ if .HasFields -}} {{ range .Fields -}} {{ end -}}
FieldTypeDescription
{{.SnakeName}} {{.Label}} {{.JSONType}} {{- template "field_desc" . }}
{{- else -}} Parameters has no fields. {{- end -}} {{- end }}

Result

{{- with getMessage .ResponseLongType }} {{ if .HasFields -}} {{- range .Fields -}} {{$msg0 := .}} {{with getMessage .LongType -}} {{- range .Fields -}} {{$msg1 := .}} {{with getMessage .LongType -}} {{- range .Fields -}} {{- end}}{{end}}{{end}}{{end}}{{end -}}
FieldTypeDescription
{{.Name}} {{.Label}} {{.JSONType}} {{- template "field_desc" . }}
{{$msg0.Name}}{{if $msg0.IsRepeated}}[]{{end}}.{{.Name}} {{.Label}} {{.JSONType}} {{- template "field_desc" . }}
{{$msg0.Name}}{{if $msg0.IsRepeated}}[]{{end}}.{{$msg1.Name}}{{if $msg1.IsRepeated}}[]{{end}}.{{.Name}} {{.Label}} {{.JSONType}} {{- template "field_desc" . }}
{{- else -}} Result has no fields. {{- end}}{{end}}{{end}}{{end -}} {{- end}}
================================================ FILE: www/grpc/buf/templates/openrpc.tmpl ================================================ { "openrpc": "1.2.1", "info": { "title": "Pactus OpenRPC", "version": "1.2.1" }, "methods": [ {{- $firstMethod := true -}} {{- range .Files -}} {{- range .Services -}}{{- $ServiceName := .SnakeName -}} {{ range .Methods }} {{- if not $firstMethod -}},{{- end -}} {{- $firstMethod = false -}} { "name": "{{ .SnakeName }}", "description": "{{ .Description | nobr }}", "tags": [{ "name": "{{ $ServiceName}}"}], "paramStructure": "by-name", "params": [ {{- with getMessage .RequestLongType -}} {{- $firstParam := true -}} {{ range .Fields }} {{- if not $firstParam -}},{{- end -}} {{- $firstParam = false -}} { "name": "{{ .SnakeName }}", "description": "{{ .Description | nobr }}", "schema": {{ template "renderFieldSchema" . }} } {{- end -}} {{- end -}} ], "result": { "name": "fields", "schema": { "type": "object", {{- with getMessage .ResponseLongType -}} "required": [ {{- $firstField := true -}} {{- range .Fields -}} {{- if not $firstField -}},{{- end -}} {{- $firstField = false -}} "{{ .SnakeName }}" {{- end -}} ], "properties": { {{- $firstField := true -}} {{- range .Fields -}} {{- if not $firstField -}},{{- end -}} {{- $firstField = false -}} "{{ .SnakeName }}": {{ template "renderFieldSchema" . -}} {{- end -}} {{- end -}} } } } } {{- end -}} {{- end -}} {{- end -}} ] } {{/* --- Helpers --- */}} {{ define "renderFieldSchema" }} {{- if .IsMap -}} { "type": "object" } {{- else if .IsRepeated -}} { "type": "array", "items": {{ template "renderFieldItemSchema" . }} } {{- else -}} {{- template "renderFieldItemSchema" . -}} {{- end -}} {{- end -}} {{- define "renderFieldItemSchema" -}} {{- if or (eq .OpenRPCType "string") (eq .OpenRPCType "boolean") (eq .OpenRPCType "integer") (eq .OpenRPCType "number") -}} { "type": "{{ .OpenRPCType }}" } {{- else -}} { "type": "object", {{- with getMessage .LongType -}} "required": [ {{- $firstField := true -}} {{- range .Fields -}} {{- if not $firstField -}},{{- end -}} {{- $firstField = false -}} "{{ .SnakeName }}" {{- end -}} ], "properties": { {{- $first := true -}} {{- range .Fields -}} {{- if not $first -}},{{- end -}} {{- $first = false -}} "{{ .SnakeName }}": {{ template "renderFieldSchema" . }} {{- end -}} {{- end -}} } } {{- end -}} {{- end -}} ================================================ FILE: www/grpc/config.go ================================================ package grpc import "github.com/pactus-project/pactus/util/htpasswd" // Config defines parameters for the gRPC server. type Config struct { Enable bool `toml:"enable"` EnableWallet bool `toml:"enable_wallet"` Listen string `toml:"listen"` BasicAuth string `toml:"basic_auth"` } func DefaultConfig() *Config { return &Config{ Enable: false, Listen: "", } } func (c *Config) BasicCheck() error { if c.BasicAuth != "" { if _, _, err := htpasswd.ExtractBasicAuth(c.BasicAuth); err != nil { return err } } return nil } ================================================ FILE: www/grpc/gen/dart/blockchain.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from blockchain.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'blockchain.pbenum.dart'; import 'transaction.pb.dart' as $0; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; export 'blockchain.pbenum.dart'; /// Request message for retrieving account information. class GetAccountRequest extends $pb.GeneratedMessage { factory GetAccountRequest({ $core.String? address, }) { final result = create(); if (address != null) result.address = address; return result; } GetAccountRequest._(); factory GetAccountRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetAccountRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetAccountRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAccountRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAccountRequest copyWith(void Function(GetAccountRequest) updates) => super.copyWith((message) => updates(message as GetAccountRequest)) as GetAccountRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetAccountRequest create() => GetAccountRequest._(); @$core.override GetAccountRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetAccountRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetAccountRequest? _defaultInstance; /// The address of the account to retrieve information for. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); } /// Response message contains account information. class GetAccountResponse extends $pb.GeneratedMessage { factory GetAccountResponse({ AccountInfo? account, }) { final result = create(); if (account != null) result.account = account; return result; } GetAccountResponse._(); factory GetAccountResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetAccountResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetAccountResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOM(1, _omitFieldNames ? '' : 'account', subBuilder: AccountInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAccountResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAccountResponse copyWith(void Function(GetAccountResponse) updates) => super.copyWith((message) => updates(message as GetAccountResponse)) as GetAccountResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetAccountResponse create() => GetAccountResponse._(); @$core.override GetAccountResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetAccountResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetAccountResponse? _defaultInstance; /// Detailed information about the account. @$pb.TagNumber(1) AccountInfo get account => $_getN(0); @$pb.TagNumber(1) set account(AccountInfo value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasAccount() => $_has(0); @$pb.TagNumber(1) void clearAccount() => $_clearField(1); @$pb.TagNumber(1) AccountInfo ensureAccount() => $_ensure(0); } /// Request message for retrieving validator addresses. class GetValidatorAddressesRequest extends $pb.GeneratedMessage { factory GetValidatorAddressesRequest() => create(); GetValidatorAddressesRequest._(); factory GetValidatorAddressesRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorAddressesRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorAddressesRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressesRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressesRequest copyWith( void Function(GetValidatorAddressesRequest) updates) => super.copyWith( (message) => updates(message as GetValidatorAddressesRequest)) as GetValidatorAddressesRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorAddressesRequest create() => GetValidatorAddressesRequest._(); @$core.override GetValidatorAddressesRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorAddressesRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorAddressesRequest? _defaultInstance; } /// Response message contains list of validator addresses. class GetValidatorAddressesResponse extends $pb.GeneratedMessage { factory GetValidatorAddressesResponse({ $core.Iterable<$core.String>? addresses, }) { final result = create(); if (addresses != null) result.addresses.addAll(addresses); return result; } GetValidatorAddressesResponse._(); factory GetValidatorAddressesResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorAddressesResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorAddressesResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..pPS(1, _omitFieldNames ? '' : 'addresses') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressesResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressesResponse copyWith( void Function(GetValidatorAddressesResponse) updates) => super.copyWith( (message) => updates(message as GetValidatorAddressesResponse)) as GetValidatorAddressesResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorAddressesResponse create() => GetValidatorAddressesResponse._(); @$core.override GetValidatorAddressesResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorAddressesResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorAddressesResponse? _defaultInstance; /// List of validator addresses. @$pb.TagNumber(1) $pb.PbList<$core.String> get addresses => $_getList(0); } /// Request message for retrieving validator information by address. class GetValidatorRequest extends $pb.GeneratedMessage { factory GetValidatorRequest({ $core.String? address, }) { final result = create(); if (address != null) result.address = address; return result; } GetValidatorRequest._(); factory GetValidatorRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorRequest copyWith(void Function(GetValidatorRequest) updates) => super.copyWith((message) => updates(message as GetValidatorRequest)) as GetValidatorRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorRequest create() => GetValidatorRequest._(); @$core.override GetValidatorRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorRequest? _defaultInstance; /// The address of the validator to retrieve information for. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); } /// Request message for retrieving validator information by number. class GetValidatorByNumberRequest extends $pb.GeneratedMessage { factory GetValidatorByNumberRequest({ $core.int? number, }) { final result = create(); if (number != null) result.number = number; return result; } GetValidatorByNumberRequest._(); factory GetValidatorByNumberRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorByNumberRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorByNumberRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'number') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorByNumberRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorByNumberRequest copyWith( void Function(GetValidatorByNumberRequest) updates) => super.copyWith( (message) => updates(message as GetValidatorByNumberRequest)) as GetValidatorByNumberRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorByNumberRequest create() => GetValidatorByNumberRequest._(); @$core.override GetValidatorByNumberRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorByNumberRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorByNumberRequest? _defaultInstance; /// The unique number of the validator to retrieve information for. @$pb.TagNumber(1) $core.int get number => $_getIZ(0); @$pb.TagNumber(1) set number($core.int value) => $_setSignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasNumber() => $_has(0); @$pb.TagNumber(1) void clearNumber() => $_clearField(1); } /// Response message contains validator information. class GetValidatorResponse extends $pb.GeneratedMessage { factory GetValidatorResponse({ ValidatorInfo? validator, }) { final result = create(); if (validator != null) result.validator = validator; return result; } GetValidatorResponse._(); factory GetValidatorResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOM(1, _omitFieldNames ? '' : 'validator', subBuilder: ValidatorInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorResponse copyWith(void Function(GetValidatorResponse) updates) => super.copyWith((message) => updates(message as GetValidatorResponse)) as GetValidatorResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorResponse create() => GetValidatorResponse._(); @$core.override GetValidatorResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorResponse? _defaultInstance; /// Detailed information about the validator. @$pb.TagNumber(1) ValidatorInfo get validator => $_getN(0); @$pb.TagNumber(1) set validator(ValidatorInfo value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasValidator() => $_has(0); @$pb.TagNumber(1) void clearValidator() => $_clearField(1); @$pb.TagNumber(1) ValidatorInfo ensureValidator() => $_ensure(0); } /// Request message for retrieving public key by address. class GetPublicKeyRequest extends $pb.GeneratedMessage { factory GetPublicKeyRequest({ $core.String? address, }) { final result = create(); if (address != null) result.address = address; return result; } GetPublicKeyRequest._(); factory GetPublicKeyRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetPublicKeyRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetPublicKeyRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPublicKeyRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPublicKeyRequest copyWith(void Function(GetPublicKeyRequest) updates) => super.copyWith((message) => updates(message as GetPublicKeyRequest)) as GetPublicKeyRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetPublicKeyRequest create() => GetPublicKeyRequest._(); @$core.override GetPublicKeyRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetPublicKeyRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetPublicKeyRequest? _defaultInstance; /// The address for which to retrieve the public key. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); } /// Response message contains public key information. class GetPublicKeyResponse extends $pb.GeneratedMessage { factory GetPublicKeyResponse({ $core.String? publicKey, }) { final result = create(); if (publicKey != null) result.publicKey = publicKey; return result; } GetPublicKeyResponse._(); factory GetPublicKeyResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetPublicKeyResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetPublicKeyResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'publicKey') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPublicKeyResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPublicKeyResponse copyWith(void Function(GetPublicKeyResponse) updates) => super.copyWith((message) => updates(message as GetPublicKeyResponse)) as GetPublicKeyResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetPublicKeyResponse create() => GetPublicKeyResponse._(); @$core.override GetPublicKeyResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetPublicKeyResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetPublicKeyResponse? _defaultInstance; /// The public key associated with the provided address. @$pb.TagNumber(1) $core.String get publicKey => $_getSZ(0); @$pb.TagNumber(1) set publicKey($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasPublicKey() => $_has(0); @$pb.TagNumber(1) void clearPublicKey() => $_clearField(1); } /// Request message for retrieving block information based on height and verbosity level. class GetBlockRequest extends $pb.GeneratedMessage { factory GetBlockRequest({ $core.int? height, BlockVerbosity? verbosity, }) { final result = create(); if (height != null) result.height = height; if (verbosity != null) result.verbosity = verbosity; return result; } GetBlockRequest._(); factory GetBlockRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..aE(2, _omitFieldNames ? '' : 'verbosity', enumValues: BlockVerbosity.values) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockRequest copyWith(void Function(GetBlockRequest) updates) => super.copyWith((message) => updates(message as GetBlockRequest)) as GetBlockRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockRequest create() => GetBlockRequest._(); @$core.override GetBlockRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockRequest? _defaultInstance; /// The height of the block to retrieve. @$pb.TagNumber(1) $core.int get height => $_getIZ(0); @$pb.TagNumber(1) set height($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasHeight() => $_has(0); @$pb.TagNumber(1) void clearHeight() => $_clearField(1); /// The verbosity level for block information. @$pb.TagNumber(2) BlockVerbosity get verbosity => $_getN(1); @$pb.TagNumber(2) set verbosity(BlockVerbosity value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasVerbosity() => $_has(1); @$pb.TagNumber(2) void clearVerbosity() => $_clearField(2); } /// Response message contains block information. class GetBlockResponse extends $pb.GeneratedMessage { factory GetBlockResponse({ $core.int? height, $core.String? hash, $core.String? data, $core.int? blockTime, BlockHeaderInfo? header, CertificateInfo? prevCert, $core.Iterable<$0.TransactionInfo>? txs, }) { final result = create(); if (height != null) result.height = height; if (hash != null) result.hash = hash; if (data != null) result.data = data; if (blockTime != null) result.blockTime = blockTime; if (header != null) result.header = header; if (prevCert != null) result.prevCert = prevCert; if (txs != null) result.txs.addAll(txs); return result; } GetBlockResponse._(); factory GetBlockResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'hash') ..aOS(3, _omitFieldNames ? '' : 'data') ..aI(4, _omitFieldNames ? '' : 'blockTime', fieldType: $pb.PbFieldType.OU3) ..aOM(5, _omitFieldNames ? '' : 'header', subBuilder: BlockHeaderInfo.create) ..aOM(6, _omitFieldNames ? '' : 'prevCert', subBuilder: CertificateInfo.create) ..pPM<$0.TransactionInfo>(7, _omitFieldNames ? '' : 'txs', subBuilder: $0.TransactionInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockResponse copyWith(void Function(GetBlockResponse) updates) => super.copyWith((message) => updates(message as GetBlockResponse)) as GetBlockResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockResponse create() => GetBlockResponse._(); @$core.override GetBlockResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockResponse? _defaultInstance; /// The height of the block. @$pb.TagNumber(1) $core.int get height => $_getIZ(0); @$pb.TagNumber(1) set height($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasHeight() => $_has(0); @$pb.TagNumber(1) void clearHeight() => $_clearField(1); /// The hash of the block. @$pb.TagNumber(2) $core.String get hash => $_getSZ(1); @$pb.TagNumber(2) set hash($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasHash() => $_has(1); @$pb.TagNumber(2) void clearHash() => $_clearField(2); /// Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA. @$pb.TagNumber(3) $core.String get data => $_getSZ(2); @$pb.TagNumber(3) set data($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasData() => $_has(2); @$pb.TagNumber(3) void clearData() => $_clearField(3); /// The timestamp of the block. @$pb.TagNumber(4) $core.int get blockTime => $_getIZ(3); @$pb.TagNumber(4) set blockTime($core.int value) => $_setUnsignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasBlockTime() => $_has(3); @$pb.TagNumber(4) void clearBlockTime() => $_clearField(4); /// Header information of the block. @$pb.TagNumber(5) BlockHeaderInfo get header => $_getN(4); @$pb.TagNumber(5) set header(BlockHeaderInfo value) => $_setField(5, value); @$pb.TagNumber(5) $core.bool hasHeader() => $_has(4); @$pb.TagNumber(5) void clearHeader() => $_clearField(5); @$pb.TagNumber(5) BlockHeaderInfo ensureHeader() => $_ensure(4); /// Certificate information of the previous block. @$pb.TagNumber(6) CertificateInfo get prevCert => $_getN(5); @$pb.TagNumber(6) set prevCert(CertificateInfo value) => $_setField(6, value); @$pb.TagNumber(6) $core.bool hasPrevCert() => $_has(5); @$pb.TagNumber(6) void clearPrevCert() => $_clearField(6); @$pb.TagNumber(6) CertificateInfo ensurePrevCert() => $_ensure(5); /// List of transactions in the block, available when verbosity level is set to /// BLOCK_VERBOSITY_TRANSACTIONS. @$pb.TagNumber(7) $pb.PbList<$0.TransactionInfo> get txs => $_getList(6); } /// Request message for retrieving block hash by height. class GetBlockHashRequest extends $pb.GeneratedMessage { factory GetBlockHashRequest({ $core.int? height, }) { final result = create(); if (height != null) result.height = height; return result; } GetBlockHashRequest._(); factory GetBlockHashRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockHashRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockHashRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHashRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHashRequest copyWith(void Function(GetBlockHashRequest) updates) => super.copyWith((message) => updates(message as GetBlockHashRequest)) as GetBlockHashRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockHashRequest create() => GetBlockHashRequest._(); @$core.override GetBlockHashRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockHashRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockHashRequest? _defaultInstance; /// The height of the block to retrieve the hash for. @$pb.TagNumber(1) $core.int get height => $_getIZ(0); @$pb.TagNumber(1) set height($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasHeight() => $_has(0); @$pb.TagNumber(1) void clearHeight() => $_clearField(1); } /// Response message contains block hash. class GetBlockHashResponse extends $pb.GeneratedMessage { factory GetBlockHashResponse({ $core.String? hash, }) { final result = create(); if (hash != null) result.hash = hash; return result; } GetBlockHashResponse._(); factory GetBlockHashResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockHashResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockHashResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'hash') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHashResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHashResponse copyWith(void Function(GetBlockHashResponse) updates) => super.copyWith((message) => updates(message as GetBlockHashResponse)) as GetBlockHashResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockHashResponse create() => GetBlockHashResponse._(); @$core.override GetBlockHashResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockHashResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockHashResponse? _defaultInstance; /// The hash of the block. @$pb.TagNumber(1) $core.String get hash => $_getSZ(0); @$pb.TagNumber(1) set hash($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasHash() => $_has(0); @$pb.TagNumber(1) void clearHash() => $_clearField(1); } /// Request message for retrieving block height by hash. class GetBlockHeightRequest extends $pb.GeneratedMessage { factory GetBlockHeightRequest({ $core.String? hash, }) { final result = create(); if (hash != null) result.hash = hash; return result; } GetBlockHeightRequest._(); factory GetBlockHeightRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockHeightRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockHeightRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'hash') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHeightRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHeightRequest copyWith( void Function(GetBlockHeightRequest) updates) => super.copyWith((message) => updates(message as GetBlockHeightRequest)) as GetBlockHeightRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockHeightRequest create() => GetBlockHeightRequest._(); @$core.override GetBlockHeightRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockHeightRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockHeightRequest? _defaultInstance; /// The hash of the block to retrieve the height for. @$pb.TagNumber(1) $core.String get hash => $_getSZ(0); @$pb.TagNumber(1) set hash($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasHash() => $_has(0); @$pb.TagNumber(1) void clearHash() => $_clearField(1); } /// Response message contains block height. class GetBlockHeightResponse extends $pb.GeneratedMessage { factory GetBlockHeightResponse({ $core.int? height, }) { final result = create(); if (height != null) result.height = height; return result; } GetBlockHeightResponse._(); factory GetBlockHeightResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockHeightResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockHeightResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHeightResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockHeightResponse copyWith( void Function(GetBlockHeightResponse) updates) => super.copyWith((message) => updates(message as GetBlockHeightResponse)) as GetBlockHeightResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockHeightResponse create() => GetBlockHeightResponse._(); @$core.override GetBlockHeightResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockHeightResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockHeightResponse? _defaultInstance; /// The height of the block. @$pb.TagNumber(1) $core.int get height => $_getIZ(0); @$pb.TagNumber(1) set height($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasHeight() => $_has(0); @$pb.TagNumber(1) void clearHeight() => $_clearField(1); } /// Request message for retrieving blockchain information. class GetBlockchainInfoRequest extends $pb.GeneratedMessage { factory GetBlockchainInfoRequest() => create(); GetBlockchainInfoRequest._(); factory GetBlockchainInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockchainInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockchainInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockchainInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockchainInfoRequest copyWith( void Function(GetBlockchainInfoRequest) updates) => super.copyWith((message) => updates(message as GetBlockchainInfoRequest)) as GetBlockchainInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockchainInfoRequest create() => GetBlockchainInfoRequest._(); @$core.override GetBlockchainInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockchainInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockchainInfoRequest? _defaultInstance; } /// Response message contains general blockchain information. class GetBlockchainInfoResponse extends $pb.GeneratedMessage { factory GetBlockchainInfoResponse({ $core.int? lastBlockHeight, $core.String? lastBlockHash, $core.int? totalAccounts, $core.int? totalValidators, $fixnum.Int64? totalPower, $fixnum.Int64? committeePower, $core.bool? isPruned, $core.int? pruningHeight, $fixnum.Int64? lastBlockTime, $core.int? activeValidators, $core.bool? inCommittee, $core.int? committeeSize, $core.double? averageScore, }) { final result = create(); if (lastBlockHeight != null) result.lastBlockHeight = lastBlockHeight; if (lastBlockHash != null) result.lastBlockHash = lastBlockHash; if (totalAccounts != null) result.totalAccounts = totalAccounts; if (totalValidators != null) result.totalValidators = totalValidators; if (totalPower != null) result.totalPower = totalPower; if (committeePower != null) result.committeePower = committeePower; if (isPruned != null) result.isPruned = isPruned; if (pruningHeight != null) result.pruningHeight = pruningHeight; if (lastBlockTime != null) result.lastBlockTime = lastBlockTime; if (activeValidators != null) result.activeValidators = activeValidators; if (inCommittee != null) result.inCommittee = inCommittee; if (committeeSize != null) result.committeeSize = committeeSize; if (averageScore != null) result.averageScore = averageScore; return result; } GetBlockchainInfoResponse._(); factory GetBlockchainInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetBlockchainInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetBlockchainInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'lastBlockHeight', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'lastBlockHash') ..aI(3, _omitFieldNames ? '' : 'totalAccounts') ..aI(4, _omitFieldNames ? '' : 'totalValidators') ..aInt64(5, _omitFieldNames ? '' : 'totalPower') ..aInt64(6, _omitFieldNames ? '' : 'committeePower') ..aOB(8, _omitFieldNames ? '' : 'isPruned') ..aI(9, _omitFieldNames ? '' : 'pruningHeight', fieldType: $pb.PbFieldType.OU3) ..aInt64(10, _omitFieldNames ? '' : 'lastBlockTime') ..aI(12, _omitFieldNames ? '' : 'activeValidators') ..aOB(13, _omitFieldNames ? '' : 'inCommittee') ..aI(14, _omitFieldNames ? '' : 'committeeSize') ..aD(15, _omitFieldNames ? '' : 'averageScore') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockchainInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetBlockchainInfoResponse copyWith( void Function(GetBlockchainInfoResponse) updates) => super.copyWith((message) => updates(message as GetBlockchainInfoResponse)) as GetBlockchainInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetBlockchainInfoResponse create() => GetBlockchainInfoResponse._(); @$core.override GetBlockchainInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetBlockchainInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetBlockchainInfoResponse? _defaultInstance; /// The height of the last block in the blockchain. @$pb.TagNumber(1) $core.int get lastBlockHeight => $_getIZ(0); @$pb.TagNumber(1) set lastBlockHeight($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasLastBlockHeight() => $_has(0); @$pb.TagNumber(1) void clearLastBlockHeight() => $_clearField(1); /// The hash of the last block in the blockchain. @$pb.TagNumber(2) $core.String get lastBlockHash => $_getSZ(1); @$pb.TagNumber(2) set lastBlockHash($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasLastBlockHash() => $_has(1); @$pb.TagNumber(2) void clearLastBlockHash() => $_clearField(2); /// The total number of accounts in the blockchain. @$pb.TagNumber(3) $core.int get totalAccounts => $_getIZ(2); @$pb.TagNumber(3) set totalAccounts($core.int value) => $_setSignedInt32(2, value); @$pb.TagNumber(3) $core.bool hasTotalAccounts() => $_has(2); @$pb.TagNumber(3) void clearTotalAccounts() => $_clearField(3); /// The total number of validators in the blockchain. @$pb.TagNumber(4) $core.int get totalValidators => $_getIZ(3); @$pb.TagNumber(4) set totalValidators($core.int value) => $_setSignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasTotalValidators() => $_has(3); @$pb.TagNumber(4) void clearTotalValidators() => $_clearField(4); /// The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. @$pb.TagNumber(5) $fixnum.Int64 get totalPower => $_getI64(4); @$pb.TagNumber(5) set totalPower($fixnum.Int64 value) => $_setInt64(4, value); @$pb.TagNumber(5) $core.bool hasTotalPower() => $_has(4); @$pb.TagNumber(5) void clearTotalPower() => $_clearField(5); /// The power of the committee. @$pb.TagNumber(6) $fixnum.Int64 get committeePower => $_getI64(5); @$pb.TagNumber(6) set committeePower($fixnum.Int64 value) => $_setInt64(5, value); @$pb.TagNumber(6) $core.bool hasCommitteePower() => $_has(5); @$pb.TagNumber(6) void clearCommitteePower() => $_clearField(6); /// If the blocks are subject to pruning. @$pb.TagNumber(8) $core.bool get isPruned => $_getBF(6); @$pb.TagNumber(8) set isPruned($core.bool value) => $_setBool(6, value); @$pb.TagNumber(8) $core.bool hasIsPruned() => $_has(6); @$pb.TagNumber(8) void clearIsPruned() => $_clearField(8); /// Lowest-height block stored (only present if pruning is enabled) @$pb.TagNumber(9) $core.int get pruningHeight => $_getIZ(7); @$pb.TagNumber(9) set pruningHeight($core.int value) => $_setUnsignedInt32(7, value); @$pb.TagNumber(9) $core.bool hasPruningHeight() => $_has(7); @$pb.TagNumber(9) void clearPruningHeight() => $_clearField(9); /// The timestamp of the last block in Unix format. @$pb.TagNumber(10) $fixnum.Int64 get lastBlockTime => $_getI64(8); @$pb.TagNumber(10) set lastBlockTime($fixnum.Int64 value) => $_setInt64(8, value); @$pb.TagNumber(10) $core.bool hasLastBlockTime() => $_has(8); @$pb.TagNumber(10) void clearLastBlockTime() => $_clearField(10); /// The number of active (not unbonded) validators in the blockchain. @$pb.TagNumber(12) $core.int get activeValidators => $_getIZ(9); @$pb.TagNumber(12) set activeValidators($core.int value) => $_setSignedInt32(9, value); @$pb.TagNumber(12) $core.bool hasActiveValidators() => $_has(9); @$pb.TagNumber(12) void clearActiveValidators() => $_clearField(12); /// Indicates whether this node participates in consensus: true if at least one /// of its running validators is a member of the current committee. @$pb.TagNumber(13) $core.bool get inCommittee => $_getBF(10); @$pb.TagNumber(13) set inCommittee($core.bool value) => $_setBool(10, value); @$pb.TagNumber(13) $core.bool hasInCommittee() => $_has(10); @$pb.TagNumber(13) void clearInCommittee() => $_clearField(13); /// The number of validators in the current committee. @$pb.TagNumber(14) $core.int get committeeSize => $_getIZ(11); @$pb.TagNumber(14) set committeeSize($core.int value) => $_setSignedInt32(11, value); @$pb.TagNumber(14) $core.bool hasCommitteeSize() => $_has(11); @$pb.TagNumber(14) void clearCommitteeSize() => $_clearField(14); /// Average availability score of validators with stake, in percentage (0-100). @$pb.TagNumber(15) $core.double get averageScore => $_getN(12); @$pb.TagNumber(15) set averageScore($core.double value) => $_setDouble(12, value); @$pb.TagNumber(15) $core.bool hasAverageScore() => $_has(12); @$pb.TagNumber(15) void clearAverageScore() => $_clearField(15); } /// Request message for retrieving committee information. class GetCommitteeInfoRequest extends $pb.GeneratedMessage { factory GetCommitteeInfoRequest() => create(); GetCommitteeInfoRequest._(); factory GetCommitteeInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetCommitteeInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetCommitteeInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetCommitteeInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetCommitteeInfoRequest copyWith( void Function(GetCommitteeInfoRequest) updates) => super.copyWith((message) => updates(message as GetCommitteeInfoRequest)) as GetCommitteeInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetCommitteeInfoRequest create() => GetCommitteeInfoRequest._(); @$core.override GetCommitteeInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetCommitteeInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetCommitteeInfoRequest? _defaultInstance; } /// Response message contains committee information. class GetCommitteeInfoResponse extends $pb.GeneratedMessage { factory GetCommitteeInfoResponse({ $core.int? committeeSize, $fixnum.Int64? committeePower, $fixnum.Int64? totalPower, $core.Iterable? validators, $core.Iterable<$core.MapEntry<$core.int, $core.double>>? protocolVersions, }) { final result = create(); if (committeeSize != null) result.committeeSize = committeeSize; if (committeePower != null) result.committeePower = committeePower; if (totalPower != null) result.totalPower = totalPower; if (validators != null) result.validators.addAll(validators); if (protocolVersions != null) result.protocolVersions.addEntries(protocolVersions); return result; } GetCommitteeInfoResponse._(); factory GetCommitteeInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetCommitteeInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetCommitteeInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'committeeSize') ..aInt64(2, _omitFieldNames ? '' : 'committeePower') ..aInt64(3, _omitFieldNames ? '' : 'totalPower') ..pPM(4, _omitFieldNames ? '' : 'validators', subBuilder: ValidatorInfo.create) ..m<$core.int, $core.double>(5, _omitFieldNames ? '' : 'protocolVersions', entryClassName: 'GetCommitteeInfoResponse.ProtocolVersionsEntry', keyFieldType: $pb.PbFieldType.O3, valueFieldType: $pb.PbFieldType.OD, packageName: const $pb.PackageName('pactus')) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetCommitteeInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetCommitteeInfoResponse copyWith( void Function(GetCommitteeInfoResponse) updates) => super.copyWith((message) => updates(message as GetCommitteeInfoResponse)) as GetCommitteeInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetCommitteeInfoResponse create() => GetCommitteeInfoResponse._(); @$core.override GetCommitteeInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetCommitteeInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetCommitteeInfoResponse? _defaultInstance; /// The number of validators in the committee. @$pb.TagNumber(1) $core.int get committeeSize => $_getIZ(0); @$pb.TagNumber(1) set committeeSize($core.int value) => $_setSignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasCommitteeSize() => $_has(0); @$pb.TagNumber(1) void clearCommitteeSize() => $_clearField(1); /// The power of the committee. @$pb.TagNumber(2) $fixnum.Int64 get committeePower => $_getI64(1); @$pb.TagNumber(2) set committeePower($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasCommitteePower() => $_has(1); @$pb.TagNumber(2) void clearCommitteePower() => $_clearField(2); /// The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. @$pb.TagNumber(3) $fixnum.Int64 get totalPower => $_getI64(2); @$pb.TagNumber(3) set totalPower($fixnum.Int64 value) => $_setInt64(2, value); @$pb.TagNumber(3) $core.bool hasTotalPower() => $_has(2); @$pb.TagNumber(3) void clearTotalPower() => $_clearField(3); /// List of committee validators. @$pb.TagNumber(4) $pb.PbList get validators => $_getList(3); /// Map of protocol versions and their percentages in the committee. @$pb.TagNumber(5) $pb.PbMap<$core.int, $core.double> get protocolVersions => $_getMap(4); } /// Request message for retrieving consensus information. class GetConsensusInfoRequest extends $pb.GeneratedMessage { factory GetConsensusInfoRequest() => create(); GetConsensusInfoRequest._(); factory GetConsensusInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetConsensusInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetConsensusInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetConsensusInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetConsensusInfoRequest copyWith( void Function(GetConsensusInfoRequest) updates) => super.copyWith((message) => updates(message as GetConsensusInfoRequest)) as GetConsensusInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetConsensusInfoRequest create() => GetConsensusInfoRequest._(); @$core.override GetConsensusInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetConsensusInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetConsensusInfoRequest? _defaultInstance; } /// Response message contains consensus information. class GetConsensusInfoResponse extends $pb.GeneratedMessage { factory GetConsensusInfoResponse({ ProposalInfo? proposal, $core.Iterable? instances, }) { final result = create(); if (proposal != null) result.proposal = proposal; if (instances != null) result.instances.addAll(instances); return result; } GetConsensusInfoResponse._(); factory GetConsensusInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetConsensusInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetConsensusInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOM(1, _omitFieldNames ? '' : 'proposal', subBuilder: ProposalInfo.create) ..pPM(2, _omitFieldNames ? '' : 'instances', subBuilder: ConsensusInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetConsensusInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetConsensusInfoResponse copyWith( void Function(GetConsensusInfoResponse) updates) => super.copyWith((message) => updates(message as GetConsensusInfoResponse)) as GetConsensusInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetConsensusInfoResponse create() => GetConsensusInfoResponse._(); @$core.override GetConsensusInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetConsensusInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetConsensusInfoResponse? _defaultInstance; /// The proposal of the consensus info. @$pb.TagNumber(1) ProposalInfo get proposal => $_getN(0); @$pb.TagNumber(1) set proposal(ProposalInfo value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasProposal() => $_has(0); @$pb.TagNumber(1) void clearProposal() => $_clearField(1); @$pb.TagNumber(1) ProposalInfo ensureProposal() => $_ensure(0); /// List of consensus instances. @$pb.TagNumber(2) $pb.PbList get instances => $_getList(1); } /// Request message for retrieving transactions in the transaction pool. class GetTxPoolContentRequest extends $pb.GeneratedMessage { factory GetTxPoolContentRequest({ $0.PayloadType? payloadType, }) { final result = create(); if (payloadType != null) result.payloadType = payloadType; return result; } GetTxPoolContentRequest._(); factory GetTxPoolContentRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTxPoolContentRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTxPoolContentRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aE<$0.PayloadType>(1, _omitFieldNames ? '' : 'payloadType', enumValues: $0.PayloadType.values) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTxPoolContentRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTxPoolContentRequest copyWith( void Function(GetTxPoolContentRequest) updates) => super.copyWith((message) => updates(message as GetTxPoolContentRequest)) as GetTxPoolContentRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTxPoolContentRequest create() => GetTxPoolContentRequest._(); @$core.override GetTxPoolContentRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTxPoolContentRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTxPoolContentRequest? _defaultInstance; /// The type of transactions to retrieve from the transaction pool. 0 means all types. @$pb.TagNumber(1) $0.PayloadType get payloadType => $_getN(0); @$pb.TagNumber(1) set payloadType($0.PayloadType value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasPayloadType() => $_has(0); @$pb.TagNumber(1) void clearPayloadType() => $_clearField(1); } /// Response message contains transactions in the transaction pool. class GetTxPoolContentResponse extends $pb.GeneratedMessage { factory GetTxPoolContentResponse({ $core.Iterable<$0.TransactionInfo>? txs, }) { final result = create(); if (txs != null) result.txs.addAll(txs); return result; } GetTxPoolContentResponse._(); factory GetTxPoolContentResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTxPoolContentResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTxPoolContentResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..pPM<$0.TransactionInfo>(1, _omitFieldNames ? '' : 'txs', subBuilder: $0.TransactionInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTxPoolContentResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTxPoolContentResponse copyWith( void Function(GetTxPoolContentResponse) updates) => super.copyWith((message) => updates(message as GetTxPoolContentResponse)) as GetTxPoolContentResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTxPoolContentResponse create() => GetTxPoolContentResponse._(); @$core.override GetTxPoolContentResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTxPoolContentResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTxPoolContentResponse? _defaultInstance; /// List of transactions currently in the pool. @$pb.TagNumber(1) $pb.PbList<$0.TransactionInfo> get txs => $_getList(0); } /// Message contains information about a validator. class ValidatorInfo extends $pb.GeneratedMessage { factory ValidatorInfo({ $core.String? hash, $core.String? data, $core.String? publicKey, $core.int? number, $fixnum.Int64? stake, $core.int? lastBondingHeight, $core.int? lastSortitionHeight, $core.int? unbondingHeight, $core.String? address, $core.double? availabilityScore, $core.int? protocolVersion, $core.bool? isDelegated, $core.String? delegateOwner, $fixnum.Int64? delegateShare, $core.int? delegateExpiry, }) { final result = create(); if (hash != null) result.hash = hash; if (data != null) result.data = data; if (publicKey != null) result.publicKey = publicKey; if (number != null) result.number = number; if (stake != null) result.stake = stake; if (lastBondingHeight != null) result.lastBondingHeight = lastBondingHeight; if (lastSortitionHeight != null) result.lastSortitionHeight = lastSortitionHeight; if (unbondingHeight != null) result.unbondingHeight = unbondingHeight; if (address != null) result.address = address; if (availabilityScore != null) result.availabilityScore = availabilityScore; if (protocolVersion != null) result.protocolVersion = protocolVersion; if (isDelegated != null) result.isDelegated = isDelegated; if (delegateOwner != null) result.delegateOwner = delegateOwner; if (delegateShare != null) result.delegateShare = delegateShare; if (delegateExpiry != null) result.delegateExpiry = delegateExpiry; return result; } ValidatorInfo._(); factory ValidatorInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ValidatorInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ValidatorInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'hash') ..aOS(2, _omitFieldNames ? '' : 'data') ..aOS(3, _omitFieldNames ? '' : 'publicKey') ..aI(4, _omitFieldNames ? '' : 'number') ..aInt64(5, _omitFieldNames ? '' : 'stake') ..aI(6, _omitFieldNames ? '' : 'lastBondingHeight', fieldType: $pb.PbFieldType.OU3) ..aI(7, _omitFieldNames ? '' : 'lastSortitionHeight', fieldType: $pb.PbFieldType.OU3) ..aI(8, _omitFieldNames ? '' : 'unbondingHeight', fieldType: $pb.PbFieldType.OU3) ..aOS(9, _omitFieldNames ? '' : 'address') ..aD(10, _omitFieldNames ? '' : 'availabilityScore') ..aI(11, _omitFieldNames ? '' : 'protocolVersion') ..aOB(12, _omitFieldNames ? '' : 'isDelegated') ..aOS(13, _omitFieldNames ? '' : 'delegateOwner') ..aInt64(14, _omitFieldNames ? '' : 'delegateShare') ..aI(15, _omitFieldNames ? '' : 'delegateExpiry', fieldType: $pb.PbFieldType.OU3) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ValidatorInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ValidatorInfo copyWith(void Function(ValidatorInfo) updates) => super.copyWith((message) => updates(message as ValidatorInfo)) as ValidatorInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ValidatorInfo create() => ValidatorInfo._(); @$core.override ValidatorInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ValidatorInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ValidatorInfo? _defaultInstance; /// The hash of the validator. @$pb.TagNumber(1) $core.String get hash => $_getSZ(0); @$pb.TagNumber(1) set hash($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasHash() => $_has(0); @$pb.TagNumber(1) void clearHash() => $_clearField(1); /// The serialized data of the validator. @$pb.TagNumber(2) $core.String get data => $_getSZ(1); @$pb.TagNumber(2) set data($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasData() => $_has(1); @$pb.TagNumber(2) void clearData() => $_clearField(2); /// The public key of the validator. @$pb.TagNumber(3) $core.String get publicKey => $_getSZ(2); @$pb.TagNumber(3) set publicKey($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasPublicKey() => $_has(2); @$pb.TagNumber(3) void clearPublicKey() => $_clearField(3); /// The unique number assigned to the validator. @$pb.TagNumber(4) $core.int get number => $_getIZ(3); @$pb.TagNumber(4) set number($core.int value) => $_setSignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasNumber() => $_has(3); @$pb.TagNumber(4) void clearNumber() => $_clearField(4); /// The stake of the validator in NanoPAC. @$pb.TagNumber(5) $fixnum.Int64 get stake => $_getI64(4); @$pb.TagNumber(5) set stake($fixnum.Int64 value) => $_setInt64(4, value); @$pb.TagNumber(5) $core.bool hasStake() => $_has(4); @$pb.TagNumber(5) void clearStake() => $_clearField(5); /// The height at which the validator last bonded. @$pb.TagNumber(6) $core.int get lastBondingHeight => $_getIZ(5); @$pb.TagNumber(6) set lastBondingHeight($core.int value) => $_setUnsignedInt32(5, value); @$pb.TagNumber(6) $core.bool hasLastBondingHeight() => $_has(5); @$pb.TagNumber(6) void clearLastBondingHeight() => $_clearField(6); /// The height at which the validator last participated in sortition. @$pb.TagNumber(7) $core.int get lastSortitionHeight => $_getIZ(6); @$pb.TagNumber(7) set lastSortitionHeight($core.int value) => $_setUnsignedInt32(6, value); @$pb.TagNumber(7) $core.bool hasLastSortitionHeight() => $_has(6); @$pb.TagNumber(7) void clearLastSortitionHeight() => $_clearField(7); /// The height at which the validator will unbond. @$pb.TagNumber(8) $core.int get unbondingHeight => $_getIZ(7); @$pb.TagNumber(8) set unbondingHeight($core.int value) => $_setUnsignedInt32(7, value); @$pb.TagNumber(8) $core.bool hasUnbondingHeight() => $_has(7); @$pb.TagNumber(8) void clearUnbondingHeight() => $_clearField(8); /// The address of the validator. @$pb.TagNumber(9) $core.String get address => $_getSZ(8); @$pb.TagNumber(9) set address($core.String value) => $_setString(8, value); @$pb.TagNumber(9) $core.bool hasAddress() => $_has(8); @$pb.TagNumber(9) void clearAddress() => $_clearField(9); /// The availability score of the validator. @$pb.TagNumber(10) $core.double get availabilityScore => $_getN(9); @$pb.TagNumber(10) set availabilityScore($core.double value) => $_setDouble(9, value); @$pb.TagNumber(10) $core.bool hasAvailabilityScore() => $_has(9); @$pb.TagNumber(10) void clearAvailabilityScore() => $_clearField(10); /// The protocol version of the validator. @$pb.TagNumber(11) $core.int get protocolVersion => $_getIZ(10); @$pb.TagNumber(11) set protocolVersion($core.int value) => $_setSignedInt32(10, value); @$pb.TagNumber(11) $core.bool hasProtocolVersion() => $_has(10); @$pb.TagNumber(11) void clearProtocolVersion() => $_clearField(11); /// Whether the validator is delegated. @$pb.TagNumber(12) $core.bool get isDelegated => $_getBF(11); @$pb.TagNumber(12) set isDelegated($core.bool value) => $_setBool(11, value); @$pb.TagNumber(12) $core.bool hasIsDelegated() => $_has(11); @$pb.TagNumber(12) void clearIsDelegated() => $_clearField(12); /// The address of the stake owner of the validator. @$pb.TagNumber(13) $core.String get delegateOwner => $_getSZ(12); @$pb.TagNumber(13) set delegateOwner($core.String value) => $_setString(12, value); @$pb.TagNumber(13) $core.bool hasDelegateOwner() => $_has(12); @$pb.TagNumber(13) void clearDelegateOwner() => $_clearField(13); /// The share of the stake owner of the validator. @$pb.TagNumber(14) $fixnum.Int64 get delegateShare => $_getI64(13); @$pb.TagNumber(14) set delegateShare($fixnum.Int64 value) => $_setInt64(13, value); @$pb.TagNumber(14) $core.bool hasDelegateShare() => $_has(13); @$pb.TagNumber(14) void clearDelegateShare() => $_clearField(14); /// The expiry of the stake owner of the validator. @$pb.TagNumber(15) $core.int get delegateExpiry => $_getIZ(14); @$pb.TagNumber(15) set delegateExpiry($core.int value) => $_setUnsignedInt32(14, value); @$pb.TagNumber(15) $core.bool hasDelegateExpiry() => $_has(14); @$pb.TagNumber(15) void clearDelegateExpiry() => $_clearField(15); } /// Message contains information about an account. class AccountInfo extends $pb.GeneratedMessage { factory AccountInfo({ $core.String? hash, $core.String? data, $core.int? number, $fixnum.Int64? balance, $core.String? address, }) { final result = create(); if (hash != null) result.hash = hash; if (data != null) result.data = data; if (number != null) result.number = number; if (balance != null) result.balance = balance; if (address != null) result.address = address; return result; } AccountInfo._(); factory AccountInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory AccountInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'AccountInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'hash') ..aOS(2, _omitFieldNames ? '' : 'data') ..aI(3, _omitFieldNames ? '' : 'number') ..aInt64(4, _omitFieldNames ? '' : 'balance') ..aOS(5, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') AccountInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') AccountInfo copyWith(void Function(AccountInfo) updates) => super.copyWith((message) => updates(message as AccountInfo)) as AccountInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static AccountInfo create() => AccountInfo._(); @$core.override AccountInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static AccountInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static AccountInfo? _defaultInstance; /// The hash of the account. @$pb.TagNumber(1) $core.String get hash => $_getSZ(0); @$pb.TagNumber(1) set hash($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasHash() => $_has(0); @$pb.TagNumber(1) void clearHash() => $_clearField(1); /// The serialized data of the account. @$pb.TagNumber(2) $core.String get data => $_getSZ(1); @$pb.TagNumber(2) set data($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasData() => $_has(1); @$pb.TagNumber(2) void clearData() => $_clearField(2); /// The unique number assigned to the account. @$pb.TagNumber(3) $core.int get number => $_getIZ(2); @$pb.TagNumber(3) set number($core.int value) => $_setSignedInt32(2, value); @$pb.TagNumber(3) $core.bool hasNumber() => $_has(2); @$pb.TagNumber(3) void clearNumber() => $_clearField(3); /// The balance of the account in NanoPAC. @$pb.TagNumber(4) $fixnum.Int64 get balance => $_getI64(3); @$pb.TagNumber(4) set balance($fixnum.Int64 value) => $_setInt64(3, value); @$pb.TagNumber(4) $core.bool hasBalance() => $_has(3); @$pb.TagNumber(4) void clearBalance() => $_clearField(4); /// The address of the account. @$pb.TagNumber(5) $core.String get address => $_getSZ(4); @$pb.TagNumber(5) set address($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasAddress() => $_has(4); @$pb.TagNumber(5) void clearAddress() => $_clearField(5); } /// Message contains information about the header of a block. class BlockHeaderInfo extends $pb.GeneratedMessage { factory BlockHeaderInfo({ $core.int? version, $core.String? prevBlockHash, $core.String? stateRoot, $core.String? sortitionSeed, $core.String? proposerAddress, }) { final result = create(); if (version != null) result.version = version; if (prevBlockHash != null) result.prevBlockHash = prevBlockHash; if (stateRoot != null) result.stateRoot = stateRoot; if (sortitionSeed != null) result.sortitionSeed = sortitionSeed; if (proposerAddress != null) result.proposerAddress = proposerAddress; return result; } BlockHeaderInfo._(); factory BlockHeaderInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory BlockHeaderInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'BlockHeaderInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'version') ..aOS(2, _omitFieldNames ? '' : 'prevBlockHash') ..aOS(3, _omitFieldNames ? '' : 'stateRoot') ..aOS(4, _omitFieldNames ? '' : 'sortitionSeed') ..aOS(5, _omitFieldNames ? '' : 'proposerAddress') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') BlockHeaderInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') BlockHeaderInfo copyWith(void Function(BlockHeaderInfo) updates) => super.copyWith((message) => updates(message as BlockHeaderInfo)) as BlockHeaderInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static BlockHeaderInfo create() => BlockHeaderInfo._(); @$core.override BlockHeaderInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static BlockHeaderInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static BlockHeaderInfo? _defaultInstance; /// The version of the block. @$pb.TagNumber(1) $core.int get version => $_getIZ(0); @$pb.TagNumber(1) set version($core.int value) => $_setSignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasVersion() => $_has(0); @$pb.TagNumber(1) void clearVersion() => $_clearField(1); /// The hash of the previous block. @$pb.TagNumber(2) $core.String get prevBlockHash => $_getSZ(1); @$pb.TagNumber(2) set prevBlockHash($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPrevBlockHash() => $_has(1); @$pb.TagNumber(2) void clearPrevBlockHash() => $_clearField(2); /// The state root hash of the blockchain. @$pb.TagNumber(3) $core.String get stateRoot => $_getSZ(2); @$pb.TagNumber(3) set stateRoot($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasStateRoot() => $_has(2); @$pb.TagNumber(3) void clearStateRoot() => $_clearField(3); /// The sortition seed of the block. @$pb.TagNumber(4) $core.String get sortitionSeed => $_getSZ(3); @$pb.TagNumber(4) set sortitionSeed($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasSortitionSeed() => $_has(3); @$pb.TagNumber(4) void clearSortitionSeed() => $_clearField(4); /// The address of the proposer of the block. @$pb.TagNumber(5) $core.String get proposerAddress => $_getSZ(4); @$pb.TagNumber(5) set proposerAddress($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasProposerAddress() => $_has(4); @$pb.TagNumber(5) void clearProposerAddress() => $_clearField(5); } /// Message contains information about a certificate. class CertificateInfo extends $pb.GeneratedMessage { factory CertificateInfo({ $core.String? hash, $core.int? round, $core.Iterable<$core.int>? committers, $core.Iterable<$core.int>? absentees, $core.String? signature, }) { final result = create(); if (hash != null) result.hash = hash; if (round != null) result.round = round; if (committers != null) result.committers.addAll(committers); if (absentees != null) result.absentees.addAll(absentees); if (signature != null) result.signature = signature; return result; } CertificateInfo._(); factory CertificateInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CertificateInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CertificateInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'hash') ..aI(2, _omitFieldNames ? '' : 'round') ..p<$core.int>(3, _omitFieldNames ? '' : 'committers', $pb.PbFieldType.K3) ..p<$core.int>(4, _omitFieldNames ? '' : 'absentees', $pb.PbFieldType.K3) ..aOS(5, _omitFieldNames ? '' : 'signature') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CertificateInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CertificateInfo copyWith(void Function(CertificateInfo) updates) => super.copyWith((message) => updates(message as CertificateInfo)) as CertificateInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CertificateInfo create() => CertificateInfo._(); @$core.override CertificateInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CertificateInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CertificateInfo? _defaultInstance; /// The hash of the certificate. @$pb.TagNumber(1) $core.String get hash => $_getSZ(0); @$pb.TagNumber(1) set hash($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasHash() => $_has(0); @$pb.TagNumber(1) void clearHash() => $_clearField(1); /// The round of the certificate. @$pb.TagNumber(2) $core.int get round => $_getIZ(1); @$pb.TagNumber(2) set round($core.int value) => $_setSignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasRound() => $_has(1); @$pb.TagNumber(2) void clearRound() => $_clearField(2); /// List of committers in the certificate. @$pb.TagNumber(3) $pb.PbList<$core.int> get committers => $_getList(2); /// List of absentees in the certificate. @$pb.TagNumber(4) $pb.PbList<$core.int> get absentees => $_getList(3); /// The signature of the certificate. @$pb.TagNumber(5) $core.String get signature => $_getSZ(4); @$pb.TagNumber(5) set signature($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasSignature() => $_has(4); @$pb.TagNumber(5) void clearSignature() => $_clearField(5); } /// Message contains information about a vote. class VoteInfo extends $pb.GeneratedMessage { factory VoteInfo({ VoteType? type, $core.String? voter, $core.String? blockHash, $core.int? round, $core.int? cpRound, $core.int? cpValue, }) { final result = create(); if (type != null) result.type = type; if (voter != null) result.voter = voter; if (blockHash != null) result.blockHash = blockHash; if (round != null) result.round = round; if (cpRound != null) result.cpRound = cpRound; if (cpValue != null) result.cpValue = cpValue; return result; } VoteInfo._(); factory VoteInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory VoteInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'VoteInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aE(1, _omitFieldNames ? '' : 'type', enumValues: VoteType.values) ..aOS(2, _omitFieldNames ? '' : 'voter') ..aOS(3, _omitFieldNames ? '' : 'blockHash') ..aI(4, _omitFieldNames ? '' : 'round') ..aI(5, _omitFieldNames ? '' : 'cpRound') ..aI(6, _omitFieldNames ? '' : 'cpValue') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') VoteInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') VoteInfo copyWith(void Function(VoteInfo) updates) => super.copyWith((message) => updates(message as VoteInfo)) as VoteInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static VoteInfo create() => VoteInfo._(); @$core.override VoteInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static VoteInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static VoteInfo? _defaultInstance; /// The type of the vote. @$pb.TagNumber(1) VoteType get type => $_getN(0); @$pb.TagNumber(1) set type(VoteType value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasType() => $_has(0); @$pb.TagNumber(1) void clearType() => $_clearField(1); /// The address of the voter. @$pb.TagNumber(2) $core.String get voter => $_getSZ(1); @$pb.TagNumber(2) set voter($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasVoter() => $_has(1); @$pb.TagNumber(2) void clearVoter() => $_clearField(2); /// The hash of the block being voted on. @$pb.TagNumber(3) $core.String get blockHash => $_getSZ(2); @$pb.TagNumber(3) set blockHash($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasBlockHash() => $_has(2); @$pb.TagNumber(3) void clearBlockHash() => $_clearField(3); /// The consensus round of the vote. @$pb.TagNumber(4) $core.int get round => $_getIZ(3); @$pb.TagNumber(4) set round($core.int value) => $_setSignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasRound() => $_has(3); @$pb.TagNumber(4) void clearRound() => $_clearField(4); /// The change-proposer round of the vote. @$pb.TagNumber(5) $core.int get cpRound => $_getIZ(4); @$pb.TagNumber(5) set cpRound($core.int value) => $_setSignedInt32(4, value); @$pb.TagNumber(5) $core.bool hasCpRound() => $_has(4); @$pb.TagNumber(5) void clearCpRound() => $_clearField(5); /// The change-proposer value of the vote. @$pb.TagNumber(6) $core.int get cpValue => $_getIZ(5); @$pb.TagNumber(6) set cpValue($core.int value) => $_setSignedInt32(5, value); @$pb.TagNumber(6) $core.bool hasCpValue() => $_has(5); @$pb.TagNumber(6) void clearCpValue() => $_clearField(6); } /// Message contains information about a consensus instance. class ConsensusInfo extends $pb.GeneratedMessage { factory ConsensusInfo({ $core.String? address, $core.bool? active, $core.int? height, $core.int? round, $core.Iterable? votes, }) { final result = create(); if (address != null) result.address = address; if (active != null) result.active = active; if (height != null) result.height = height; if (round != null) result.round = round; if (votes != null) result.votes.addAll(votes); return result; } ConsensusInfo._(); factory ConsensusInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ConsensusInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ConsensusInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..aOB(2, _omitFieldNames ? '' : 'active') ..aI(3, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..aI(4, _omitFieldNames ? '' : 'round') ..pPM(5, _omitFieldNames ? '' : 'votes', subBuilder: VoteInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ConsensusInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ConsensusInfo copyWith(void Function(ConsensusInfo) updates) => super.copyWith((message) => updates(message as ConsensusInfo)) as ConsensusInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ConsensusInfo create() => ConsensusInfo._(); @$core.override ConsensusInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ConsensusInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ConsensusInfo? _defaultInstance; /// The address of the consensus instance. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); /// Indicates whether the consensus instance is active and part of the committee. @$pb.TagNumber(2) $core.bool get active => $_getBF(1); @$pb.TagNumber(2) set active($core.bool value) => $_setBool(1, value); @$pb.TagNumber(2) $core.bool hasActive() => $_has(1); @$pb.TagNumber(2) void clearActive() => $_clearField(2); /// The height of the consensus instance. @$pb.TagNumber(3) $core.int get height => $_getIZ(2); @$pb.TagNumber(3) set height($core.int value) => $_setUnsignedInt32(2, value); @$pb.TagNumber(3) $core.bool hasHeight() => $_has(2); @$pb.TagNumber(3) void clearHeight() => $_clearField(3); /// The round of the consensus instance. @$pb.TagNumber(4) $core.int get round => $_getIZ(3); @$pb.TagNumber(4) set round($core.int value) => $_setSignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasRound() => $_has(3); @$pb.TagNumber(4) void clearRound() => $_clearField(4); /// List of votes in the consensus instance. @$pb.TagNumber(5) $pb.PbList get votes => $_getList(4); } /// Message contains information about a proposal. class ProposalInfo extends $pb.GeneratedMessage { factory ProposalInfo({ $core.int? height, $core.int? round, $core.String? blockData, $core.String? signature, }) { final result = create(); if (height != null) result.height = height; if (round != null) result.round = round; if (blockData != null) result.blockData = blockData; if (signature != null) result.signature = signature; return result; } ProposalInfo._(); factory ProposalInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ProposalInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ProposalInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..aI(2, _omitFieldNames ? '' : 'round') ..aOS(3, _omitFieldNames ? '' : 'blockData') ..aOS(4, _omitFieldNames ? '' : 'signature') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ProposalInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ProposalInfo copyWith(void Function(ProposalInfo) updates) => super.copyWith((message) => updates(message as ProposalInfo)) as ProposalInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ProposalInfo create() => ProposalInfo._(); @$core.override ProposalInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ProposalInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ProposalInfo? _defaultInstance; /// The height of the proposal. @$pb.TagNumber(1) $core.int get height => $_getIZ(0); @$pb.TagNumber(1) set height($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasHeight() => $_has(0); @$pb.TagNumber(1) void clearHeight() => $_clearField(1); /// The round of the proposal. @$pb.TagNumber(2) $core.int get round => $_getIZ(1); @$pb.TagNumber(2) set round($core.int value) => $_setSignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasRound() => $_has(1); @$pb.TagNumber(2) void clearRound() => $_clearField(2); /// The block data of the proposal. @$pb.TagNumber(3) $core.String get blockData => $_getSZ(2); @$pb.TagNumber(3) set blockData($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasBlockData() => $_has(2); @$pb.TagNumber(3) void clearBlockData() => $_clearField(3); /// The signature of the proposal, signed by the proposer. @$pb.TagNumber(4) $core.String get signature => $_getSZ(3); @$pb.TagNumber(4) set signature($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasSignature() => $_has(3); @$pb.TagNumber(4) void clearSignature() => $_clearField(4); } /// Blockchain service defines RPC methods for interacting with the blockchain. class BlockchainApi { final $pb.RpcClient _client; BlockchainApi(this._client); /// GetBlock retrieves information about a block based on the provided request parameters. $async.Future getBlock( $pb.ClientContext? ctx, GetBlockRequest request) => _client.invoke( ctx, 'Blockchain', 'GetBlock', request, GetBlockResponse()); /// GetBlockHash retrieves the hash of a block at the specified height. $async.Future getBlockHash( $pb.ClientContext? ctx, GetBlockHashRequest request) => _client.invoke( ctx, 'Blockchain', 'GetBlockHash', request, GetBlockHashResponse()); /// GetBlockHeight retrieves the height of a block with the specified hash. $async.Future getBlockHeight( $pb.ClientContext? ctx, GetBlockHeightRequest request) => _client.invoke(ctx, 'Blockchain', 'GetBlockHeight', request, GetBlockHeightResponse()); /// GetBlockchainInfo retrieves general information about the blockchain. $async.Future getBlockchainInfo( $pb.ClientContext? ctx, GetBlockchainInfoRequest request) => _client.invoke(ctx, 'Blockchain', 'GetBlockchainInfo', request, GetBlockchainInfoResponse()); /// GetCommitteeInfo retrieves information about the current committee. $async.Future getCommitteeInfo( $pb.ClientContext? ctx, GetCommitteeInfoRequest request) => _client.invoke(ctx, 'Blockchain', 'GetCommitteeInfo', request, GetCommitteeInfoResponse()); /// GetConsensusInfo retrieves information about the consensus instances. $async.Future getConsensusInfo( $pb.ClientContext? ctx, GetConsensusInfoRequest request) => _client.invoke(ctx, 'Blockchain', 'GetConsensusInfo', request, GetConsensusInfoResponse()); /// GetAccount retrieves information about an account based on the provided address. $async.Future getAccount( $pb.ClientContext? ctx, GetAccountRequest request) => _client.invoke( ctx, 'Blockchain', 'GetAccount', request, GetAccountResponse()); /// GetValidator retrieves information about a validator based on the provided address. $async.Future getValidator( $pb.ClientContext? ctx, GetValidatorRequest request) => _client.invoke( ctx, 'Blockchain', 'GetValidator', request, GetValidatorResponse()); /// GetValidatorByNumber retrieves information about a validator based on the provided number. $async.Future getValidatorByNumber( $pb.ClientContext? ctx, GetValidatorByNumberRequest request) => _client.invoke(ctx, 'Blockchain', 'GetValidatorByNumber', request, GetValidatorResponse()); /// GetValidatorAddresses retrieves a list of all validator addresses. $async.Future getValidatorAddresses( $pb.ClientContext? ctx, GetValidatorAddressesRequest request) => _client.invoke(ctx, 'Blockchain', 'GetValidatorAddresses', request, GetValidatorAddressesResponse()); /// GetPublicKey retrieves the public key of an account based on the provided address. $async.Future getPublicKey( $pb.ClientContext? ctx, GetPublicKeyRequest request) => _client.invoke( ctx, 'Blockchain', 'GetPublicKey', request, GetPublicKeyResponse()); /// GetTxPoolContent retrieves current transactions in the transaction pool. $async.Future getTxPoolContent( $pb.ClientContext? ctx, GetTxPoolContentRequest request) => _client.invoke(ctx, 'Blockchain', 'GetTxPoolContent', request, GetTxPoolContentResponse()); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: www/grpc/gen/dart/blockchain.pbenum.dart ================================================ // This is a generated file - do not edit. // // Generated from blockchain.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; /// Enumeration for verbosity levels when requesting block information. class BlockVerbosity extends $pb.ProtobufEnum { /// Request only block data. static const BlockVerbosity BLOCK_VERBOSITY_DATA = BlockVerbosity._(0, _omitEnumNames ? '' : 'BLOCK_VERBOSITY_DATA'); /// Request block information and transaction IDs. static const BlockVerbosity BLOCK_VERBOSITY_INFO = BlockVerbosity._(1, _omitEnumNames ? '' : 'BLOCK_VERBOSITY_INFO'); /// Request block information and detailed transaction data. static const BlockVerbosity BLOCK_VERBOSITY_TRANSACTIONS = BlockVerbosity._(2, _omitEnumNames ? '' : 'BLOCK_VERBOSITY_TRANSACTIONS'); static const $core.List values = [ BLOCK_VERBOSITY_DATA, BLOCK_VERBOSITY_INFO, BLOCK_VERBOSITY_TRANSACTIONS, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 2); static BlockVerbosity? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const BlockVerbosity._(super.value, super.name); } /// Enumeration for types of votes. class VoteType extends $pb.ProtobufEnum { /// Unspecified vote type. static const VoteType VOTE_TYPE_UNSPECIFIED = VoteType._(0, _omitEnumNames ? '' : 'VOTE_TYPE_UNSPECIFIED'); /// Prepare vote type. static const VoteType VOTE_TYPE_PREPARE = VoteType._(1, _omitEnumNames ? '' : 'VOTE_TYPE_PREPARE'); /// Precommit vote type. static const VoteType VOTE_TYPE_PRECOMMIT = VoteType._(2, _omitEnumNames ? '' : 'VOTE_TYPE_PRECOMMIT'); /// Change-proposer:pre-vote vote type. static const VoteType VOTE_TYPE_CP_PRE_VOTE = VoteType._(3, _omitEnumNames ? '' : 'VOTE_TYPE_CP_PRE_VOTE'); /// Change-proposer:main-vote vote type. static const VoteType VOTE_TYPE_CP_MAIN_VOTE = VoteType._(4, _omitEnumNames ? '' : 'VOTE_TYPE_CP_MAIN_VOTE'); /// Change-proposer:decided vote type. static const VoteType VOTE_TYPE_CP_DECIDED = VoteType._(5, _omitEnumNames ? '' : 'VOTE_TYPE_CP_DECIDED'); static const $core.List values = [ VOTE_TYPE_UNSPECIFIED, VOTE_TYPE_PREPARE, VOTE_TYPE_PRECOMMIT, VOTE_TYPE_CP_PRE_VOTE, VOTE_TYPE_CP_MAIN_VOTE, VOTE_TYPE_CP_DECIDED, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 5); static VoteType? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const VoteType._(super.value, super.name); } const $core.bool _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names'); ================================================ FILE: www/grpc/gen/dart/blockchain.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from blockchain.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; import 'transaction.pbjson.dart' as $0; @$core.Deprecated('Use blockVerbosityDescriptor instead') const BlockVerbosity$json = { '1': 'BlockVerbosity', '2': [ {'1': 'BLOCK_VERBOSITY_DATA', '2': 0}, {'1': 'BLOCK_VERBOSITY_INFO', '2': 1}, {'1': 'BLOCK_VERBOSITY_TRANSACTIONS', '2': 2}, ], }; /// Descriptor for `BlockVerbosity`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List blockVerbosityDescriptor = $convert.base64Decode( 'Cg5CbG9ja1ZlcmJvc2l0eRIYChRCTE9DS19WRVJCT1NJVFlfREFUQRAAEhgKFEJMT0NLX1ZFUk' 'JPU0lUWV9JTkZPEAESIAocQkxPQ0tfVkVSQk9TSVRZX1RSQU5TQUNUSU9OUxAC'); @$core.Deprecated('Use voteTypeDescriptor instead') const VoteType$json = { '1': 'VoteType', '2': [ {'1': 'VOTE_TYPE_UNSPECIFIED', '2': 0}, {'1': 'VOTE_TYPE_PREPARE', '2': 1}, {'1': 'VOTE_TYPE_PRECOMMIT', '2': 2}, {'1': 'VOTE_TYPE_CP_PRE_VOTE', '2': 3}, {'1': 'VOTE_TYPE_CP_MAIN_VOTE', '2': 4}, {'1': 'VOTE_TYPE_CP_DECIDED', '2': 5}, ], }; /// Descriptor for `VoteType`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List voteTypeDescriptor = $convert.base64Decode( 'CghWb3RlVHlwZRIZChVWT1RFX1RZUEVfVU5TUEVDSUZJRUQQABIVChFWT1RFX1RZUEVfUFJFUE' 'FSRRABEhcKE1ZPVEVfVFlQRV9QUkVDT01NSVQQAhIZChVWT1RFX1RZUEVfQ1BfUFJFX1ZPVEUQ' 'AxIaChZWT1RFX1RZUEVfQ1BfTUFJTl9WT1RFEAQSGAoUVk9URV9UWVBFX0NQX0RFQ0lERUQQBQ' '=='); @$core.Deprecated('Use getAccountRequestDescriptor instead') const GetAccountRequest$json = { '1': 'GetAccountRequest', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `GetAccountRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getAccountRequestDescriptor = $convert.base64Decode( 'ChFHZXRBY2NvdW50UmVxdWVzdBIYCgdhZGRyZXNzGAEgASgJUgdhZGRyZXNz'); @$core.Deprecated('Use getAccountResponseDescriptor instead') const GetAccountResponse$json = { '1': 'GetAccountResponse', '2': [ { '1': 'account', '3': 1, '4': 1, '5': 11, '6': '.pactus.AccountInfo', '10': 'account' }, ], }; /// Descriptor for `GetAccountResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getAccountResponseDescriptor = $convert.base64Decode( 'ChJHZXRBY2NvdW50UmVzcG9uc2USLQoHYWNjb3VudBgBIAEoCzITLnBhY3R1cy5BY2NvdW50SW' '5mb1IHYWNjb3VudA=='); @$core.Deprecated('Use getValidatorAddressesRequestDescriptor instead') const GetValidatorAddressesRequest$json = { '1': 'GetValidatorAddressesRequest', }; /// Descriptor for `GetValidatorAddressesRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorAddressesRequestDescriptor = $convert.base64Decode('ChxHZXRWYWxpZGF0b3JBZGRyZXNzZXNSZXF1ZXN0'); @$core.Deprecated('Use getValidatorAddressesResponseDescriptor instead') const GetValidatorAddressesResponse$json = { '1': 'GetValidatorAddressesResponse', '2': [ {'1': 'addresses', '3': 1, '4': 3, '5': 9, '10': 'addresses'}, ], }; /// Descriptor for `GetValidatorAddressesResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorAddressesResponseDescriptor = $convert.base64Decode( 'Ch1HZXRWYWxpZGF0b3JBZGRyZXNzZXNSZXNwb25zZRIcCglhZGRyZXNzZXMYASADKAlSCWFkZH' 'Jlc3Nlcw=='); @$core.Deprecated('Use getValidatorRequestDescriptor instead') const GetValidatorRequest$json = { '1': 'GetValidatorRequest', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `GetValidatorRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorRequestDescriptor = $convert.base64Decode( 'ChNHZXRWYWxpZGF0b3JSZXF1ZXN0EhgKB2FkZHJlc3MYASABKAlSB2FkZHJlc3M='); @$core.Deprecated('Use getValidatorByNumberRequestDescriptor instead') const GetValidatorByNumberRequest$json = { '1': 'GetValidatorByNumberRequest', '2': [ {'1': 'number', '3': 1, '4': 1, '5': 5, '10': 'number'}, ], }; /// Descriptor for `GetValidatorByNumberRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorByNumberRequestDescriptor = $convert.base64Decode( 'ChtHZXRWYWxpZGF0b3JCeU51bWJlclJlcXVlc3QSFgoGbnVtYmVyGAEgASgFUgZudW1iZXI='); @$core.Deprecated('Use getValidatorResponseDescriptor instead') const GetValidatorResponse$json = { '1': 'GetValidatorResponse', '2': [ { '1': 'validator', '3': 1, '4': 1, '5': 11, '6': '.pactus.ValidatorInfo', '10': 'validator' }, ], }; /// Descriptor for `GetValidatorResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorResponseDescriptor = $convert.base64Decode( 'ChRHZXRWYWxpZGF0b3JSZXNwb25zZRIzCgl2YWxpZGF0b3IYASABKAsyFS5wYWN0dXMuVmFsaW' 'RhdG9ySW5mb1IJdmFsaWRhdG9y'); @$core.Deprecated('Use getPublicKeyRequestDescriptor instead') const GetPublicKeyRequest$json = { '1': 'GetPublicKeyRequest', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `GetPublicKeyRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getPublicKeyRequestDescriptor = $convert.base64Decode( 'ChNHZXRQdWJsaWNLZXlSZXF1ZXN0EhgKB2FkZHJlc3MYASABKAlSB2FkZHJlc3M='); @$core.Deprecated('Use getPublicKeyResponseDescriptor instead') const GetPublicKeyResponse$json = { '1': 'GetPublicKeyResponse', '2': [ {'1': 'public_key', '3': 1, '4': 1, '5': 9, '10': 'publicKey'}, ], }; /// Descriptor for `GetPublicKeyResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getPublicKeyResponseDescriptor = $convert.base64Decode( 'ChRHZXRQdWJsaWNLZXlSZXNwb25zZRIdCgpwdWJsaWNfa2V5GAEgASgJUglwdWJsaWNLZXk='); @$core.Deprecated('Use getBlockRequestDescriptor instead') const GetBlockRequest$json = { '1': 'GetBlockRequest', '2': [ {'1': 'height', '3': 1, '4': 1, '5': 13, '10': 'height'}, { '1': 'verbosity', '3': 2, '4': 1, '5': 14, '6': '.pactus.BlockVerbosity', '10': 'verbosity' }, ], }; /// Descriptor for `GetBlockRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockRequestDescriptor = $convert.base64Decode( 'Cg9HZXRCbG9ja1JlcXVlc3QSFgoGaGVpZ2h0GAEgASgNUgZoZWlnaHQSNAoJdmVyYm9zaXR5GA' 'IgASgOMhYucGFjdHVzLkJsb2NrVmVyYm9zaXR5Ugl2ZXJib3NpdHk='); @$core.Deprecated('Use getBlockResponseDescriptor instead') const GetBlockResponse$json = { '1': 'GetBlockResponse', '2': [ {'1': 'height', '3': 1, '4': 1, '5': 13, '10': 'height'}, {'1': 'hash', '3': 2, '4': 1, '5': 9, '10': 'hash'}, {'1': 'data', '3': 3, '4': 1, '5': 9, '10': 'data'}, {'1': 'block_time', '3': 4, '4': 1, '5': 13, '10': 'blockTime'}, { '1': 'header', '3': 5, '4': 1, '5': 11, '6': '.pactus.BlockHeaderInfo', '10': 'header' }, { '1': 'prev_cert', '3': 6, '4': 1, '5': 11, '6': '.pactus.CertificateInfo', '10': 'prevCert' }, { '1': 'txs', '3': 7, '4': 3, '5': 11, '6': '.pactus.TransactionInfo', '10': 'txs' }, ], }; /// Descriptor for `GetBlockResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockResponseDescriptor = $convert.base64Decode( 'ChBHZXRCbG9ja1Jlc3BvbnNlEhYKBmhlaWdodBgBIAEoDVIGaGVpZ2h0EhIKBGhhc2gYAiABKA' 'lSBGhhc2gSEgoEZGF0YRgDIAEoCVIEZGF0YRIdCgpibG9ja190aW1lGAQgASgNUglibG9ja1Rp' 'bWUSLwoGaGVhZGVyGAUgASgLMhcucGFjdHVzLkJsb2NrSGVhZGVySW5mb1IGaGVhZGVyEjQKCX' 'ByZXZfY2VydBgGIAEoCzIXLnBhY3R1cy5DZXJ0aWZpY2F0ZUluZm9SCHByZXZDZXJ0EikKA3R4' 'cxgHIAMoCzIXLnBhY3R1cy5UcmFuc2FjdGlvbkluZm9SA3R4cw=='); @$core.Deprecated('Use getBlockHashRequestDescriptor instead') const GetBlockHashRequest$json = { '1': 'GetBlockHashRequest', '2': [ {'1': 'height', '3': 1, '4': 1, '5': 13, '10': 'height'}, ], }; /// Descriptor for `GetBlockHashRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockHashRequestDescriptor = $convert.base64Decode( 'ChNHZXRCbG9ja0hhc2hSZXF1ZXN0EhYKBmhlaWdodBgBIAEoDVIGaGVpZ2h0'); @$core.Deprecated('Use getBlockHashResponseDescriptor instead') const GetBlockHashResponse$json = { '1': 'GetBlockHashResponse', '2': [ {'1': 'hash', '3': 1, '4': 1, '5': 9, '10': 'hash'}, ], }; /// Descriptor for `GetBlockHashResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockHashResponseDescriptor = $convert .base64Decode('ChRHZXRCbG9ja0hhc2hSZXNwb25zZRISCgRoYXNoGAEgASgJUgRoYXNo'); @$core.Deprecated('Use getBlockHeightRequestDescriptor instead') const GetBlockHeightRequest$json = { '1': 'GetBlockHeightRequest', '2': [ {'1': 'hash', '3': 1, '4': 1, '5': 9, '10': 'hash'}, ], }; /// Descriptor for `GetBlockHeightRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockHeightRequestDescriptor = $convert.base64Decode( 'ChVHZXRCbG9ja0hlaWdodFJlcXVlc3QSEgoEaGFzaBgBIAEoCVIEaGFzaA=='); @$core.Deprecated('Use getBlockHeightResponseDescriptor instead') const GetBlockHeightResponse$json = { '1': 'GetBlockHeightResponse', '2': [ {'1': 'height', '3': 1, '4': 1, '5': 13, '10': 'height'}, ], }; /// Descriptor for `GetBlockHeightResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockHeightResponseDescriptor = $convert.base64Decode( 'ChZHZXRCbG9ja0hlaWdodFJlc3BvbnNlEhYKBmhlaWdodBgBIAEoDVIGaGVpZ2h0'); @$core.Deprecated('Use getBlockchainInfoRequestDescriptor instead') const GetBlockchainInfoRequest$json = { '1': 'GetBlockchainInfoRequest', }; /// Descriptor for `GetBlockchainInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockchainInfoRequestDescriptor = $convert.base64Decode('ChhHZXRCbG9ja2NoYWluSW5mb1JlcXVlc3Q='); @$core.Deprecated('Use getBlockchainInfoResponseDescriptor instead') const GetBlockchainInfoResponse$json = { '1': 'GetBlockchainInfoResponse', '2': [ { '1': 'last_block_height', '3': 1, '4': 1, '5': 13, '10': 'lastBlockHeight' }, {'1': 'last_block_hash', '3': 2, '4': 1, '5': 9, '10': 'lastBlockHash'}, {'1': 'last_block_time', '3': 10, '4': 1, '5': 3, '10': 'lastBlockTime'}, {'1': 'total_accounts', '3': 3, '4': 1, '5': 5, '10': 'totalAccounts'}, {'1': 'total_validators', '3': 4, '4': 1, '5': 5, '10': 'totalValidators'}, { '1': 'active_validators', '3': 12, '4': 1, '5': 5, '10': 'activeValidators' }, {'1': 'total_power', '3': 5, '4': 1, '5': 3, '10': 'totalPower'}, {'1': 'committee_power', '3': 6, '4': 1, '5': 3, '10': 'committeePower'}, {'1': 'is_pruned', '3': 8, '4': 1, '5': 8, '10': 'isPruned'}, {'1': 'pruning_height', '3': 9, '4': 1, '5': 13, '10': 'pruningHeight'}, {'1': 'in_committee', '3': 13, '4': 1, '5': 8, '10': 'inCommittee'}, {'1': 'committee_size', '3': 14, '4': 1, '5': 5, '10': 'committeeSize'}, {'1': 'average_score', '3': 15, '4': 1, '5': 1, '10': 'averageScore'}, ], }; /// Descriptor for `GetBlockchainInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getBlockchainInfoResponseDescriptor = $convert.base64Decode( 'ChlHZXRCbG9ja2NoYWluSW5mb1Jlc3BvbnNlEioKEWxhc3RfYmxvY2tfaGVpZ2h0GAEgASgNUg' '9sYXN0QmxvY2tIZWlnaHQSJgoPbGFzdF9ibG9ja19oYXNoGAIgASgJUg1sYXN0QmxvY2tIYXNo' 'EiYKD2xhc3RfYmxvY2tfdGltZRgKIAEoA1INbGFzdEJsb2NrVGltZRIlCg50b3RhbF9hY2NvdW' '50cxgDIAEoBVINdG90YWxBY2NvdW50cxIpChB0b3RhbF92YWxpZGF0b3JzGAQgASgFUg90b3Rh' 'bFZhbGlkYXRvcnMSKwoRYWN0aXZlX3ZhbGlkYXRvcnMYDCABKAVSEGFjdGl2ZVZhbGlkYXRvcn' 'MSHwoLdG90YWxfcG93ZXIYBSABKANSCnRvdGFsUG93ZXISJwoPY29tbWl0dGVlX3Bvd2VyGAYg' 'ASgDUg5jb21taXR0ZWVQb3dlchIbCglpc19wcnVuZWQYCCABKAhSCGlzUHJ1bmVkEiUKDnBydW' '5pbmdfaGVpZ2h0GAkgASgNUg1wcnVuaW5nSGVpZ2h0EiEKDGluX2NvbW1pdHRlZRgNIAEoCFIL' 'aW5Db21taXR0ZWUSJQoOY29tbWl0dGVlX3NpemUYDiABKAVSDWNvbW1pdHRlZVNpemUSIwoNYX' 'ZlcmFnZV9zY29yZRgPIAEoAVIMYXZlcmFnZVNjb3Jl'); @$core.Deprecated('Use getCommitteeInfoRequestDescriptor instead') const GetCommitteeInfoRequest$json = { '1': 'GetCommitteeInfoRequest', }; /// Descriptor for `GetCommitteeInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getCommitteeInfoRequestDescriptor = $convert.base64Decode('ChdHZXRDb21taXR0ZWVJbmZvUmVxdWVzdA=='); @$core.Deprecated('Use getCommitteeInfoResponseDescriptor instead') const GetCommitteeInfoResponse$json = { '1': 'GetCommitteeInfoResponse', '2': [ {'1': 'committee_size', '3': 1, '4': 1, '5': 5, '10': 'committeeSize'}, {'1': 'committee_power', '3': 2, '4': 1, '5': 3, '10': 'committeePower'}, {'1': 'total_power', '3': 3, '4': 1, '5': 3, '10': 'totalPower'}, { '1': 'validators', '3': 4, '4': 3, '5': 11, '6': '.pactus.ValidatorInfo', '10': 'validators' }, { '1': 'protocol_versions', '3': 5, '4': 3, '5': 11, '6': '.pactus.GetCommitteeInfoResponse.ProtocolVersionsEntry', '10': 'protocolVersions' }, ], '3': [GetCommitteeInfoResponse_ProtocolVersionsEntry$json], }; @$core.Deprecated('Use getCommitteeInfoResponseDescriptor instead') const GetCommitteeInfoResponse_ProtocolVersionsEntry$json = { '1': 'ProtocolVersionsEntry', '2': [ {'1': 'key', '3': 1, '4': 1, '5': 5, '10': 'key'}, {'1': 'value', '3': 2, '4': 1, '5': 1, '10': 'value'}, ], '7': {'7': true}, }; /// Descriptor for `GetCommitteeInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getCommitteeInfoResponseDescriptor = $convert.base64Decode( 'ChhHZXRDb21taXR0ZWVJbmZvUmVzcG9uc2USJQoOY29tbWl0dGVlX3NpemUYASABKAVSDWNvbW' '1pdHRlZVNpemUSJwoPY29tbWl0dGVlX3Bvd2VyGAIgASgDUg5jb21taXR0ZWVQb3dlchIfCgt0' 'b3RhbF9wb3dlchgDIAEoA1IKdG90YWxQb3dlchI1Cgp2YWxpZGF0b3JzGAQgAygLMhUucGFjdH' 'VzLlZhbGlkYXRvckluZm9SCnZhbGlkYXRvcnMSYwoRcHJvdG9jb2xfdmVyc2lvbnMYBSADKAsy' 'Ni5wYWN0dXMuR2V0Q29tbWl0dGVlSW5mb1Jlc3BvbnNlLlByb3RvY29sVmVyc2lvbnNFbnRyeV' 'IQcHJvdG9jb2xWZXJzaW9ucxpDChVQcm90b2NvbFZlcnNpb25zRW50cnkSEAoDa2V5GAEgASgF' 'UgNrZXkSFAoFdmFsdWUYAiABKAFSBXZhbHVlOgI4AQ=='); @$core.Deprecated('Use getConsensusInfoRequestDescriptor instead') const GetConsensusInfoRequest$json = { '1': 'GetConsensusInfoRequest', }; /// Descriptor for `GetConsensusInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getConsensusInfoRequestDescriptor = $convert.base64Decode('ChdHZXRDb25zZW5zdXNJbmZvUmVxdWVzdA=='); @$core.Deprecated('Use getConsensusInfoResponseDescriptor instead') const GetConsensusInfoResponse$json = { '1': 'GetConsensusInfoResponse', '2': [ { '1': 'proposal', '3': 1, '4': 1, '5': 11, '6': '.pactus.ProposalInfo', '10': 'proposal' }, { '1': 'instances', '3': 2, '4': 3, '5': 11, '6': '.pactus.ConsensusInfo', '10': 'instances' }, ], }; /// Descriptor for `GetConsensusInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getConsensusInfoResponseDescriptor = $convert.base64Decode( 'ChhHZXRDb25zZW5zdXNJbmZvUmVzcG9uc2USMAoIcHJvcG9zYWwYASABKAsyFC5wYWN0dXMuUH' 'JvcG9zYWxJbmZvUghwcm9wb3NhbBIzCglpbnN0YW5jZXMYAiADKAsyFS5wYWN0dXMuQ29uc2Vu' 'c3VzSW5mb1IJaW5zdGFuY2Vz'); @$core.Deprecated('Use getTxPoolContentRequestDescriptor instead') const GetTxPoolContentRequest$json = { '1': 'GetTxPoolContentRequest', '2': [ { '1': 'payload_type', '3': 1, '4': 1, '5': 14, '6': '.pactus.PayloadType', '10': 'payloadType' }, ], }; /// Descriptor for `GetTxPoolContentRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTxPoolContentRequestDescriptor = $convert.base64Decode( 'ChdHZXRUeFBvb2xDb250ZW50UmVxdWVzdBI2CgxwYXlsb2FkX3R5cGUYASABKA4yEy5wYWN0dX' 'MuUGF5bG9hZFR5cGVSC3BheWxvYWRUeXBl'); @$core.Deprecated('Use getTxPoolContentResponseDescriptor instead') const GetTxPoolContentResponse$json = { '1': 'GetTxPoolContentResponse', '2': [ { '1': 'txs', '3': 1, '4': 3, '5': 11, '6': '.pactus.TransactionInfo', '10': 'txs' }, ], }; /// Descriptor for `GetTxPoolContentResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTxPoolContentResponseDescriptor = $convert.base64Decode( 'ChhHZXRUeFBvb2xDb250ZW50UmVzcG9uc2USKQoDdHhzGAEgAygLMhcucGFjdHVzLlRyYW5zYW' 'N0aW9uSW5mb1IDdHhz'); @$core.Deprecated('Use validatorInfoDescriptor instead') const ValidatorInfo$json = { '1': 'ValidatorInfo', '2': [ {'1': 'hash', '3': 1, '4': 1, '5': 9, '10': 'hash'}, {'1': 'data', '3': 2, '4': 1, '5': 9, '10': 'data'}, {'1': 'public_key', '3': 3, '4': 1, '5': 9, '10': 'publicKey'}, {'1': 'number', '3': 4, '4': 1, '5': 5, '10': 'number'}, {'1': 'stake', '3': 5, '4': 1, '5': 3, '10': 'stake'}, { '1': 'last_bonding_height', '3': 6, '4': 1, '5': 13, '10': 'lastBondingHeight' }, { '1': 'last_sortition_height', '3': 7, '4': 1, '5': 13, '10': 'lastSortitionHeight' }, {'1': 'unbonding_height', '3': 8, '4': 1, '5': 13, '10': 'unbondingHeight'}, {'1': 'address', '3': 9, '4': 1, '5': 9, '10': 'address'}, { '1': 'availability_score', '3': 10, '4': 1, '5': 1, '10': 'availabilityScore' }, {'1': 'protocol_version', '3': 11, '4': 1, '5': 5, '10': 'protocolVersion'}, {'1': 'is_delegated', '3': 12, '4': 1, '5': 8, '10': 'isDelegated'}, {'1': 'delegate_owner', '3': 13, '4': 1, '5': 9, '10': 'delegateOwner'}, {'1': 'delegate_share', '3': 14, '4': 1, '5': 3, '10': 'delegateShare'}, {'1': 'delegate_expiry', '3': 15, '4': 1, '5': 13, '10': 'delegateExpiry'}, ], }; /// Descriptor for `ValidatorInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List validatorInfoDescriptor = $convert.base64Decode( 'Cg1WYWxpZGF0b3JJbmZvEhIKBGhhc2gYASABKAlSBGhhc2gSEgoEZGF0YRgCIAEoCVIEZGF0YR' 'IdCgpwdWJsaWNfa2V5GAMgASgJUglwdWJsaWNLZXkSFgoGbnVtYmVyGAQgASgFUgZudW1iZXIS' 'FAoFc3Rha2UYBSABKANSBXN0YWtlEi4KE2xhc3RfYm9uZGluZ19oZWlnaHQYBiABKA1SEWxhc3' 'RCb25kaW5nSGVpZ2h0EjIKFWxhc3Rfc29ydGl0aW9uX2hlaWdodBgHIAEoDVITbGFzdFNvcnRp' 'dGlvbkhlaWdodBIpChB1bmJvbmRpbmdfaGVpZ2h0GAggASgNUg91bmJvbmRpbmdIZWlnaHQSGA' 'oHYWRkcmVzcxgJIAEoCVIHYWRkcmVzcxItChJhdmFpbGFiaWxpdHlfc2NvcmUYCiABKAFSEWF2' 'YWlsYWJpbGl0eVNjb3JlEikKEHByb3RvY29sX3ZlcnNpb24YCyABKAVSD3Byb3RvY29sVmVyc2' 'lvbhIhCgxpc19kZWxlZ2F0ZWQYDCABKAhSC2lzRGVsZWdhdGVkEiUKDmRlbGVnYXRlX293bmVy' 'GA0gASgJUg1kZWxlZ2F0ZU93bmVyEiUKDmRlbGVnYXRlX3NoYXJlGA4gASgDUg1kZWxlZ2F0ZV' 'NoYXJlEicKD2RlbGVnYXRlX2V4cGlyeRgPIAEoDVIOZGVsZWdhdGVFeHBpcnk='); @$core.Deprecated('Use accountInfoDescriptor instead') const AccountInfo$json = { '1': 'AccountInfo', '2': [ {'1': 'hash', '3': 1, '4': 1, '5': 9, '10': 'hash'}, {'1': 'data', '3': 2, '4': 1, '5': 9, '10': 'data'}, {'1': 'number', '3': 3, '4': 1, '5': 5, '10': 'number'}, {'1': 'balance', '3': 4, '4': 1, '5': 3, '10': 'balance'}, {'1': 'address', '3': 5, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `AccountInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List accountInfoDescriptor = $convert.base64Decode( 'CgtBY2NvdW50SW5mbxISCgRoYXNoGAEgASgJUgRoYXNoEhIKBGRhdGEYAiABKAlSBGRhdGESFg' 'oGbnVtYmVyGAMgASgFUgZudW1iZXISGAoHYmFsYW5jZRgEIAEoA1IHYmFsYW5jZRIYCgdhZGRy' 'ZXNzGAUgASgJUgdhZGRyZXNz'); @$core.Deprecated('Use blockHeaderInfoDescriptor instead') const BlockHeaderInfo$json = { '1': 'BlockHeaderInfo', '2': [ {'1': 'version', '3': 1, '4': 1, '5': 5, '10': 'version'}, {'1': 'prev_block_hash', '3': 2, '4': 1, '5': 9, '10': 'prevBlockHash'}, {'1': 'state_root', '3': 3, '4': 1, '5': 9, '10': 'stateRoot'}, {'1': 'sortition_seed', '3': 4, '4': 1, '5': 9, '10': 'sortitionSeed'}, {'1': 'proposer_address', '3': 5, '4': 1, '5': 9, '10': 'proposerAddress'}, ], }; /// Descriptor for `BlockHeaderInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List blockHeaderInfoDescriptor = $convert.base64Decode( 'Cg9CbG9ja0hlYWRlckluZm8SGAoHdmVyc2lvbhgBIAEoBVIHdmVyc2lvbhImCg9wcmV2X2Jsb2' 'NrX2hhc2gYAiABKAlSDXByZXZCbG9ja0hhc2gSHQoKc3RhdGVfcm9vdBgDIAEoCVIJc3RhdGVS' 'b290EiUKDnNvcnRpdGlvbl9zZWVkGAQgASgJUg1zb3J0aXRpb25TZWVkEikKEHByb3Bvc2VyX2' 'FkZHJlc3MYBSABKAlSD3Byb3Bvc2VyQWRkcmVzcw=='); @$core.Deprecated('Use certificateInfoDescriptor instead') const CertificateInfo$json = { '1': 'CertificateInfo', '2': [ {'1': 'hash', '3': 1, '4': 1, '5': 9, '10': 'hash'}, {'1': 'round', '3': 2, '4': 1, '5': 5, '10': 'round'}, {'1': 'committers', '3': 3, '4': 3, '5': 5, '10': 'committers'}, {'1': 'absentees', '3': 4, '4': 3, '5': 5, '10': 'absentees'}, {'1': 'signature', '3': 5, '4': 1, '5': 9, '10': 'signature'}, ], }; /// Descriptor for `CertificateInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List certificateInfoDescriptor = $convert.base64Decode( 'Cg9DZXJ0aWZpY2F0ZUluZm8SEgoEaGFzaBgBIAEoCVIEaGFzaBIUCgVyb3VuZBgCIAEoBVIFcm' '91bmQSHgoKY29tbWl0dGVycxgDIAMoBVIKY29tbWl0dGVycxIcCglhYnNlbnRlZXMYBCADKAVS' 'CWFic2VudGVlcxIcCglzaWduYXR1cmUYBSABKAlSCXNpZ25hdHVyZQ=='); @$core.Deprecated('Use voteInfoDescriptor instead') const VoteInfo$json = { '1': 'VoteInfo', '2': [ { '1': 'type', '3': 1, '4': 1, '5': 14, '6': '.pactus.VoteType', '10': 'type' }, {'1': 'voter', '3': 2, '4': 1, '5': 9, '10': 'voter'}, {'1': 'block_hash', '3': 3, '4': 1, '5': 9, '10': 'blockHash'}, {'1': 'round', '3': 4, '4': 1, '5': 5, '10': 'round'}, {'1': 'cp_round', '3': 5, '4': 1, '5': 5, '10': 'cpRound'}, {'1': 'cp_value', '3': 6, '4': 1, '5': 5, '10': 'cpValue'}, ], }; /// Descriptor for `VoteInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List voteInfoDescriptor = $convert.base64Decode( 'CghWb3RlSW5mbxIkCgR0eXBlGAEgASgOMhAucGFjdHVzLlZvdGVUeXBlUgR0eXBlEhQKBXZvdG' 'VyGAIgASgJUgV2b3RlchIdCgpibG9ja19oYXNoGAMgASgJUglibG9ja0hhc2gSFAoFcm91bmQY' 'BCABKAVSBXJvdW5kEhkKCGNwX3JvdW5kGAUgASgFUgdjcFJvdW5kEhkKCGNwX3ZhbHVlGAYgAS' 'gFUgdjcFZhbHVl'); @$core.Deprecated('Use consensusInfoDescriptor instead') const ConsensusInfo$json = { '1': 'ConsensusInfo', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, {'1': 'active', '3': 2, '4': 1, '5': 8, '10': 'active'}, {'1': 'height', '3': 3, '4': 1, '5': 13, '10': 'height'}, {'1': 'round', '3': 4, '4': 1, '5': 5, '10': 'round'}, { '1': 'votes', '3': 5, '4': 3, '5': 11, '6': '.pactus.VoteInfo', '10': 'votes' }, ], }; /// Descriptor for `ConsensusInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List consensusInfoDescriptor = $convert.base64Decode( 'Cg1Db25zZW5zdXNJbmZvEhgKB2FkZHJlc3MYASABKAlSB2FkZHJlc3MSFgoGYWN0aXZlGAIgAS' 'gIUgZhY3RpdmUSFgoGaGVpZ2h0GAMgASgNUgZoZWlnaHQSFAoFcm91bmQYBCABKAVSBXJvdW5k' 'EiYKBXZvdGVzGAUgAygLMhAucGFjdHVzLlZvdGVJbmZvUgV2b3Rlcw=='); @$core.Deprecated('Use proposalInfoDescriptor instead') const ProposalInfo$json = { '1': 'ProposalInfo', '2': [ {'1': 'height', '3': 1, '4': 1, '5': 13, '10': 'height'}, {'1': 'round', '3': 2, '4': 1, '5': 5, '10': 'round'}, {'1': 'block_data', '3': 3, '4': 1, '5': 9, '10': 'blockData'}, {'1': 'signature', '3': 4, '4': 1, '5': 9, '10': 'signature'}, ], }; /// Descriptor for `ProposalInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List proposalInfoDescriptor = $convert.base64Decode( 'CgxQcm9wb3NhbEluZm8SFgoGaGVpZ2h0GAEgASgNUgZoZWlnaHQSFAoFcm91bmQYAiABKAVSBX' 'JvdW5kEh0KCmJsb2NrX2RhdGEYAyABKAlSCWJsb2NrRGF0YRIcCglzaWduYXR1cmUYBCABKAlS' 'CXNpZ25hdHVyZQ=='); const $core.Map<$core.String, $core.dynamic> BlockchainServiceBase$json = { '1': 'Blockchain', '2': [ { '1': 'GetBlock', '2': '.pactus.GetBlockRequest', '3': '.pactus.GetBlockResponse' }, { '1': 'GetBlockHash', '2': '.pactus.GetBlockHashRequest', '3': '.pactus.GetBlockHashResponse' }, { '1': 'GetBlockHeight', '2': '.pactus.GetBlockHeightRequest', '3': '.pactus.GetBlockHeightResponse' }, { '1': 'GetBlockchainInfo', '2': '.pactus.GetBlockchainInfoRequest', '3': '.pactus.GetBlockchainInfoResponse' }, { '1': 'GetCommitteeInfo', '2': '.pactus.GetCommitteeInfoRequest', '3': '.pactus.GetCommitteeInfoResponse' }, { '1': 'GetConsensusInfo', '2': '.pactus.GetConsensusInfoRequest', '3': '.pactus.GetConsensusInfoResponse' }, { '1': 'GetAccount', '2': '.pactus.GetAccountRequest', '3': '.pactus.GetAccountResponse' }, { '1': 'GetValidator', '2': '.pactus.GetValidatorRequest', '3': '.pactus.GetValidatorResponse' }, { '1': 'GetValidatorByNumber', '2': '.pactus.GetValidatorByNumberRequest', '3': '.pactus.GetValidatorResponse' }, { '1': 'GetValidatorAddresses', '2': '.pactus.GetValidatorAddressesRequest', '3': '.pactus.GetValidatorAddressesResponse' }, { '1': 'GetPublicKey', '2': '.pactus.GetPublicKeyRequest', '3': '.pactus.GetPublicKeyResponse' }, { '1': 'GetTxPoolContent', '2': '.pactus.GetTxPoolContentRequest', '3': '.pactus.GetTxPoolContentResponse' }, ], }; @$core.Deprecated('Use blockchainServiceDescriptor instead') const $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> BlockchainServiceBase$messageJson = { '.pactus.GetBlockRequest': GetBlockRequest$json, '.pactus.GetBlockResponse': GetBlockResponse$json, '.pactus.BlockHeaderInfo': BlockHeaderInfo$json, '.pactus.CertificateInfo': CertificateInfo$json, '.pactus.TransactionInfo': $0.TransactionInfo$json, '.pactus.PayloadTransfer': $0.PayloadTransfer$json, '.pactus.PayloadBond': $0.PayloadBond$json, '.pactus.PayloadSortition': $0.PayloadSortition$json, '.pactus.PayloadUnbond': $0.PayloadUnbond$json, '.pactus.PayloadWithdraw': $0.PayloadWithdraw$json, '.pactus.PayloadBatchTransfer': $0.PayloadBatchTransfer$json, '.pactus.Recipient': $0.Recipient$json, '.pactus.GetBlockHashRequest': GetBlockHashRequest$json, '.pactus.GetBlockHashResponse': GetBlockHashResponse$json, '.pactus.GetBlockHeightRequest': GetBlockHeightRequest$json, '.pactus.GetBlockHeightResponse': GetBlockHeightResponse$json, '.pactus.GetBlockchainInfoRequest': GetBlockchainInfoRequest$json, '.pactus.GetBlockchainInfoResponse': GetBlockchainInfoResponse$json, '.pactus.GetCommitteeInfoRequest': GetCommitteeInfoRequest$json, '.pactus.GetCommitteeInfoResponse': GetCommitteeInfoResponse$json, '.pactus.ValidatorInfo': ValidatorInfo$json, '.pactus.GetCommitteeInfoResponse.ProtocolVersionsEntry': GetCommitteeInfoResponse_ProtocolVersionsEntry$json, '.pactus.GetConsensusInfoRequest': GetConsensusInfoRequest$json, '.pactus.GetConsensusInfoResponse': GetConsensusInfoResponse$json, '.pactus.ProposalInfo': ProposalInfo$json, '.pactus.ConsensusInfo': ConsensusInfo$json, '.pactus.VoteInfo': VoteInfo$json, '.pactus.GetAccountRequest': GetAccountRequest$json, '.pactus.GetAccountResponse': GetAccountResponse$json, '.pactus.AccountInfo': AccountInfo$json, '.pactus.GetValidatorRequest': GetValidatorRequest$json, '.pactus.GetValidatorResponse': GetValidatorResponse$json, '.pactus.GetValidatorByNumberRequest': GetValidatorByNumberRequest$json, '.pactus.GetValidatorAddressesRequest': GetValidatorAddressesRequest$json, '.pactus.GetValidatorAddressesResponse': GetValidatorAddressesResponse$json, '.pactus.GetPublicKeyRequest': GetPublicKeyRequest$json, '.pactus.GetPublicKeyResponse': GetPublicKeyResponse$json, '.pactus.GetTxPoolContentRequest': GetTxPoolContentRequest$json, '.pactus.GetTxPoolContentResponse': GetTxPoolContentResponse$json, }; /// Descriptor for `Blockchain`. Decode as a `google.protobuf.ServiceDescriptorProto`. final $typed_data.Uint8List blockchainServiceDescriptor = $convert.base64Decode( 'CgpCbG9ja2NoYWluEj0KCEdldEJsb2NrEhcucGFjdHVzLkdldEJsb2NrUmVxdWVzdBoYLnBhY3' 'R1cy5HZXRCbG9ja1Jlc3BvbnNlEkkKDEdldEJsb2NrSGFzaBIbLnBhY3R1cy5HZXRCbG9ja0hh' 'c2hSZXF1ZXN0GhwucGFjdHVzLkdldEJsb2NrSGFzaFJlc3BvbnNlEk8KDkdldEJsb2NrSGVpZ2' 'h0Eh0ucGFjdHVzLkdldEJsb2NrSGVpZ2h0UmVxdWVzdBoeLnBhY3R1cy5HZXRCbG9ja0hlaWdo' 'dFJlc3BvbnNlElgKEUdldEJsb2NrY2hhaW5JbmZvEiAucGFjdHVzLkdldEJsb2NrY2hhaW5Jbm' 'ZvUmVxdWVzdBohLnBhY3R1cy5HZXRCbG9ja2NoYWluSW5mb1Jlc3BvbnNlElUKEEdldENvbW1p' 'dHRlZUluZm8SHy5wYWN0dXMuR2V0Q29tbWl0dGVlSW5mb1JlcXVlc3QaIC5wYWN0dXMuR2V0Q2' '9tbWl0dGVlSW5mb1Jlc3BvbnNlElUKEEdldENvbnNlbnN1c0luZm8SHy5wYWN0dXMuR2V0Q29u' 'c2Vuc3VzSW5mb1JlcXVlc3QaIC5wYWN0dXMuR2V0Q29uc2Vuc3VzSW5mb1Jlc3BvbnNlEkMKCk' 'dldEFjY291bnQSGS5wYWN0dXMuR2V0QWNjb3VudFJlcXVlc3QaGi5wYWN0dXMuR2V0QWNjb3Vu' 'dFJlc3BvbnNlEkkKDEdldFZhbGlkYXRvchIbLnBhY3R1cy5HZXRWYWxpZGF0b3JSZXF1ZXN0Gh' 'wucGFjdHVzLkdldFZhbGlkYXRvclJlc3BvbnNlElkKFEdldFZhbGlkYXRvckJ5TnVtYmVyEiMu' 'cGFjdHVzLkdldFZhbGlkYXRvckJ5TnVtYmVyUmVxdWVzdBocLnBhY3R1cy5HZXRWYWxpZGF0b3' 'JSZXNwb25zZRJkChVHZXRWYWxpZGF0b3JBZGRyZXNzZXMSJC5wYWN0dXMuR2V0VmFsaWRhdG9y' 'QWRkcmVzc2VzUmVxdWVzdBolLnBhY3R1cy5HZXRWYWxpZGF0b3JBZGRyZXNzZXNSZXNwb25zZR' 'JJCgxHZXRQdWJsaWNLZXkSGy5wYWN0dXMuR2V0UHVibGljS2V5UmVxdWVzdBocLnBhY3R1cy5H' 'ZXRQdWJsaWNLZXlSZXNwb25zZRJVChBHZXRUeFBvb2xDb250ZW50Eh8ucGFjdHVzLkdldFR4UG' '9vbENvbnRlbnRSZXF1ZXN0GiAucGFjdHVzLkdldFR4UG9vbENvbnRlbnRSZXNwb25zZQ=='); ================================================ FILE: www/grpc/gen/dart/blockchain.pbserver.dart ================================================ // This is a generated file - do not edit. // // Generated from blockchain.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'blockchain.pb.dart' as $1; import 'blockchain.pbjson.dart'; export 'blockchain.pb.dart'; abstract class BlockchainServiceBase extends $pb.GeneratedService { $async.Future<$1.GetBlockResponse> getBlock( $pb.ServerContext ctx, $1.GetBlockRequest request); $async.Future<$1.GetBlockHashResponse> getBlockHash( $pb.ServerContext ctx, $1.GetBlockHashRequest request); $async.Future<$1.GetBlockHeightResponse> getBlockHeight( $pb.ServerContext ctx, $1.GetBlockHeightRequest request); $async.Future<$1.GetBlockchainInfoResponse> getBlockchainInfo( $pb.ServerContext ctx, $1.GetBlockchainInfoRequest request); $async.Future<$1.GetCommitteeInfoResponse> getCommitteeInfo( $pb.ServerContext ctx, $1.GetCommitteeInfoRequest request); $async.Future<$1.GetConsensusInfoResponse> getConsensusInfo( $pb.ServerContext ctx, $1.GetConsensusInfoRequest request); $async.Future<$1.GetAccountResponse> getAccount( $pb.ServerContext ctx, $1.GetAccountRequest request); $async.Future<$1.GetValidatorResponse> getValidator( $pb.ServerContext ctx, $1.GetValidatorRequest request); $async.Future<$1.GetValidatorResponse> getValidatorByNumber( $pb.ServerContext ctx, $1.GetValidatorByNumberRequest request); $async.Future<$1.GetValidatorAddressesResponse> getValidatorAddresses( $pb.ServerContext ctx, $1.GetValidatorAddressesRequest request); $async.Future<$1.GetPublicKeyResponse> getPublicKey( $pb.ServerContext ctx, $1.GetPublicKeyRequest request); $async.Future<$1.GetTxPoolContentResponse> getTxPoolContent( $pb.ServerContext ctx, $1.GetTxPoolContentRequest request); $pb.GeneratedMessage createRequest($core.String methodName) { switch (methodName) { case 'GetBlock': return $1.GetBlockRequest(); case 'GetBlockHash': return $1.GetBlockHashRequest(); case 'GetBlockHeight': return $1.GetBlockHeightRequest(); case 'GetBlockchainInfo': return $1.GetBlockchainInfoRequest(); case 'GetCommitteeInfo': return $1.GetCommitteeInfoRequest(); case 'GetConsensusInfo': return $1.GetConsensusInfoRequest(); case 'GetAccount': return $1.GetAccountRequest(); case 'GetValidator': return $1.GetValidatorRequest(); case 'GetValidatorByNumber': return $1.GetValidatorByNumberRequest(); case 'GetValidatorAddresses': return $1.GetValidatorAddressesRequest(); case 'GetPublicKey': return $1.GetPublicKeyRequest(); case 'GetTxPoolContent': return $1.GetTxPoolContentRequest(); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $async.Future<$pb.GeneratedMessage> handleCall($pb.ServerContext ctx, $core.String methodName, $pb.GeneratedMessage request) { switch (methodName) { case 'GetBlock': return getBlock(ctx, request as $1.GetBlockRequest); case 'GetBlockHash': return getBlockHash(ctx, request as $1.GetBlockHashRequest); case 'GetBlockHeight': return getBlockHeight(ctx, request as $1.GetBlockHeightRequest); case 'GetBlockchainInfo': return getBlockchainInfo(ctx, request as $1.GetBlockchainInfoRequest); case 'GetCommitteeInfo': return getCommitteeInfo(ctx, request as $1.GetCommitteeInfoRequest); case 'GetConsensusInfo': return getConsensusInfo(ctx, request as $1.GetConsensusInfoRequest); case 'GetAccount': return getAccount(ctx, request as $1.GetAccountRequest); case 'GetValidator': return getValidator(ctx, request as $1.GetValidatorRequest); case 'GetValidatorByNumber': return getValidatorByNumber( ctx, request as $1.GetValidatorByNumberRequest); case 'GetValidatorAddresses': return getValidatorAddresses( ctx, request as $1.GetValidatorAddressesRequest); case 'GetPublicKey': return getPublicKey(ctx, request as $1.GetPublicKeyRequest); case 'GetTxPoolContent': return getTxPoolContent(ctx, request as $1.GetTxPoolContentRequest); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $core.Map<$core.String, $core.dynamic> get $json => BlockchainServiceBase$json; $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> get $messageJson => BlockchainServiceBase$messageJson; } ================================================ FILE: www/grpc/gen/dart/network.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from network.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'network.pbenum.dart'; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; export 'network.pbenum.dart'; /// Request message for retrieving overall network information. class GetNetworkInfoRequest extends $pb.GeneratedMessage { factory GetNetworkInfoRequest() => create(); GetNetworkInfoRequest._(); factory GetNetworkInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetNetworkInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetNetworkInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNetworkInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNetworkInfoRequest copyWith( void Function(GetNetworkInfoRequest) updates) => super.copyWith((message) => updates(message as GetNetworkInfoRequest)) as GetNetworkInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetNetworkInfoRequest create() => GetNetworkInfoRequest._(); @$core.override GetNetworkInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetNetworkInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetNetworkInfoRequest? _defaultInstance; } /// Response message contains information about the overall network. class GetNetworkInfoResponse extends $pb.GeneratedMessage { factory GetNetworkInfoResponse({ $core.String? networkName, $core.int? connectedPeersCount, MetricInfo? metricInfo, }) { final result = create(); if (networkName != null) result.networkName = networkName; if (connectedPeersCount != null) result.connectedPeersCount = connectedPeersCount; if (metricInfo != null) result.metricInfo = metricInfo; return result; } GetNetworkInfoResponse._(); factory GetNetworkInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetNetworkInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetNetworkInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'networkName') ..aI(2, _omitFieldNames ? '' : 'connectedPeersCount', fieldType: $pb.PbFieldType.OU3) ..aOM(4, _omitFieldNames ? '' : 'metricInfo', subBuilder: MetricInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNetworkInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNetworkInfoResponse copyWith( void Function(GetNetworkInfoResponse) updates) => super.copyWith((message) => updates(message as GetNetworkInfoResponse)) as GetNetworkInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetNetworkInfoResponse create() => GetNetworkInfoResponse._(); @$core.override GetNetworkInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetNetworkInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetNetworkInfoResponse? _defaultInstance; /// Name of the P2P network. @$pb.TagNumber(1) $core.String get networkName => $_getSZ(0); @$pb.TagNumber(1) set networkName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasNetworkName() => $_has(0); @$pb.TagNumber(1) void clearNetworkName() => $_clearField(1); /// Number of connected peers. @$pb.TagNumber(2) $core.int get connectedPeersCount => $_getIZ(1); @$pb.TagNumber(2) set connectedPeersCount($core.int value) => $_setUnsignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasConnectedPeersCount() => $_has(1); @$pb.TagNumber(2) void clearConnectedPeersCount() => $_clearField(2); /// Metrics related to node activity. @$pb.TagNumber(4) MetricInfo get metricInfo => $_getN(2); @$pb.TagNumber(4) set metricInfo(MetricInfo value) => $_setField(4, value); @$pb.TagNumber(4) $core.bool hasMetricInfo() => $_has(2); @$pb.TagNumber(4) void clearMetricInfo() => $_clearField(4); @$pb.TagNumber(4) MetricInfo ensureMetricInfo() => $_ensure(2); } /// Request message for listing peers. class ListPeersRequest extends $pb.GeneratedMessage { factory ListPeersRequest({ $core.bool? includeDisconnected, }) { final result = create(); if (includeDisconnected != null) result.includeDisconnected = includeDisconnected; return result; } ListPeersRequest._(); factory ListPeersRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListPeersRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListPeersRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOB(1, _omitFieldNames ? '' : 'includeDisconnected') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListPeersRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListPeersRequest copyWith(void Function(ListPeersRequest) updates) => super.copyWith((message) => updates(message as ListPeersRequest)) as ListPeersRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListPeersRequest create() => ListPeersRequest._(); @$core.override ListPeersRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListPeersRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListPeersRequest? _defaultInstance; /// If true, includes disconnected peers (default: connected peers only). @$pb.TagNumber(1) $core.bool get includeDisconnected => $_getBF(0); @$pb.TagNumber(1) set includeDisconnected($core.bool value) => $_setBool(0, value); @$pb.TagNumber(1) $core.bool hasIncludeDisconnected() => $_has(0); @$pb.TagNumber(1) void clearIncludeDisconnected() => $_clearField(1); } /// Response message for listing peers. class ListPeersResponse extends $pb.GeneratedMessage { factory ListPeersResponse({ $core.Iterable? peers, }) { final result = create(); if (peers != null) result.peers.addAll(peers); return result; } ListPeersResponse._(); factory ListPeersResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListPeersResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListPeersResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..pPM(1, _omitFieldNames ? '' : 'peers', subBuilder: PeerInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListPeersResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListPeersResponse copyWith(void Function(ListPeersResponse) updates) => super.copyWith((message) => updates(message as ListPeersResponse)) as ListPeersResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListPeersResponse create() => ListPeersResponse._(); @$core.override ListPeersResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListPeersResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListPeersResponse? _defaultInstance; /// List of peers. @$pb.TagNumber(1) $pb.PbList get peers => $_getList(0); } /// Request message for retrieving information of the node. class GetNodeInfoRequest extends $pb.GeneratedMessage { factory GetNodeInfoRequest() => create(); GetNodeInfoRequest._(); factory GetNodeInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetNodeInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetNodeInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNodeInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNodeInfoRequest copyWith(void Function(GetNodeInfoRequest) updates) => super.copyWith((message) => updates(message as GetNodeInfoRequest)) as GetNodeInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetNodeInfoRequest create() => GetNodeInfoRequest._(); @$core.override GetNodeInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetNodeInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetNodeInfoRequest? _defaultInstance; } /// Response message contains information about a specific node in the network. class GetNodeInfoResponse extends $pb.GeneratedMessage { factory GetNodeInfoResponse({ $core.String? moniker, $core.String? agent, $core.String? peerId, $fixnum.Int64? startedAt, $core.String? reachability, $core.int? services, $core.String? servicesNames, $core.Iterable<$core.String>? localAddrs, $core.Iterable<$core.String>? protocols, $core.double? clockOffset, ConnectionInfo? connectionInfo, $core.Iterable? zmqPublishers, $fixnum.Int64? currentTime, $core.String? networkName, }) { final result = create(); if (moniker != null) result.moniker = moniker; if (agent != null) result.agent = agent; if (peerId != null) result.peerId = peerId; if (startedAt != null) result.startedAt = startedAt; if (reachability != null) result.reachability = reachability; if (services != null) result.services = services; if (servicesNames != null) result.servicesNames = servicesNames; if (localAddrs != null) result.localAddrs.addAll(localAddrs); if (protocols != null) result.protocols.addAll(protocols); if (clockOffset != null) result.clockOffset = clockOffset; if (connectionInfo != null) result.connectionInfo = connectionInfo; if (zmqPublishers != null) result.zmqPublishers.addAll(zmqPublishers); if (currentTime != null) result.currentTime = currentTime; if (networkName != null) result.networkName = networkName; return result; } GetNodeInfoResponse._(); factory GetNodeInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetNodeInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetNodeInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'moniker') ..aOS(2, _omitFieldNames ? '' : 'agent') ..aOS(3, _omitFieldNames ? '' : 'peerId') ..a<$fixnum.Int64>( 4, _omitFieldNames ? '' : 'startedAt', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..aOS(5, _omitFieldNames ? '' : 'reachability') ..aI(6, _omitFieldNames ? '' : 'services') ..aOS(7, _omitFieldNames ? '' : 'servicesNames') ..pPS(8, _omitFieldNames ? '' : 'localAddrs') ..pPS(9, _omitFieldNames ? '' : 'protocols') ..aD(13, _omitFieldNames ? '' : 'clockOffset') ..aOM(14, _omitFieldNames ? '' : 'connectionInfo', subBuilder: ConnectionInfo.create) ..pPM(15, _omitFieldNames ? '' : 'zmqPublishers', subBuilder: ZMQPublisherInfo.create) ..a<$fixnum.Int64>( 16, _omitFieldNames ? '' : 'currentTime', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..aOS(17, _omitFieldNames ? '' : 'networkName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNodeInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNodeInfoResponse copyWith(void Function(GetNodeInfoResponse) updates) => super.copyWith((message) => updates(message as GetNodeInfoResponse)) as GetNodeInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetNodeInfoResponse create() => GetNodeInfoResponse._(); @$core.override GetNodeInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetNodeInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetNodeInfoResponse? _defaultInstance; /// Moniker or Human-readable name identifying this node in the network. @$pb.TagNumber(1) $core.String get moniker => $_getSZ(0); @$pb.TagNumber(1) set moniker($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasMoniker() => $_has(0); @$pb.TagNumber(1) void clearMoniker() => $_clearField(1); /// Version and agent details of the node. @$pb.TagNumber(2) $core.String get agent => $_getSZ(1); @$pb.TagNumber(2) set agent($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAgent() => $_has(1); @$pb.TagNumber(2) void clearAgent() => $_clearField(2); /// Peer ID of the node. @$pb.TagNumber(3) $core.String get peerId => $_getSZ(2); @$pb.TagNumber(3) set peerId($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasPeerId() => $_has(2); @$pb.TagNumber(3) void clearPeerId() => $_clearField(3); /// Unix timestamp when the node was started (UTC). @$pb.TagNumber(4) $fixnum.Int64 get startedAt => $_getI64(3); @$pb.TagNumber(4) set startedAt($fixnum.Int64 value) => $_setInt64(3, value); @$pb.TagNumber(4) $core.bool hasStartedAt() => $_has(3); @$pb.TagNumber(4) void clearStartedAt() => $_clearField(4); /// Reachability status of the node. @$pb.TagNumber(5) $core.String get reachability => $_getSZ(4); @$pb.TagNumber(5) set reachability($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasReachability() => $_has(4); @$pb.TagNumber(5) void clearReachability() => $_clearField(5); /// Bitfield representing the services provided by the node. @$pb.TagNumber(6) $core.int get services => $_getIZ(5); @$pb.TagNumber(6) set services($core.int value) => $_setSignedInt32(5, value); @$pb.TagNumber(6) $core.bool hasServices() => $_has(5); @$pb.TagNumber(6) void clearServices() => $_clearField(6); /// Names of services provided by the node. @$pb.TagNumber(7) $core.String get servicesNames => $_getSZ(6); @$pb.TagNumber(7) set servicesNames($core.String value) => $_setString(6, value); @$pb.TagNumber(7) $core.bool hasServicesNames() => $_has(6); @$pb.TagNumber(7) void clearServicesNames() => $_clearField(7); /// List of addresses associated with the node. @$pb.TagNumber(8) $pb.PbList<$core.String> get localAddrs => $_getList(7); /// List of protocols supported by the node. @$pb.TagNumber(9) $pb.PbList<$core.String> get protocols => $_getList(8); /// Offset between the node's clock and the network's clock (in seconds). @$pb.TagNumber(13) $core.double get clockOffset => $_getN(9); @$pb.TagNumber(13) set clockOffset($core.double value) => $_setDouble(9, value); @$pb.TagNumber(13) $core.bool hasClockOffset() => $_has(9); @$pb.TagNumber(13) void clearClockOffset() => $_clearField(13); /// Information about the node's connections. @$pb.TagNumber(14) ConnectionInfo get connectionInfo => $_getN(10); @$pb.TagNumber(14) set connectionInfo(ConnectionInfo value) => $_setField(14, value); @$pb.TagNumber(14) $core.bool hasConnectionInfo() => $_has(10); @$pb.TagNumber(14) void clearConnectionInfo() => $_clearField(14); @$pb.TagNumber(14) ConnectionInfo ensureConnectionInfo() => $_ensure(10); /// List of active ZeroMQ publishers. @$pb.TagNumber(15) $pb.PbList get zmqPublishers => $_getList(11); /// Current Unix timestamp of the node (UTC). @$pb.TagNumber(16) $fixnum.Int64 get currentTime => $_getI64(12); @$pb.TagNumber(16) set currentTime($fixnum.Int64 value) => $_setInt64(12, value); @$pb.TagNumber(16) $core.bool hasCurrentTime() => $_has(12); @$pb.TagNumber(16) void clearCurrentTime() => $_clearField(16); /// Name of the P2P network. @$pb.TagNumber(17) $core.String get networkName => $_getSZ(13); @$pb.TagNumber(17) set networkName($core.String value) => $_setString(13, value); @$pb.TagNumber(17) $core.bool hasNetworkName() => $_has(13); @$pb.TagNumber(17) void clearNetworkName() => $_clearField(17); } /// ZMQPublisherInfo contains information about a ZeroMQ publisher. class ZMQPublisherInfo extends $pb.GeneratedMessage { factory ZMQPublisherInfo({ $core.String? topic, $core.String? address, $core.int? hwm, }) { final result = create(); if (topic != null) result.topic = topic; if (address != null) result.address = address; if (hwm != null) result.hwm = hwm; return result; } ZMQPublisherInfo._(); factory ZMQPublisherInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ZMQPublisherInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ZMQPublisherInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'topic') ..aOS(2, _omitFieldNames ? '' : 'address') ..aI(3, _omitFieldNames ? '' : 'hwm') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ZMQPublisherInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ZMQPublisherInfo copyWith(void Function(ZMQPublisherInfo) updates) => super.copyWith((message) => updates(message as ZMQPublisherInfo)) as ZMQPublisherInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ZMQPublisherInfo create() => ZMQPublisherInfo._(); @$core.override ZMQPublisherInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ZMQPublisherInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ZMQPublisherInfo? _defaultInstance; /// The topic associated with the publisher. @$pb.TagNumber(1) $core.String get topic => $_getSZ(0); @$pb.TagNumber(1) set topic($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasTopic() => $_has(0); @$pb.TagNumber(1) void clearTopic() => $_clearField(1); /// The address of the publisher. @$pb.TagNumber(2) $core.String get address => $_getSZ(1); @$pb.TagNumber(2) set address($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAddress() => $_has(1); @$pb.TagNumber(2) void clearAddress() => $_clearField(2); /// The high-water mark (HWM) for the publisher, indicating the /// maximum number of messages to queue before dropping older ones. @$pb.TagNumber(3) $core.int get hwm => $_getIZ(2); @$pb.TagNumber(3) set hwm($core.int value) => $_setSignedInt32(2, value); @$pb.TagNumber(3) $core.bool hasHwm() => $_has(2); @$pb.TagNumber(3) void clearHwm() => $_clearField(3); } /// PeerInfo contains information about a peer in the network. class PeerInfo extends $pb.GeneratedMessage { factory PeerInfo({ $core.int? status, $core.String? moniker, $core.String? agent, $core.String? peerId, $core.Iterable<$core.String>? consensusKeys, $core.Iterable<$core.String>? consensusAddresses, $core.int? services, $core.String? lastBlockHash, $core.int? height, $fixnum.Int64? lastSent, $fixnum.Int64? lastReceived, $core.String? address, Direction? direction, $core.Iterable<$core.String>? protocols, $core.int? totalSessions, $core.int? completedSessions, MetricInfo? metricInfo, $core.bool? outboundHelloSent, }) { final result = create(); if (status != null) result.status = status; if (moniker != null) result.moniker = moniker; if (agent != null) result.agent = agent; if (peerId != null) result.peerId = peerId; if (consensusKeys != null) result.consensusKeys.addAll(consensusKeys); if (consensusAddresses != null) result.consensusAddresses.addAll(consensusAddresses); if (services != null) result.services = services; if (lastBlockHash != null) result.lastBlockHash = lastBlockHash; if (height != null) result.height = height; if (lastSent != null) result.lastSent = lastSent; if (lastReceived != null) result.lastReceived = lastReceived; if (address != null) result.address = address; if (direction != null) result.direction = direction; if (protocols != null) result.protocols.addAll(protocols); if (totalSessions != null) result.totalSessions = totalSessions; if (completedSessions != null) result.completedSessions = completedSessions; if (metricInfo != null) result.metricInfo = metricInfo; if (outboundHelloSent != null) result.outboundHelloSent = outboundHelloSent; return result; } PeerInfo._(); factory PeerInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PeerInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PeerInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'status') ..aOS(2, _omitFieldNames ? '' : 'moniker') ..aOS(3, _omitFieldNames ? '' : 'agent') ..aOS(4, _omitFieldNames ? '' : 'peerId') ..pPS(5, _omitFieldNames ? '' : 'consensusKeys') ..pPS(6, _omitFieldNames ? '' : 'consensusAddresses') ..aI(7, _omitFieldNames ? '' : 'services', fieldType: $pb.PbFieldType.OU3) ..aOS(8, _omitFieldNames ? '' : 'lastBlockHash') ..aI(9, _omitFieldNames ? '' : 'height', fieldType: $pb.PbFieldType.OU3) ..aInt64(10, _omitFieldNames ? '' : 'lastSent') ..aInt64(11, _omitFieldNames ? '' : 'lastReceived') ..aOS(12, _omitFieldNames ? '' : 'address') ..aE(13, _omitFieldNames ? '' : 'direction', enumValues: Direction.values) ..pPS(14, _omitFieldNames ? '' : 'protocols') ..aI(15, _omitFieldNames ? '' : 'totalSessions') ..aI(16, _omitFieldNames ? '' : 'completedSessions') ..aOM(17, _omitFieldNames ? '' : 'metricInfo', subBuilder: MetricInfo.create) ..aOB(18, _omitFieldNames ? '' : 'outboundHelloSent') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PeerInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PeerInfo copyWith(void Function(PeerInfo) updates) => super.copyWith((message) => updates(message as PeerInfo)) as PeerInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PeerInfo create() => PeerInfo._(); @$core.override PeerInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PeerInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PeerInfo? _defaultInstance; /// Current status of the peer (e.g., connected, disconnected). @$pb.TagNumber(1) $core.int get status => $_getIZ(0); @$pb.TagNumber(1) set status($core.int value) => $_setSignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasStatus() => $_has(0); @$pb.TagNumber(1) void clearStatus() => $_clearField(1); /// Moniker or Human-Readable name of the peer. @$pb.TagNumber(2) $core.String get moniker => $_getSZ(1); @$pb.TagNumber(2) set moniker($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasMoniker() => $_has(1); @$pb.TagNumber(2) void clearMoniker() => $_clearField(2); /// Version and agent details of the peer. @$pb.TagNumber(3) $core.String get agent => $_getSZ(2); @$pb.TagNumber(3) set agent($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasAgent() => $_has(2); @$pb.TagNumber(3) void clearAgent() => $_clearField(3); /// Peer ID of the peer in P2P network. @$pb.TagNumber(4) $core.String get peerId => $_getSZ(3); @$pb.TagNumber(4) set peerId($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasPeerId() => $_has(3); @$pb.TagNumber(4) void clearPeerId() => $_clearField(4); /// List of consensus keys used by the peer. @$pb.TagNumber(5) $pb.PbList<$core.String> get consensusKeys => $_getList(4); /// List of consensus addresses used by the peer. @$pb.TagNumber(6) $pb.PbList<$core.String> get consensusAddresses => $_getList(5); /// Bitfield representing the services provided by the peer. @$pb.TagNumber(7) $core.int get services => $_getIZ(6); @$pb.TagNumber(7) set services($core.int value) => $_setUnsignedInt32(6, value); @$pb.TagNumber(7) $core.bool hasServices() => $_has(6); @$pb.TagNumber(7) void clearServices() => $_clearField(7); /// Hash of the last block the peer knows. @$pb.TagNumber(8) $core.String get lastBlockHash => $_getSZ(7); @$pb.TagNumber(8) set lastBlockHash($core.String value) => $_setString(7, value); @$pb.TagNumber(8) $core.bool hasLastBlockHash() => $_has(7); @$pb.TagNumber(8) void clearLastBlockHash() => $_clearField(8); /// Blockchain height of the peer. @$pb.TagNumber(9) $core.int get height => $_getIZ(8); @$pb.TagNumber(9) set height($core.int value) => $_setUnsignedInt32(8, value); @$pb.TagNumber(9) $core.bool hasHeight() => $_has(8); @$pb.TagNumber(9) void clearHeight() => $_clearField(9); /// Unix timestamp of the last bundle sent to the peer (UTC). @$pb.TagNumber(10) $fixnum.Int64 get lastSent => $_getI64(9); @$pb.TagNumber(10) set lastSent($fixnum.Int64 value) => $_setInt64(9, value); @$pb.TagNumber(10) $core.bool hasLastSent() => $_has(9); @$pb.TagNumber(10) void clearLastSent() => $_clearField(10); /// Unix timestamp of the last bundle received from the peer (UTC). @$pb.TagNumber(11) $fixnum.Int64 get lastReceived => $_getI64(10); @$pb.TagNumber(11) set lastReceived($fixnum.Int64 value) => $_setInt64(10, value); @$pb.TagNumber(11) $core.bool hasLastReceived() => $_has(10); @$pb.TagNumber(11) void clearLastReceived() => $_clearField(11); /// Network address of the peer. @$pb.TagNumber(12) $core.String get address => $_getSZ(11); @$pb.TagNumber(12) set address($core.String value) => $_setString(11, value); @$pb.TagNumber(12) $core.bool hasAddress() => $_has(11); @$pb.TagNumber(12) void clearAddress() => $_clearField(12); /// Connection direction (e.g., inbound, outbound). @$pb.TagNumber(13) Direction get direction => $_getN(12); @$pb.TagNumber(13) set direction(Direction value) => $_setField(13, value); @$pb.TagNumber(13) $core.bool hasDirection() => $_has(12); @$pb.TagNumber(13) void clearDirection() => $_clearField(13); /// List of protocols supported by the peer. @$pb.TagNumber(14) $pb.PbList<$core.String> get protocols => $_getList(13); /// Total download sessions with the peer. @$pb.TagNumber(15) $core.int get totalSessions => $_getIZ(14); @$pb.TagNumber(15) set totalSessions($core.int value) => $_setSignedInt32(14, value); @$pb.TagNumber(15) $core.bool hasTotalSessions() => $_has(14); @$pb.TagNumber(15) void clearTotalSessions() => $_clearField(15); /// Completed download sessions with the peer. @$pb.TagNumber(16) $core.int get completedSessions => $_getIZ(15); @$pb.TagNumber(16) set completedSessions($core.int value) => $_setSignedInt32(15, value); @$pb.TagNumber(16) $core.bool hasCompletedSessions() => $_has(15); @$pb.TagNumber(16) void clearCompletedSessions() => $_clearField(16); /// Metrics related to peer activity. @$pb.TagNumber(17) MetricInfo get metricInfo => $_getN(16); @$pb.TagNumber(17) set metricInfo(MetricInfo value) => $_setField(17, value); @$pb.TagNumber(17) $core.bool hasMetricInfo() => $_has(16); @$pb.TagNumber(17) void clearMetricInfo() => $_clearField(17); @$pb.TagNumber(17) MetricInfo ensureMetricInfo() => $_ensure(16); /// Whether the hello message was sent from the outbound connection. @$pb.TagNumber(18) $core.bool get outboundHelloSent => $_getBF(17); @$pb.TagNumber(18) set outboundHelloSent($core.bool value) => $_setBool(17, value); @$pb.TagNumber(18) $core.bool hasOutboundHelloSent() => $_has(17); @$pb.TagNumber(18) void clearOutboundHelloSent() => $_clearField(18); } /// ConnectionInfo contains information about the node's connections. class ConnectionInfo extends $pb.GeneratedMessage { factory ConnectionInfo({ $fixnum.Int64? connections, $fixnum.Int64? inboundConnections, $fixnum.Int64? outboundConnections, }) { final result = create(); if (connections != null) result.connections = connections; if (inboundConnections != null) result.inboundConnections = inboundConnections; if (outboundConnections != null) result.outboundConnections = outboundConnections; return result; } ConnectionInfo._(); factory ConnectionInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ConnectionInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ConnectionInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..a<$fixnum.Int64>( 1, _omitFieldNames ? '' : 'connections', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..a<$fixnum.Int64>( 2, _omitFieldNames ? '' : 'inboundConnections', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..a<$fixnum.Int64>( 3, _omitFieldNames ? '' : 'outboundConnections', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ConnectionInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ConnectionInfo copyWith(void Function(ConnectionInfo) updates) => super.copyWith((message) => updates(message as ConnectionInfo)) as ConnectionInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ConnectionInfo create() => ConnectionInfo._(); @$core.override ConnectionInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ConnectionInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ConnectionInfo? _defaultInstance; /// Total number of connections. @$pb.TagNumber(1) $fixnum.Int64 get connections => $_getI64(0); @$pb.TagNumber(1) set connections($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasConnections() => $_has(0); @$pb.TagNumber(1) void clearConnections() => $_clearField(1); /// Number of inbound connections. @$pb.TagNumber(2) $fixnum.Int64 get inboundConnections => $_getI64(1); @$pb.TagNumber(2) set inboundConnections($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasInboundConnections() => $_has(1); @$pb.TagNumber(2) void clearInboundConnections() => $_clearField(2); /// Number of outbound connections. @$pb.TagNumber(3) $fixnum.Int64 get outboundConnections => $_getI64(2); @$pb.TagNumber(3) set outboundConnections($fixnum.Int64 value) => $_setInt64(2, value); @$pb.TagNumber(3) $core.bool hasOutboundConnections() => $_has(2); @$pb.TagNumber(3) void clearOutboundConnections() => $_clearField(3); } /// MetricInfo contains metrics data regarding network activity. class MetricInfo extends $pb.GeneratedMessage { factory MetricInfo({ CounterInfo? totalInvalid, CounterInfo? totalSent, CounterInfo? totalReceived, $core.Iterable<$core.MapEntry<$core.int, CounterInfo>>? messageSent, $core.Iterable<$core.MapEntry<$core.int, CounterInfo>>? messageReceived, }) { final result = create(); if (totalInvalid != null) result.totalInvalid = totalInvalid; if (totalSent != null) result.totalSent = totalSent; if (totalReceived != null) result.totalReceived = totalReceived; if (messageSent != null) result.messageSent.addEntries(messageSent); if (messageReceived != null) result.messageReceived.addEntries(messageReceived); return result; } MetricInfo._(); factory MetricInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory MetricInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'MetricInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOM(1, _omitFieldNames ? '' : 'totalInvalid', subBuilder: CounterInfo.create) ..aOM(2, _omitFieldNames ? '' : 'totalSent', subBuilder: CounterInfo.create) ..aOM(3, _omitFieldNames ? '' : 'totalReceived', subBuilder: CounterInfo.create) ..m<$core.int, CounterInfo>(4, _omitFieldNames ? '' : 'messageSent', entryClassName: 'MetricInfo.MessageSentEntry', keyFieldType: $pb.PbFieldType.O3, valueFieldType: $pb.PbFieldType.OM, valueCreator: CounterInfo.create, valueDefaultOrMaker: CounterInfo.getDefault, packageName: const $pb.PackageName('pactus')) ..m<$core.int, CounterInfo>(5, _omitFieldNames ? '' : 'messageReceived', entryClassName: 'MetricInfo.MessageReceivedEntry', keyFieldType: $pb.PbFieldType.O3, valueFieldType: $pb.PbFieldType.OM, valueCreator: CounterInfo.create, valueDefaultOrMaker: CounterInfo.getDefault, packageName: const $pb.PackageName('pactus')) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') MetricInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') MetricInfo copyWith(void Function(MetricInfo) updates) => super.copyWith((message) => updates(message as MetricInfo)) as MetricInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static MetricInfo create() => MetricInfo._(); @$core.override MetricInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static MetricInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static MetricInfo? _defaultInstance; /// Total number of invalid bundles. @$pb.TagNumber(1) CounterInfo get totalInvalid => $_getN(0); @$pb.TagNumber(1) set totalInvalid(CounterInfo value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasTotalInvalid() => $_has(0); @$pb.TagNumber(1) void clearTotalInvalid() => $_clearField(1); @$pb.TagNumber(1) CounterInfo ensureTotalInvalid() => $_ensure(0); /// Total number of bundles sent. @$pb.TagNumber(2) CounterInfo get totalSent => $_getN(1); @$pb.TagNumber(2) set totalSent(CounterInfo value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasTotalSent() => $_has(1); @$pb.TagNumber(2) void clearTotalSent() => $_clearField(2); @$pb.TagNumber(2) CounterInfo ensureTotalSent() => $_ensure(1); /// Total number of bundles received. @$pb.TagNumber(3) CounterInfo get totalReceived => $_getN(2); @$pb.TagNumber(3) set totalReceived(CounterInfo value) => $_setField(3, value); @$pb.TagNumber(3) $core.bool hasTotalReceived() => $_has(2); @$pb.TagNumber(3) void clearTotalReceived() => $_clearField(3); @$pb.TagNumber(3) CounterInfo ensureTotalReceived() => $_ensure(2); /// Number of sent bundles categorized by message type. @$pb.TagNumber(4) $pb.PbMap<$core.int, CounterInfo> get messageSent => $_getMap(3); /// Number of received bundles categorized by message type. @$pb.TagNumber(5) $pb.PbMap<$core.int, CounterInfo> get messageReceived => $_getMap(4); } /// CounterInfo holds counter data regarding byte and bundle counts. class CounterInfo extends $pb.GeneratedMessage { factory CounterInfo({ $fixnum.Int64? bytes, $fixnum.Int64? bundles, }) { final result = create(); if (bytes != null) result.bytes = bytes; if (bundles != null) result.bundles = bundles; return result; } CounterInfo._(); factory CounterInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CounterInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CounterInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..a<$fixnum.Int64>(1, _omitFieldNames ? '' : 'bytes', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..a<$fixnum.Int64>(2, _omitFieldNames ? '' : 'bundles', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CounterInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CounterInfo copyWith(void Function(CounterInfo) updates) => super.copyWith((message) => updates(message as CounterInfo)) as CounterInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CounterInfo create() => CounterInfo._(); @$core.override CounterInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CounterInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CounterInfo? _defaultInstance; /// Total number of bytes. @$pb.TagNumber(1) $fixnum.Int64 get bytes => $_getI64(0); @$pb.TagNumber(1) set bytes($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasBytes() => $_has(0); @$pb.TagNumber(1) void clearBytes() => $_clearField(1); /// Total number of bundles. @$pb.TagNumber(2) $fixnum.Int64 get bundles => $_getI64(1); @$pb.TagNumber(2) set bundles($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasBundles() => $_has(1); @$pb.TagNumber(2) void clearBundles() => $_clearField(2); } /// Request message for ping - intentionally empty for measuring round-trip time. class PingRequest extends $pb.GeneratedMessage { factory PingRequest() => create(); PingRequest._(); factory PingRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PingRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PingRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PingRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PingRequest copyWith(void Function(PingRequest) updates) => super.copyWith((message) => updates(message as PingRequest)) as PingRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PingRequest create() => PingRequest._(); @$core.override PingRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PingRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PingRequest? _defaultInstance; } /// Response message for ping - intentionally empty for measuring round-trip time. class PingResponse extends $pb.GeneratedMessage { factory PingResponse() => create(); PingResponse._(); factory PingResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PingResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PingResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PingResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PingResponse copyWith(void Function(PingResponse) updates) => super.copyWith((message) => updates(message as PingResponse)) as PingResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PingResponse create() => PingResponse._(); @$core.override PingResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PingResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PingResponse? _defaultInstance; } /// Network service provides RPCs for retrieving information about the network. class NetworkApi { final $pb.RpcClient _client; NetworkApi(this._client); /// GetNetworkInfo retrieves information about the overall network. $async.Future getNetworkInfo( $pb.ClientContext? ctx, GetNetworkInfoRequest request) => _client.invoke( ctx, 'Network', 'GetNetworkInfo', request, GetNetworkInfoResponse()); /// ListPeers lists all peers in the network. $async.Future listPeers( $pb.ClientContext? ctx, ListPeersRequest request) => _client.invoke( ctx, 'Network', 'ListPeers', request, ListPeersResponse()); /// GetNodeInfo retrieves information about a specific node in the network. $async.Future getNodeInfo( $pb.ClientContext? ctx, GetNodeInfoRequest request) => _client.invoke( ctx, 'Network', 'GetNodeInfo', request, GetNodeInfoResponse()); /// Ping provides a simple connectivity test and latency measurement. $async.Future ping( $pb.ClientContext? ctx, PingRequest request) => _client.invoke( ctx, 'Network', 'Ping', request, PingResponse()); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: www/grpc/gen/dart/network.pbenum.dart ================================================ // This is a generated file - do not edit. // // Generated from network.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; /// Direction represents the connection direction between peers. class Direction extends $pb.ProtobufEnum { /// Unknown direction (default value). static const Direction DIRECTION_UNKNOWN = Direction._(0, _omitEnumNames ? '' : 'DIRECTION_UNKNOWN'); /// Inbound connection - peer connected to us. static const Direction DIRECTION_INBOUND = Direction._(1, _omitEnumNames ? '' : 'DIRECTION_INBOUND'); /// Outbound connection - we connected to peer. static const Direction DIRECTION_OUTBOUND = Direction._(2, _omitEnumNames ? '' : 'DIRECTION_OUTBOUND'); static const $core.List values = [ DIRECTION_UNKNOWN, DIRECTION_INBOUND, DIRECTION_OUTBOUND, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 2); static Direction? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const Direction._(super.value, super.name); } const $core.bool _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names'); ================================================ FILE: www/grpc/gen/dart/network.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from network.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use directionDescriptor instead') const Direction$json = { '1': 'Direction', '2': [ {'1': 'DIRECTION_UNKNOWN', '2': 0}, {'1': 'DIRECTION_INBOUND', '2': 1}, {'1': 'DIRECTION_OUTBOUND', '2': 2}, ], }; /// Descriptor for `Direction`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List directionDescriptor = $convert.base64Decode( 'CglEaXJlY3Rpb24SFQoRRElSRUNUSU9OX1VOS05PV04QABIVChFESVJFQ1RJT05fSU5CT1VORB' 'ABEhYKEkRJUkVDVElPTl9PVVRCT1VORBAC'); @$core.Deprecated('Use getNetworkInfoRequestDescriptor instead') const GetNetworkInfoRequest$json = { '1': 'GetNetworkInfoRequest', }; /// Descriptor for `GetNetworkInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getNetworkInfoRequestDescriptor = $convert.base64Decode('ChVHZXROZXR3b3JrSW5mb1JlcXVlc3Q='); @$core.Deprecated('Use getNetworkInfoResponseDescriptor instead') const GetNetworkInfoResponse$json = { '1': 'GetNetworkInfoResponse', '2': [ {'1': 'network_name', '3': 1, '4': 1, '5': 9, '10': 'networkName'}, { '1': 'connected_peers_count', '3': 2, '4': 1, '5': 13, '10': 'connectedPeersCount' }, { '1': 'metric_info', '3': 4, '4': 1, '5': 11, '6': '.pactus.MetricInfo', '10': 'metricInfo' }, ], }; /// Descriptor for `GetNetworkInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getNetworkInfoResponseDescriptor = $convert.base64Decode( 'ChZHZXROZXR3b3JrSW5mb1Jlc3BvbnNlEiEKDG5ldHdvcmtfbmFtZRgBIAEoCVILbmV0d29ya0' '5hbWUSMgoVY29ubmVjdGVkX3BlZXJzX2NvdW50GAIgASgNUhNjb25uZWN0ZWRQZWVyc0NvdW50' 'EjMKC21ldHJpY19pbmZvGAQgASgLMhIucGFjdHVzLk1ldHJpY0luZm9SCm1ldHJpY0luZm8='); @$core.Deprecated('Use listPeersRequestDescriptor instead') const ListPeersRequest$json = { '1': 'ListPeersRequest', '2': [ { '1': 'include_disconnected', '3': 1, '4': 1, '5': 8, '10': 'includeDisconnected' }, ], }; /// Descriptor for `ListPeersRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listPeersRequestDescriptor = $convert.base64Decode( 'ChBMaXN0UGVlcnNSZXF1ZXN0EjEKFGluY2x1ZGVfZGlzY29ubmVjdGVkGAEgASgIUhNpbmNsdW' 'RlRGlzY29ubmVjdGVk'); @$core.Deprecated('Use listPeersResponseDescriptor instead') const ListPeersResponse$json = { '1': 'ListPeersResponse', '2': [ { '1': 'peers', '3': 1, '4': 3, '5': 11, '6': '.pactus.PeerInfo', '10': 'peers' }, ], }; /// Descriptor for `ListPeersResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listPeersResponseDescriptor = $convert.base64Decode( 'ChFMaXN0UGVlcnNSZXNwb25zZRImCgVwZWVycxgBIAMoCzIQLnBhY3R1cy5QZWVySW5mb1IFcG' 'VlcnM='); @$core.Deprecated('Use getNodeInfoRequestDescriptor instead') const GetNodeInfoRequest$json = { '1': 'GetNodeInfoRequest', }; /// Descriptor for `GetNodeInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getNodeInfoRequestDescriptor = $convert.base64Decode('ChJHZXROb2RlSW5mb1JlcXVlc3Q='); @$core.Deprecated('Use getNodeInfoResponseDescriptor instead') const GetNodeInfoResponse$json = { '1': 'GetNodeInfoResponse', '2': [ {'1': 'moniker', '3': 1, '4': 1, '5': 9, '10': 'moniker'}, {'1': 'agent', '3': 2, '4': 1, '5': 9, '10': 'agent'}, {'1': 'peer_id', '3': 3, '4': 1, '5': 9, '10': 'peerId'}, {'1': 'started_at', '3': 4, '4': 1, '5': 4, '10': 'startedAt'}, {'1': 'reachability', '3': 5, '4': 1, '5': 9, '10': 'reachability'}, {'1': 'services', '3': 6, '4': 1, '5': 5, '10': 'services'}, {'1': 'services_names', '3': 7, '4': 1, '5': 9, '10': 'servicesNames'}, {'1': 'local_addrs', '3': 8, '4': 3, '5': 9, '10': 'localAddrs'}, {'1': 'protocols', '3': 9, '4': 3, '5': 9, '10': 'protocols'}, {'1': 'clock_offset', '3': 13, '4': 1, '5': 1, '10': 'clockOffset'}, { '1': 'connection_info', '3': 14, '4': 1, '5': 11, '6': '.pactus.ConnectionInfo', '10': 'connectionInfo' }, { '1': 'zmq_publishers', '3': 15, '4': 3, '5': 11, '6': '.pactus.ZMQPublisherInfo', '10': 'zmqPublishers' }, {'1': 'current_time', '3': 16, '4': 1, '5': 4, '10': 'currentTime'}, {'1': 'network_name', '3': 17, '4': 1, '5': 9, '10': 'networkName'}, ], }; /// Descriptor for `GetNodeInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getNodeInfoResponseDescriptor = $convert.base64Decode( 'ChNHZXROb2RlSW5mb1Jlc3BvbnNlEhgKB21vbmlrZXIYASABKAlSB21vbmlrZXISFAoFYWdlbn' 'QYAiABKAlSBWFnZW50EhcKB3BlZXJfaWQYAyABKAlSBnBlZXJJZBIdCgpzdGFydGVkX2F0GAQg' 'ASgEUglzdGFydGVkQXQSIgoMcmVhY2hhYmlsaXR5GAUgASgJUgxyZWFjaGFiaWxpdHkSGgoIc2' 'VydmljZXMYBiABKAVSCHNlcnZpY2VzEiUKDnNlcnZpY2VzX25hbWVzGAcgASgJUg1zZXJ2aWNl' 'c05hbWVzEh8KC2xvY2FsX2FkZHJzGAggAygJUgpsb2NhbEFkZHJzEhwKCXByb3RvY29scxgJIA' 'MoCVIJcHJvdG9jb2xzEiEKDGNsb2NrX29mZnNldBgNIAEoAVILY2xvY2tPZmZzZXQSPwoPY29u' 'bmVjdGlvbl9pbmZvGA4gASgLMhYucGFjdHVzLkNvbm5lY3Rpb25JbmZvUg5jb25uZWN0aW9uSW' '5mbxI/Cg56bXFfcHVibGlzaGVycxgPIAMoCzIYLnBhY3R1cy5aTVFQdWJsaXNoZXJJbmZvUg16' 'bXFQdWJsaXNoZXJzEiEKDGN1cnJlbnRfdGltZRgQIAEoBFILY3VycmVudFRpbWUSIQoMbmV0d2' '9ya19uYW1lGBEgASgJUgtuZXR3b3JrTmFtZQ=='); @$core.Deprecated('Use zMQPublisherInfoDescriptor instead') const ZMQPublisherInfo$json = { '1': 'ZMQPublisherInfo', '2': [ {'1': 'topic', '3': 1, '4': 1, '5': 9, '10': 'topic'}, {'1': 'address', '3': 2, '4': 1, '5': 9, '10': 'address'}, {'1': 'hwm', '3': 3, '4': 1, '5': 5, '10': 'hwm'}, ], }; /// Descriptor for `ZMQPublisherInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List zMQPublisherInfoDescriptor = $convert.base64Decode( 'ChBaTVFQdWJsaXNoZXJJbmZvEhQKBXRvcGljGAEgASgJUgV0b3BpYxIYCgdhZGRyZXNzGAIgAS' 'gJUgdhZGRyZXNzEhAKA2h3bRgDIAEoBVIDaHdt'); @$core.Deprecated('Use peerInfoDescriptor instead') const PeerInfo$json = { '1': 'PeerInfo', '2': [ {'1': 'status', '3': 1, '4': 1, '5': 5, '10': 'status'}, {'1': 'moniker', '3': 2, '4': 1, '5': 9, '10': 'moniker'}, {'1': 'agent', '3': 3, '4': 1, '5': 9, '10': 'agent'}, {'1': 'peer_id', '3': 4, '4': 1, '5': 9, '10': 'peerId'}, {'1': 'consensus_keys', '3': 5, '4': 3, '5': 9, '10': 'consensusKeys'}, { '1': 'consensus_addresses', '3': 6, '4': 3, '5': 9, '10': 'consensusAddresses' }, {'1': 'services', '3': 7, '4': 1, '5': 13, '10': 'services'}, {'1': 'last_block_hash', '3': 8, '4': 1, '5': 9, '10': 'lastBlockHash'}, {'1': 'height', '3': 9, '4': 1, '5': 13, '10': 'height'}, {'1': 'last_sent', '3': 10, '4': 1, '5': 3, '10': 'lastSent'}, {'1': 'last_received', '3': 11, '4': 1, '5': 3, '10': 'lastReceived'}, {'1': 'address', '3': 12, '4': 1, '5': 9, '10': 'address'}, { '1': 'direction', '3': 13, '4': 1, '5': 14, '6': '.pactus.Direction', '10': 'direction' }, {'1': 'protocols', '3': 14, '4': 3, '5': 9, '10': 'protocols'}, {'1': 'total_sessions', '3': 15, '4': 1, '5': 5, '10': 'totalSessions'}, { '1': 'completed_sessions', '3': 16, '4': 1, '5': 5, '10': 'completedSessions' }, { '1': 'metric_info', '3': 17, '4': 1, '5': 11, '6': '.pactus.MetricInfo', '10': 'metricInfo' }, { '1': 'outbound_hello_sent', '3': 18, '4': 1, '5': 8, '10': 'outboundHelloSent' }, ], }; /// Descriptor for `PeerInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List peerInfoDescriptor = $convert.base64Decode( 'CghQZWVySW5mbxIWCgZzdGF0dXMYASABKAVSBnN0YXR1cxIYCgdtb25pa2VyGAIgASgJUgdtb2' '5pa2VyEhQKBWFnZW50GAMgASgJUgVhZ2VudBIXCgdwZWVyX2lkGAQgASgJUgZwZWVySWQSJQoO' 'Y29uc2Vuc3VzX2tleXMYBSADKAlSDWNvbnNlbnN1c0tleXMSLwoTY29uc2Vuc3VzX2FkZHJlc3' 'NlcxgGIAMoCVISY29uc2Vuc3VzQWRkcmVzc2VzEhoKCHNlcnZpY2VzGAcgASgNUghzZXJ2aWNl' 'cxImCg9sYXN0X2Jsb2NrX2hhc2gYCCABKAlSDWxhc3RCbG9ja0hhc2gSFgoGaGVpZ2h0GAkgAS' 'gNUgZoZWlnaHQSGwoJbGFzdF9zZW50GAogASgDUghsYXN0U2VudBIjCg1sYXN0X3JlY2VpdmVk' 'GAsgASgDUgxsYXN0UmVjZWl2ZWQSGAoHYWRkcmVzcxgMIAEoCVIHYWRkcmVzcxIvCglkaXJlY3' 'Rpb24YDSABKA4yES5wYWN0dXMuRGlyZWN0aW9uUglkaXJlY3Rpb24SHAoJcHJvdG9jb2xzGA4g' 'AygJUglwcm90b2NvbHMSJQoOdG90YWxfc2Vzc2lvbnMYDyABKAVSDXRvdGFsU2Vzc2lvbnMSLQ' 'oSY29tcGxldGVkX3Nlc3Npb25zGBAgASgFUhFjb21wbGV0ZWRTZXNzaW9ucxIzCgttZXRyaWNf' 'aW5mbxgRIAEoCzISLnBhY3R1cy5NZXRyaWNJbmZvUgptZXRyaWNJbmZvEi4KE291dGJvdW5kX2' 'hlbGxvX3NlbnQYEiABKAhSEW91dGJvdW5kSGVsbG9TZW50'); @$core.Deprecated('Use connectionInfoDescriptor instead') const ConnectionInfo$json = { '1': 'ConnectionInfo', '2': [ {'1': 'connections', '3': 1, '4': 1, '5': 4, '10': 'connections'}, { '1': 'inbound_connections', '3': 2, '4': 1, '5': 4, '10': 'inboundConnections' }, { '1': 'outbound_connections', '3': 3, '4': 1, '5': 4, '10': 'outboundConnections' }, ], }; /// Descriptor for `ConnectionInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List connectionInfoDescriptor = $convert.base64Decode( 'Cg5Db25uZWN0aW9uSW5mbxIgCgtjb25uZWN0aW9ucxgBIAEoBFILY29ubmVjdGlvbnMSLwoTaW' '5ib3VuZF9jb25uZWN0aW9ucxgCIAEoBFISaW5ib3VuZENvbm5lY3Rpb25zEjEKFG91dGJvdW5k' 'X2Nvbm5lY3Rpb25zGAMgASgEUhNvdXRib3VuZENvbm5lY3Rpb25z'); @$core.Deprecated('Use metricInfoDescriptor instead') const MetricInfo$json = { '1': 'MetricInfo', '2': [ { '1': 'total_invalid', '3': 1, '4': 1, '5': 11, '6': '.pactus.CounterInfo', '10': 'totalInvalid' }, { '1': 'total_sent', '3': 2, '4': 1, '5': 11, '6': '.pactus.CounterInfo', '10': 'totalSent' }, { '1': 'total_received', '3': 3, '4': 1, '5': 11, '6': '.pactus.CounterInfo', '10': 'totalReceived' }, { '1': 'message_sent', '3': 4, '4': 3, '5': 11, '6': '.pactus.MetricInfo.MessageSentEntry', '10': 'messageSent' }, { '1': 'message_received', '3': 5, '4': 3, '5': 11, '6': '.pactus.MetricInfo.MessageReceivedEntry', '10': 'messageReceived' }, ], '3': [MetricInfo_MessageSentEntry$json, MetricInfo_MessageReceivedEntry$json], }; @$core.Deprecated('Use metricInfoDescriptor instead') const MetricInfo_MessageSentEntry$json = { '1': 'MessageSentEntry', '2': [ {'1': 'key', '3': 1, '4': 1, '5': 5, '10': 'key'}, { '1': 'value', '3': 2, '4': 1, '5': 11, '6': '.pactus.CounterInfo', '10': 'value' }, ], '7': {'7': true}, }; @$core.Deprecated('Use metricInfoDescriptor instead') const MetricInfo_MessageReceivedEntry$json = { '1': 'MessageReceivedEntry', '2': [ {'1': 'key', '3': 1, '4': 1, '5': 5, '10': 'key'}, { '1': 'value', '3': 2, '4': 1, '5': 11, '6': '.pactus.CounterInfo', '10': 'value' }, ], '7': {'7': true}, }; /// Descriptor for `MetricInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List metricInfoDescriptor = $convert.base64Decode( 'CgpNZXRyaWNJbmZvEjgKDXRvdGFsX2ludmFsaWQYASABKAsyEy5wYWN0dXMuQ291bnRlckluZm' '9SDHRvdGFsSW52YWxpZBIyCgp0b3RhbF9zZW50GAIgASgLMhMucGFjdHVzLkNvdW50ZXJJbmZv' 'Ugl0b3RhbFNlbnQSOgoOdG90YWxfcmVjZWl2ZWQYAyABKAsyEy5wYWN0dXMuQ291bnRlckluZm' '9SDXRvdGFsUmVjZWl2ZWQSRgoMbWVzc2FnZV9zZW50GAQgAygLMiMucGFjdHVzLk1ldHJpY0lu' 'Zm8uTWVzc2FnZVNlbnRFbnRyeVILbWVzc2FnZVNlbnQSUgoQbWVzc2FnZV9yZWNlaXZlZBgFIA' 'MoCzInLnBhY3R1cy5NZXRyaWNJbmZvLk1lc3NhZ2VSZWNlaXZlZEVudHJ5Ug9tZXNzYWdlUmVj' 'ZWl2ZWQaUwoQTWVzc2FnZVNlbnRFbnRyeRIQCgNrZXkYASABKAVSA2tleRIpCgV2YWx1ZRgCIA' 'EoCzITLnBhY3R1cy5Db3VudGVySW5mb1IFdmFsdWU6AjgBGlcKFE1lc3NhZ2VSZWNlaXZlZEVu' 'dHJ5EhAKA2tleRgBIAEoBVIDa2V5EikKBXZhbHVlGAIgASgLMhMucGFjdHVzLkNvdW50ZXJJbm' 'ZvUgV2YWx1ZToCOAE='); @$core.Deprecated('Use counterInfoDescriptor instead') const CounterInfo$json = { '1': 'CounterInfo', '2': [ {'1': 'bytes', '3': 1, '4': 1, '5': 4, '10': 'bytes'}, {'1': 'bundles', '3': 2, '4': 1, '5': 4, '10': 'bundles'}, ], }; /// Descriptor for `CounterInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List counterInfoDescriptor = $convert.base64Decode( 'CgtDb3VudGVySW5mbxIUCgVieXRlcxgBIAEoBFIFYnl0ZXMSGAoHYnVuZGxlcxgCIAEoBFIHYn' 'VuZGxlcw=='); @$core.Deprecated('Use pingRequestDescriptor instead') const PingRequest$json = { '1': 'PingRequest', }; /// Descriptor for `PingRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List pingRequestDescriptor = $convert.base64Decode('CgtQaW5nUmVxdWVzdA=='); @$core.Deprecated('Use pingResponseDescriptor instead') const PingResponse$json = { '1': 'PingResponse', }; /// Descriptor for `PingResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List pingResponseDescriptor = $convert.base64Decode('CgxQaW5nUmVzcG9uc2U='); const $core.Map<$core.String, $core.dynamic> NetworkServiceBase$json = { '1': 'Network', '2': [ { '1': 'GetNetworkInfo', '2': '.pactus.GetNetworkInfoRequest', '3': '.pactus.GetNetworkInfoResponse' }, { '1': 'ListPeers', '2': '.pactus.ListPeersRequest', '3': '.pactus.ListPeersResponse' }, { '1': 'GetNodeInfo', '2': '.pactus.GetNodeInfoRequest', '3': '.pactus.GetNodeInfoResponse' }, {'1': 'Ping', '2': '.pactus.PingRequest', '3': '.pactus.PingResponse'}, ], }; @$core.Deprecated('Use networkServiceDescriptor instead') const $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> NetworkServiceBase$messageJson = { '.pactus.GetNetworkInfoRequest': GetNetworkInfoRequest$json, '.pactus.GetNetworkInfoResponse': GetNetworkInfoResponse$json, '.pactus.MetricInfo': MetricInfo$json, '.pactus.CounterInfo': CounterInfo$json, '.pactus.MetricInfo.MessageSentEntry': MetricInfo_MessageSentEntry$json, '.pactus.MetricInfo.MessageReceivedEntry': MetricInfo_MessageReceivedEntry$json, '.pactus.ListPeersRequest': ListPeersRequest$json, '.pactus.ListPeersResponse': ListPeersResponse$json, '.pactus.PeerInfo': PeerInfo$json, '.pactus.GetNodeInfoRequest': GetNodeInfoRequest$json, '.pactus.GetNodeInfoResponse': GetNodeInfoResponse$json, '.pactus.ConnectionInfo': ConnectionInfo$json, '.pactus.ZMQPublisherInfo': ZMQPublisherInfo$json, '.pactus.PingRequest': PingRequest$json, '.pactus.PingResponse': PingResponse$json, }; /// Descriptor for `Network`. Decode as a `google.protobuf.ServiceDescriptorProto`. final $typed_data.Uint8List networkServiceDescriptor = $convert.base64Decode( 'CgdOZXR3b3JrEk8KDkdldE5ldHdvcmtJbmZvEh0ucGFjdHVzLkdldE5ldHdvcmtJbmZvUmVxdW' 'VzdBoeLnBhY3R1cy5HZXROZXR3b3JrSW5mb1Jlc3BvbnNlEkAKCUxpc3RQZWVycxIYLnBhY3R1' 'cy5MaXN0UGVlcnNSZXF1ZXN0GhkucGFjdHVzLkxpc3RQZWVyc1Jlc3BvbnNlEkYKC0dldE5vZG' 'VJbmZvEhoucGFjdHVzLkdldE5vZGVJbmZvUmVxdWVzdBobLnBhY3R1cy5HZXROb2RlSW5mb1Jl' 'c3BvbnNlEjEKBFBpbmcSEy5wYWN0dXMuUGluZ1JlcXVlc3QaFC5wYWN0dXMuUGluZ1Jlc3Bvbn' 'Nl'); ================================================ FILE: www/grpc/gen/dart/network.pbserver.dart ================================================ // This is a generated file - do not edit. // // Generated from network.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'network.pb.dart' as $0; import 'network.pbjson.dart'; export 'network.pb.dart'; abstract class NetworkServiceBase extends $pb.GeneratedService { $async.Future<$0.GetNetworkInfoResponse> getNetworkInfo( $pb.ServerContext ctx, $0.GetNetworkInfoRequest request); $async.Future<$0.ListPeersResponse> listPeers( $pb.ServerContext ctx, $0.ListPeersRequest request); $async.Future<$0.GetNodeInfoResponse> getNodeInfo( $pb.ServerContext ctx, $0.GetNodeInfoRequest request); $async.Future<$0.PingResponse> ping( $pb.ServerContext ctx, $0.PingRequest request); $pb.GeneratedMessage createRequest($core.String methodName) { switch (methodName) { case 'GetNetworkInfo': return $0.GetNetworkInfoRequest(); case 'ListPeers': return $0.ListPeersRequest(); case 'GetNodeInfo': return $0.GetNodeInfoRequest(); case 'Ping': return $0.PingRequest(); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $async.Future<$pb.GeneratedMessage> handleCall($pb.ServerContext ctx, $core.String methodName, $pb.GeneratedMessage request) { switch (methodName) { case 'GetNetworkInfo': return getNetworkInfo(ctx, request as $0.GetNetworkInfoRequest); case 'ListPeers': return listPeers(ctx, request as $0.ListPeersRequest); case 'GetNodeInfo': return getNodeInfo(ctx, request as $0.GetNodeInfoRequest); case 'Ping': return ping(ctx, request as $0.PingRequest); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $core.Map<$core.String, $core.dynamic> get $json => NetworkServiceBase$json; $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> get $messageJson => NetworkServiceBase$messageJson; } ================================================ FILE: www/grpc/gen/dart/transaction.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from transaction.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'transaction.pbenum.dart'; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; export 'transaction.pbenum.dart'; /// Request message for retrieving transaction details. class GetTransactionRequest extends $pb.GeneratedMessage { factory GetTransactionRequest({ $core.String? id, TransactionVerbosity? verbosity, }) { final result = create(); if (id != null) result.id = id; if (verbosity != null) result.verbosity = verbosity; return result; } GetTransactionRequest._(); factory GetTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'id') ..aE(2, _omitFieldNames ? '' : 'verbosity', enumValues: TransactionVerbosity.values) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTransactionRequest copyWith( void Function(GetTransactionRequest) updates) => super.copyWith((message) => updates(message as GetTransactionRequest)) as GetTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTransactionRequest create() => GetTransactionRequest._(); @$core.override GetTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTransactionRequest? _defaultInstance; /// The unique ID of the transaction to retrieve. @$pb.TagNumber(1) $core.String get id => $_getSZ(0); @$pb.TagNumber(1) set id($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasId() => $_has(0); @$pb.TagNumber(1) void clearId() => $_clearField(1); /// The verbosity level for transaction details. @$pb.TagNumber(2) TransactionVerbosity get verbosity => $_getN(1); @$pb.TagNumber(2) set verbosity(TransactionVerbosity value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasVerbosity() => $_has(1); @$pb.TagNumber(2) void clearVerbosity() => $_clearField(2); } /// Response message contains details of a transaction. class GetTransactionResponse extends $pb.GeneratedMessage { factory GetTransactionResponse({ $core.int? blockHeight, $core.int? blockTime, TransactionInfo? transaction, }) { final result = create(); if (blockHeight != null) result.blockHeight = blockHeight; if (blockTime != null) result.blockTime = blockTime; if (transaction != null) result.transaction = transaction; return result; } GetTransactionResponse._(); factory GetTransactionResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTransactionResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTransactionResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'blockHeight', fieldType: $pb.PbFieldType.OU3) ..aI(2, _omitFieldNames ? '' : 'blockTime', fieldType: $pb.PbFieldType.OU3) ..aOM(3, _omitFieldNames ? '' : 'transaction', subBuilder: TransactionInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTransactionResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTransactionResponse copyWith( void Function(GetTransactionResponse) updates) => super.copyWith((message) => updates(message as GetTransactionResponse)) as GetTransactionResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTransactionResponse create() => GetTransactionResponse._(); @$core.override GetTransactionResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTransactionResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTransactionResponse? _defaultInstance; /// The height of the block containing the transaction. @$pb.TagNumber(1) $core.int get blockHeight => $_getIZ(0); @$pb.TagNumber(1) set blockHeight($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasBlockHeight() => $_has(0); @$pb.TagNumber(1) void clearBlockHeight() => $_clearField(1); /// The UNIX timestamp of the block containing the transaction. @$pb.TagNumber(2) $core.int get blockTime => $_getIZ(1); @$pb.TagNumber(2) set blockTime($core.int value) => $_setUnsignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasBlockTime() => $_has(1); @$pb.TagNumber(2) void clearBlockTime() => $_clearField(2); /// Detailed information about the transaction. @$pb.TagNumber(3) TransactionInfo get transaction => $_getN(2); @$pb.TagNumber(3) set transaction(TransactionInfo value) => $_setField(3, value); @$pb.TagNumber(3) $core.bool hasTransaction() => $_has(2); @$pb.TagNumber(3) void clearTransaction() => $_clearField(3); @$pb.TagNumber(3) TransactionInfo ensureTransaction() => $_ensure(2); } /// Request message for calculating transaction fee. class CalculateFeeRequest extends $pb.GeneratedMessage { factory CalculateFeeRequest({ $fixnum.Int64? amount, PayloadType? payloadType, $core.bool? fixedAmount, }) { final result = create(); if (amount != null) result.amount = amount; if (payloadType != null) result.payloadType = payloadType; if (fixedAmount != null) result.fixedAmount = fixedAmount; return result; } CalculateFeeRequest._(); factory CalculateFeeRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CalculateFeeRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CalculateFeeRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'amount') ..aE(2, _omitFieldNames ? '' : 'payloadType', enumValues: PayloadType.values) ..aOB(3, _omitFieldNames ? '' : 'fixedAmount') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CalculateFeeRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CalculateFeeRequest copyWith(void Function(CalculateFeeRequest) updates) => super.copyWith((message) => updates(message as CalculateFeeRequest)) as CalculateFeeRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CalculateFeeRequest create() => CalculateFeeRequest._(); @$core.override CalculateFeeRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CalculateFeeRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CalculateFeeRequest? _defaultInstance; /// The amount involved in the transaction, specified in NanoPAC. @$pb.TagNumber(1) $fixnum.Int64 get amount => $_getI64(0); @$pb.TagNumber(1) set amount($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasAmount() => $_has(0); @$pb.TagNumber(1) void clearAmount() => $_clearField(1); /// The type of transaction payload. @$pb.TagNumber(2) PayloadType get payloadType => $_getN(1); @$pb.TagNumber(2) set payloadType(PayloadType value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasPayloadType() => $_has(1); @$pb.TagNumber(2) void clearPayloadType() => $_clearField(2); /// Indicates if the amount should be fixed and include the fee. @$pb.TagNumber(3) $core.bool get fixedAmount => $_getBF(2); @$pb.TagNumber(3) set fixedAmount($core.bool value) => $_setBool(2, value); @$pb.TagNumber(3) $core.bool hasFixedAmount() => $_has(2); @$pb.TagNumber(3) void clearFixedAmount() => $_clearField(3); } /// Response message contains the calculated transaction fee. class CalculateFeeResponse extends $pb.GeneratedMessage { factory CalculateFeeResponse({ $fixnum.Int64? amount, $fixnum.Int64? fee, }) { final result = create(); if (amount != null) result.amount = amount; if (fee != null) result.fee = fee; return result; } CalculateFeeResponse._(); factory CalculateFeeResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CalculateFeeResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CalculateFeeResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'amount') ..aInt64(2, _omitFieldNames ? '' : 'fee') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CalculateFeeResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CalculateFeeResponse copyWith(void Function(CalculateFeeResponse) updates) => super.copyWith((message) => updates(message as CalculateFeeResponse)) as CalculateFeeResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CalculateFeeResponse create() => CalculateFeeResponse._(); @$core.override CalculateFeeResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CalculateFeeResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CalculateFeeResponse? _defaultInstance; /// The calculated amount in NanoPAC. @$pb.TagNumber(1) $fixnum.Int64 get amount => $_getI64(0); @$pb.TagNumber(1) set amount($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasAmount() => $_has(0); @$pb.TagNumber(1) void clearAmount() => $_clearField(1); /// The calculated transaction fee in NanoPAC. @$pb.TagNumber(2) $fixnum.Int64 get fee => $_getI64(1); @$pb.TagNumber(2) set fee($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasFee() => $_has(1); @$pb.TagNumber(2) void clearFee() => $_clearField(2); } /// Request message for broadcasting a signed transaction to the network. class BroadcastTransactionRequest extends $pb.GeneratedMessage { factory BroadcastTransactionRequest({ $core.String? signedRawTransaction, }) { final result = create(); if (signedRawTransaction != null) result.signedRawTransaction = signedRawTransaction; return result; } BroadcastTransactionRequest._(); factory BroadcastTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory BroadcastTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'BroadcastTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'signedRawTransaction') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') BroadcastTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') BroadcastTransactionRequest copyWith( void Function(BroadcastTransactionRequest) updates) => super.copyWith( (message) => updates(message as BroadcastTransactionRequest)) as BroadcastTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static BroadcastTransactionRequest create() => BroadcastTransactionRequest._(); @$core.override BroadcastTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static BroadcastTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static BroadcastTransactionRequest? _defaultInstance; /// The signed raw transaction data to be broadcasted. @$pb.TagNumber(1) $core.String get signedRawTransaction => $_getSZ(0); @$pb.TagNumber(1) set signedRawTransaction($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSignedRawTransaction() => $_has(0); @$pb.TagNumber(1) void clearSignedRawTransaction() => $_clearField(1); } /// Response message contains the ID of the broadcasted transaction. class BroadcastTransactionResponse extends $pb.GeneratedMessage { factory BroadcastTransactionResponse({ $core.String? id, }) { final result = create(); if (id != null) result.id = id; return result; } BroadcastTransactionResponse._(); factory BroadcastTransactionResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory BroadcastTransactionResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'BroadcastTransactionResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'id') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') BroadcastTransactionResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') BroadcastTransactionResponse copyWith( void Function(BroadcastTransactionResponse) updates) => super.copyWith( (message) => updates(message as BroadcastTransactionResponse)) as BroadcastTransactionResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static BroadcastTransactionResponse create() => BroadcastTransactionResponse._(); @$core.override BroadcastTransactionResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static BroadcastTransactionResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static BroadcastTransactionResponse? _defaultInstance; /// The unique ID of the broadcasted transaction. @$pb.TagNumber(1) $core.String get id => $_getSZ(0); @$pb.TagNumber(1) set id($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasId() => $_has(0); @$pb.TagNumber(1) void clearId() => $_clearField(1); } /// Request message for retrieving raw details of a transfer transaction. class GetRawTransferTransactionRequest extends $pb.GeneratedMessage { factory GetRawTransferTransactionRequest({ $core.int? lockTime, $core.String? sender, $core.String? receiver, $fixnum.Int64? amount, $fixnum.Int64? fee, $core.String? memo, }) { final result = create(); if (lockTime != null) result.lockTime = lockTime; if (sender != null) result.sender = sender; if (receiver != null) result.receiver = receiver; if (amount != null) result.amount = amount; if (fee != null) result.fee = fee; if (memo != null) result.memo = memo; return result; } GetRawTransferTransactionRequest._(); factory GetRawTransferTransactionRequest.fromBuffer( $core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetRawTransferTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetRawTransferTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'lockTime', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'sender') ..aOS(3, _omitFieldNames ? '' : 'receiver') ..aInt64(4, _omitFieldNames ? '' : 'amount') ..aInt64(5, _omitFieldNames ? '' : 'fee') ..aOS(6, _omitFieldNames ? '' : 'memo') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawTransferTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawTransferTransactionRequest copyWith( void Function(GetRawTransferTransactionRequest) updates) => super.copyWith( (message) => updates(message as GetRawTransferTransactionRequest)) as GetRawTransferTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetRawTransferTransactionRequest create() => GetRawTransferTransactionRequest._(); @$core.override GetRawTransferTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetRawTransferTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor( create); static GetRawTransferTransactionRequest? _defaultInstance; /// The lock time for the transaction. If not set, defaults to the last block height. @$pb.TagNumber(1) $core.int get lockTime => $_getIZ(0); @$pb.TagNumber(1) set lockTime($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasLockTime() => $_has(0); @$pb.TagNumber(1) void clearLockTime() => $_clearField(1); /// The sender's account address. @$pb.TagNumber(2) $core.String get sender => $_getSZ(1); @$pb.TagNumber(2) set sender($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasSender() => $_has(1); @$pb.TagNumber(2) void clearSender() => $_clearField(2); /// The receiver's account address. @$pb.TagNumber(3) $core.String get receiver => $_getSZ(2); @$pb.TagNumber(3) set receiver($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasReceiver() => $_has(2); @$pb.TagNumber(3) void clearReceiver() => $_clearField(3); /// The amount to be transferred, specified in NanoPAC. Must be greater than 0. @$pb.TagNumber(4) $fixnum.Int64 get amount => $_getI64(3); @$pb.TagNumber(4) set amount($fixnum.Int64 value) => $_setInt64(3, value); @$pb.TagNumber(4) $core.bool hasAmount() => $_has(3); @$pb.TagNumber(4) void clearAmount() => $_clearField(4); /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. @$pb.TagNumber(5) $fixnum.Int64 get fee => $_getI64(4); @$pb.TagNumber(5) set fee($fixnum.Int64 value) => $_setInt64(4, value); @$pb.TagNumber(5) $core.bool hasFee() => $_has(4); @$pb.TagNumber(5) void clearFee() => $_clearField(5); /// A memo string for the transaction. @$pb.TagNumber(6) $core.String get memo => $_getSZ(5); @$pb.TagNumber(6) set memo($core.String value) => $_setString(5, value); @$pb.TagNumber(6) $core.bool hasMemo() => $_has(5); @$pb.TagNumber(6) void clearMemo() => $_clearField(6); } /// Request message for retrieving raw details of a bond transaction. class GetRawBondTransactionRequest extends $pb.GeneratedMessage { factory GetRawBondTransactionRequest({ $core.int? lockTime, $core.String? sender, $core.String? receiver, $fixnum.Int64? stake, $core.String? publicKey, $fixnum.Int64? fee, $core.String? memo, $core.String? delegateOwner, $fixnum.Int64? delegateShare, $core.int? delegateExpiry, }) { final result = create(); if (lockTime != null) result.lockTime = lockTime; if (sender != null) result.sender = sender; if (receiver != null) result.receiver = receiver; if (stake != null) result.stake = stake; if (publicKey != null) result.publicKey = publicKey; if (fee != null) result.fee = fee; if (memo != null) result.memo = memo; if (delegateOwner != null) result.delegateOwner = delegateOwner; if (delegateShare != null) result.delegateShare = delegateShare; if (delegateExpiry != null) result.delegateExpiry = delegateExpiry; return result; } GetRawBondTransactionRequest._(); factory GetRawBondTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetRawBondTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetRawBondTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'lockTime', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'sender') ..aOS(3, _omitFieldNames ? '' : 'receiver') ..aInt64(4, _omitFieldNames ? '' : 'stake') ..aOS(5, _omitFieldNames ? '' : 'publicKey') ..aInt64(6, _omitFieldNames ? '' : 'fee') ..aOS(7, _omitFieldNames ? '' : 'memo') ..aOS(8, _omitFieldNames ? '' : 'delegateOwner') ..aInt64(9, _omitFieldNames ? '' : 'delegateShare') ..aI(10, _omitFieldNames ? '' : 'delegateExpiry', fieldType: $pb.PbFieldType.OU3) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawBondTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawBondTransactionRequest copyWith( void Function(GetRawBondTransactionRequest) updates) => super.copyWith( (message) => updates(message as GetRawBondTransactionRequest)) as GetRawBondTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetRawBondTransactionRequest create() => GetRawBondTransactionRequest._(); @$core.override GetRawBondTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetRawBondTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetRawBondTransactionRequest? _defaultInstance; /// The lock time for the transaction. If not set, defaults to the last block height. @$pb.TagNumber(1) $core.int get lockTime => $_getIZ(0); @$pb.TagNumber(1) set lockTime($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasLockTime() => $_has(0); @$pb.TagNumber(1) void clearLockTime() => $_clearField(1); /// The sender's account address. @$pb.TagNumber(2) $core.String get sender => $_getSZ(1); @$pb.TagNumber(2) set sender($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasSender() => $_has(1); @$pb.TagNumber(2) void clearSender() => $_clearField(2); /// The receiver's validator address. @$pb.TagNumber(3) $core.String get receiver => $_getSZ(2); @$pb.TagNumber(3) set receiver($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasReceiver() => $_has(2); @$pb.TagNumber(3) void clearReceiver() => $_clearField(3); /// The stake amount in NanoPAC. Must be greater than 0. @$pb.TagNumber(4) $fixnum.Int64 get stake => $_getI64(3); @$pb.TagNumber(4) set stake($fixnum.Int64 value) => $_setInt64(3, value); @$pb.TagNumber(4) $core.bool hasStake() => $_has(3); @$pb.TagNumber(4) void clearStake() => $_clearField(4); /// The public key of the validator. /// Optional, but required when registering a new validator.; @$pb.TagNumber(5) $core.String get publicKey => $_getSZ(4); @$pb.TagNumber(5) set publicKey($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasPublicKey() => $_has(4); @$pb.TagNumber(5) void clearPublicKey() => $_clearField(5); /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. @$pb.TagNumber(6) $fixnum.Int64 get fee => $_getI64(5); @$pb.TagNumber(6) set fee($fixnum.Int64 value) => $_setInt64(5, value); @$pb.TagNumber(6) $core.bool hasFee() => $_has(5); @$pb.TagNumber(6) void clearFee() => $_clearField(6); /// A memo string for the transaction. @$pb.TagNumber(7) $core.String get memo => $_getSZ(6); @$pb.TagNumber(7) set memo($core.String value) => $_setString(6, value); @$pb.TagNumber(7) $core.bool hasMemo() => $_has(6); @$pb.TagNumber(7) void clearMemo() => $_clearField(7); /// The address of the delegate owner. /// Optional, but required when registering a new validator with delegation.; @$pb.TagNumber(8) $core.String get delegateOwner => $_getSZ(7); @$pb.TagNumber(8) set delegateOwner($core.String value) => $_setString(7, value); @$pb.TagNumber(8) $core.bool hasDelegateOwner() => $_has(7); @$pb.TagNumber(8) void clearDelegateOwner() => $_clearField(8); /// The share percentage for the delegate owner. /// Optional, but required when registering a new validator with delegation.; /// Must be between 0 and 0.7 PAC in nano PAC. @$pb.TagNumber(9) $fixnum.Int64 get delegateShare => $_getI64(8); @$pb.TagNumber(9) set delegateShare($fixnum.Int64 value) => $_setInt64(8, value); @$pb.TagNumber(9) $core.bool hasDelegateShare() => $_has(8); @$pb.TagNumber(9) void clearDelegateShare() => $_clearField(9); /// The expiry height for the delegate relationship. /// Optional, but required when registering a new validator with delegation.; @$pb.TagNumber(10) $core.int get delegateExpiry => $_getIZ(9); @$pb.TagNumber(10) set delegateExpiry($core.int value) => $_setUnsignedInt32(9, value); @$pb.TagNumber(10) $core.bool hasDelegateExpiry() => $_has(9); @$pb.TagNumber(10) void clearDelegateExpiry() => $_clearField(10); } /// Request message for retrieving raw details of an unbond transaction. class GetRawUnbondTransactionRequest extends $pb.GeneratedMessage { factory GetRawUnbondTransactionRequest({ $core.int? lockTime, $core.String? validatorAddress, $core.String? memo, $core.String? delegateOwner, }) { final result = create(); if (lockTime != null) result.lockTime = lockTime; if (validatorAddress != null) result.validatorAddress = validatorAddress; if (memo != null) result.memo = memo; if (delegateOwner != null) result.delegateOwner = delegateOwner; return result; } GetRawUnbondTransactionRequest._(); factory GetRawUnbondTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetRawUnbondTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetRawUnbondTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'lockTime', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'validatorAddress') ..aOS(3, _omitFieldNames ? '' : 'memo') ..aOS(4, _omitFieldNames ? '' : 'delegateOwner') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawUnbondTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawUnbondTransactionRequest copyWith( void Function(GetRawUnbondTransactionRequest) updates) => super.copyWith( (message) => updates(message as GetRawUnbondTransactionRequest)) as GetRawUnbondTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetRawUnbondTransactionRequest create() => GetRawUnbondTransactionRequest._(); @$core.override GetRawUnbondTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetRawUnbondTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetRawUnbondTransactionRequest? _defaultInstance; /// The lock time for the transaction. If not set, defaults to the last block height. @$pb.TagNumber(1) $core.int get lockTime => $_getIZ(0); @$pb.TagNumber(1) set lockTime($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasLockTime() => $_has(0); @$pb.TagNumber(1) void clearLockTime() => $_clearField(1); /// The address of the validator to unbond from. @$pb.TagNumber(2) $core.String get validatorAddress => $_getSZ(1); @$pb.TagNumber(2) set validatorAddress($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasValidatorAddress() => $_has(1); @$pb.TagNumber(2) void clearValidatorAddress() => $_clearField(2); /// A memo string for the transaction. @$pb.TagNumber(3) $core.String get memo => $_getSZ(2); @$pb.TagNumber(3) set memo($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasMemo() => $_has(2); @$pb.TagNumber(3) void clearMemo() => $_clearField(3); /// The address of the delegate owner. /// Optional, but required when the validator is a delegated validator.; @$pb.TagNumber(4) $core.String get delegateOwner => $_getSZ(3); @$pb.TagNumber(4) set delegateOwner($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasDelegateOwner() => $_has(3); @$pb.TagNumber(4) void clearDelegateOwner() => $_clearField(4); } /// Request message for retrieving raw details of a withdraw transaction. class GetRawWithdrawTransactionRequest extends $pb.GeneratedMessage { factory GetRawWithdrawTransactionRequest({ $core.int? lockTime, $core.String? validatorAddress, $core.String? accountAddress, $fixnum.Int64? amount, $fixnum.Int64? fee, $core.String? memo, }) { final result = create(); if (lockTime != null) result.lockTime = lockTime; if (validatorAddress != null) result.validatorAddress = validatorAddress; if (accountAddress != null) result.accountAddress = accountAddress; if (amount != null) result.amount = amount; if (fee != null) result.fee = fee; if (memo != null) result.memo = memo; return result; } GetRawWithdrawTransactionRequest._(); factory GetRawWithdrawTransactionRequest.fromBuffer( $core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetRawWithdrawTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetRawWithdrawTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'lockTime', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'validatorAddress') ..aOS(3, _omitFieldNames ? '' : 'accountAddress') ..aInt64(4, _omitFieldNames ? '' : 'amount') ..aInt64(5, _omitFieldNames ? '' : 'fee') ..aOS(6, _omitFieldNames ? '' : 'memo') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawWithdrawTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawWithdrawTransactionRequest copyWith( void Function(GetRawWithdrawTransactionRequest) updates) => super.copyWith( (message) => updates(message as GetRawWithdrawTransactionRequest)) as GetRawWithdrawTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetRawWithdrawTransactionRequest create() => GetRawWithdrawTransactionRequest._(); @$core.override GetRawWithdrawTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetRawWithdrawTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor( create); static GetRawWithdrawTransactionRequest? _defaultInstance; /// The lock time for the transaction. If not set, defaults to the last block height. @$pb.TagNumber(1) $core.int get lockTime => $_getIZ(0); @$pb.TagNumber(1) set lockTime($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasLockTime() => $_has(0); @$pb.TagNumber(1) void clearLockTime() => $_clearField(1); /// The address of the validator to withdraw from. @$pb.TagNumber(2) $core.String get validatorAddress => $_getSZ(1); @$pb.TagNumber(2) set validatorAddress($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasValidatorAddress() => $_has(1); @$pb.TagNumber(2) void clearValidatorAddress() => $_clearField(2); /// The address of the account to withdraw to. @$pb.TagNumber(3) $core.String get accountAddress => $_getSZ(2); @$pb.TagNumber(3) set accountAddress($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasAccountAddress() => $_has(2); @$pb.TagNumber(3) void clearAccountAddress() => $_clearField(3); /// The withdrawal amount in NanoPAC. Must be greater than 0. @$pb.TagNumber(4) $fixnum.Int64 get amount => $_getI64(3); @$pb.TagNumber(4) set amount($fixnum.Int64 value) => $_setInt64(3, value); @$pb.TagNumber(4) $core.bool hasAmount() => $_has(3); @$pb.TagNumber(4) void clearAmount() => $_clearField(4); /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. @$pb.TagNumber(5) $fixnum.Int64 get fee => $_getI64(4); @$pb.TagNumber(5) set fee($fixnum.Int64 value) => $_setInt64(4, value); @$pb.TagNumber(5) $core.bool hasFee() => $_has(4); @$pb.TagNumber(5) void clearFee() => $_clearField(5); /// A memo string for the transaction. @$pb.TagNumber(6) $core.String get memo => $_getSZ(5); @$pb.TagNumber(6) set memo($core.String value) => $_setString(5, value); @$pb.TagNumber(6) $core.bool hasMemo() => $_has(5); @$pb.TagNumber(6) void clearMemo() => $_clearField(6); } /// Request message for retrieving raw details of a batch transfer transaction. class GetRawBatchTransferTransactionRequest extends $pb.GeneratedMessage { factory GetRawBatchTransferTransactionRequest({ $core.int? lockTime, $core.String? sender, $core.Iterable? recipients, $fixnum.Int64? fee, $core.String? memo, }) { final result = create(); if (lockTime != null) result.lockTime = lockTime; if (sender != null) result.sender = sender; if (recipients != null) result.recipients.addAll(recipients); if (fee != null) result.fee = fee; if (memo != null) result.memo = memo; return result; } GetRawBatchTransferTransactionRequest._(); factory GetRawBatchTransferTransactionRequest.fromBuffer( $core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetRawBatchTransferTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetRawBatchTransferTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'lockTime', fieldType: $pb.PbFieldType.OU3) ..aOS(2, _omitFieldNames ? '' : 'sender') ..pPM(3, _omitFieldNames ? '' : 'recipients', subBuilder: Recipient.create) ..aInt64(4, _omitFieldNames ? '' : 'fee') ..aOS(5, _omitFieldNames ? '' : 'memo') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawBatchTransferTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawBatchTransferTransactionRequest copyWith( void Function(GetRawBatchTransferTransactionRequest) updates) => super.copyWith((message) => updates(message as GetRawBatchTransferTransactionRequest)) as GetRawBatchTransferTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetRawBatchTransferTransactionRequest create() => GetRawBatchTransferTransactionRequest._(); @$core.override GetRawBatchTransferTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetRawBatchTransferTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< GetRawBatchTransferTransactionRequest>(create); static GetRawBatchTransferTransactionRequest? _defaultInstance; /// The lock time for the transaction. If not set, defaults to the last block height. @$pb.TagNumber(1) $core.int get lockTime => $_getIZ(0); @$pb.TagNumber(1) set lockTime($core.int value) => $_setUnsignedInt32(0, value); @$pb.TagNumber(1) $core.bool hasLockTime() => $_has(0); @$pb.TagNumber(1) void clearLockTime() => $_clearField(1); /// The sender's account address. @$pb.TagNumber(2) $core.String get sender => $_getSZ(1); @$pb.TagNumber(2) set sender($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasSender() => $_has(1); @$pb.TagNumber(2) void clearSender() => $_clearField(2); /// The list of recipients with their amounts. Minimum 2 recipients required. @$pb.TagNumber(3) $pb.PbList get recipients => $_getList(2); /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. @$pb.TagNumber(4) $fixnum.Int64 get fee => $_getI64(3); @$pb.TagNumber(4) set fee($fixnum.Int64 value) => $_setInt64(3, value); @$pb.TagNumber(4) $core.bool hasFee() => $_has(3); @$pb.TagNumber(4) void clearFee() => $_clearField(4); /// A memo string for the transaction. @$pb.TagNumber(5) $core.String get memo => $_getSZ(4); @$pb.TagNumber(5) set memo($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasMemo() => $_has(4); @$pb.TagNumber(5) void clearMemo() => $_clearField(5); } /// Response message contains raw transaction data. class GetRawTransactionResponse extends $pb.GeneratedMessage { factory GetRawTransactionResponse({ $core.String? rawTransaction, $core.String? id, }) { final result = create(); if (rawTransaction != null) result.rawTransaction = rawTransaction; if (id != null) result.id = id; return result; } GetRawTransactionResponse._(); factory GetRawTransactionResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetRawTransactionResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetRawTransactionResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'rawTransaction') ..aOS(2, _omitFieldNames ? '' : 'id') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawTransactionResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetRawTransactionResponse copyWith( void Function(GetRawTransactionResponse) updates) => super.copyWith((message) => updates(message as GetRawTransactionResponse)) as GetRawTransactionResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetRawTransactionResponse create() => GetRawTransactionResponse._(); @$core.override GetRawTransactionResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetRawTransactionResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetRawTransactionResponse? _defaultInstance; /// The raw transaction data in hexadecimal format. @$pb.TagNumber(1) $core.String get rawTransaction => $_getSZ(0); @$pb.TagNumber(1) set rawTransaction($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasRawTransaction() => $_has(0); @$pb.TagNumber(1) void clearRawTransaction() => $_clearField(1); /// The unique ID of the transaction. @$pb.TagNumber(2) $core.String get id => $_getSZ(1); @$pb.TagNumber(2) set id($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasId() => $_has(1); @$pb.TagNumber(2) void clearId() => $_clearField(2); } /// Payload for a transfer transaction. class PayloadTransfer extends $pb.GeneratedMessage { factory PayloadTransfer({ $core.String? sender, $core.String? receiver, $fixnum.Int64? amount, }) { final result = create(); if (sender != null) result.sender = sender; if (receiver != null) result.receiver = receiver; if (amount != null) result.amount = amount; return result; } PayloadTransfer._(); factory PayloadTransfer.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PayloadTransfer.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PayloadTransfer', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'sender') ..aOS(2, _omitFieldNames ? '' : 'receiver') ..aInt64(3, _omitFieldNames ? '' : 'amount') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadTransfer clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadTransfer copyWith(void Function(PayloadTransfer) updates) => super.copyWith((message) => updates(message as PayloadTransfer)) as PayloadTransfer; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PayloadTransfer create() => PayloadTransfer._(); @$core.override PayloadTransfer createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PayloadTransfer getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PayloadTransfer? _defaultInstance; /// The sender's address. @$pb.TagNumber(1) $core.String get sender => $_getSZ(0); @$pb.TagNumber(1) set sender($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSender() => $_has(0); @$pb.TagNumber(1) void clearSender() => $_clearField(1); /// The receiver's address. @$pb.TagNumber(2) $core.String get receiver => $_getSZ(1); @$pb.TagNumber(2) set receiver($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasReceiver() => $_has(1); @$pb.TagNumber(2) void clearReceiver() => $_clearField(2); /// The amount to be transferred in NanoPAC. @$pb.TagNumber(3) $fixnum.Int64 get amount => $_getI64(2); @$pb.TagNumber(3) set amount($fixnum.Int64 value) => $_setInt64(2, value); @$pb.TagNumber(3) $core.bool hasAmount() => $_has(2); @$pb.TagNumber(3) void clearAmount() => $_clearField(3); } /// Payload for a bond transaction. class PayloadBond extends $pb.GeneratedMessage { factory PayloadBond({ $core.String? sender, $core.String? receiver, $fixnum.Int64? stake, $core.String? publicKey, $core.bool? isDelegated, $core.String? delegateOwner, $fixnum.Int64? delegateShare, $core.int? delegateExpiry, }) { final result = create(); if (sender != null) result.sender = sender; if (receiver != null) result.receiver = receiver; if (stake != null) result.stake = stake; if (publicKey != null) result.publicKey = publicKey; if (isDelegated != null) result.isDelegated = isDelegated; if (delegateOwner != null) result.delegateOwner = delegateOwner; if (delegateShare != null) result.delegateShare = delegateShare; if (delegateExpiry != null) result.delegateExpiry = delegateExpiry; return result; } PayloadBond._(); factory PayloadBond.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PayloadBond.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PayloadBond', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'sender') ..aOS(2, _omitFieldNames ? '' : 'receiver') ..aInt64(3, _omitFieldNames ? '' : 'stake') ..aOS(4, _omitFieldNames ? '' : 'publicKey') ..aOB(5, _omitFieldNames ? '' : 'isDelegated') ..aOS(6, _omitFieldNames ? '' : 'delegateOwner') ..aInt64(7, _omitFieldNames ? '' : 'delegateShare') ..aI(8, _omitFieldNames ? '' : 'delegateExpiry', fieldType: $pb.PbFieldType.OU3) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadBond clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadBond copyWith(void Function(PayloadBond) updates) => super.copyWith((message) => updates(message as PayloadBond)) as PayloadBond; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PayloadBond create() => PayloadBond._(); @$core.override PayloadBond createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PayloadBond getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PayloadBond? _defaultInstance; /// The sender's address. @$pb.TagNumber(1) $core.String get sender => $_getSZ(0); @$pb.TagNumber(1) set sender($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSender() => $_has(0); @$pb.TagNumber(1) void clearSender() => $_clearField(1); /// The receiver's address. @$pb.TagNumber(2) $core.String get receiver => $_getSZ(1); @$pb.TagNumber(2) set receiver($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasReceiver() => $_has(1); @$pb.TagNumber(2) void clearReceiver() => $_clearField(2); /// The stake amount in NanoPAC. @$pb.TagNumber(3) $fixnum.Int64 get stake => $_getI64(2); @$pb.TagNumber(3) set stake($fixnum.Int64 value) => $_setInt64(2, value); @$pb.TagNumber(3) $core.bool hasStake() => $_has(2); @$pb.TagNumber(3) void clearStake() => $_clearField(3); /// The public key of the validator. @$pb.TagNumber(4) $core.String get publicKey => $_getSZ(3); @$pb.TagNumber(4) set publicKey($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasPublicKey() => $_has(3); @$pb.TagNumber(4) void clearPublicKey() => $_clearField(4); /// Indicates whether the bond transaction is a delegation. @$pb.TagNumber(5) $core.bool get isDelegated => $_getBF(4); @$pb.TagNumber(5) set isDelegated($core.bool value) => $_setBool(4, value); @$pb.TagNumber(5) $core.bool hasIsDelegated() => $_has(4); @$pb.TagNumber(5) void clearIsDelegated() => $_clearField(5); /// The address of the delegate owner. /// Optional, but required when registering a new validator with delegation.; @$pb.TagNumber(6) $core.String get delegateOwner => $_getSZ(5); @$pb.TagNumber(6) set delegateOwner($core.String value) => $_setString(5, value); @$pb.TagNumber(6) $core.bool hasDelegateOwner() => $_has(5); @$pb.TagNumber(6) void clearDelegateOwner() => $_clearField(6); /// The share percentage for the delegate owner. /// Optional, but required when registering a new validator with delegation.; /// Must be between 0 and 0.7 PAC in nano PAC. @$pb.TagNumber(7) $fixnum.Int64 get delegateShare => $_getI64(6); @$pb.TagNumber(7) set delegateShare($fixnum.Int64 value) => $_setInt64(6, value); @$pb.TagNumber(7) $core.bool hasDelegateShare() => $_has(6); @$pb.TagNumber(7) void clearDelegateShare() => $_clearField(7); /// The expiry height for the delegate relationship. /// Optional, but required when registering a new validator with delegation.; @$pb.TagNumber(8) $core.int get delegateExpiry => $_getIZ(7); @$pb.TagNumber(8) set delegateExpiry($core.int value) => $_setUnsignedInt32(7, value); @$pb.TagNumber(8) $core.bool hasDelegateExpiry() => $_has(7); @$pb.TagNumber(8) void clearDelegateExpiry() => $_clearField(8); } /// Payload for a sortition transaction. class PayloadSortition extends $pb.GeneratedMessage { factory PayloadSortition({ $core.String? address, $core.String? proof, }) { final result = create(); if (address != null) result.address = address; if (proof != null) result.proof = proof; return result; } PayloadSortition._(); factory PayloadSortition.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PayloadSortition.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PayloadSortition', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..aOS(2, _omitFieldNames ? '' : 'proof') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadSortition clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadSortition copyWith(void Function(PayloadSortition) updates) => super.copyWith((message) => updates(message as PayloadSortition)) as PayloadSortition; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PayloadSortition create() => PayloadSortition._(); @$core.override PayloadSortition createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PayloadSortition getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PayloadSortition? _defaultInstance; /// The validator address associated with the sortition proof. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); /// The proof for the sortition. @$pb.TagNumber(2) $core.String get proof => $_getSZ(1); @$pb.TagNumber(2) set proof($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasProof() => $_has(1); @$pb.TagNumber(2) void clearProof() => $_clearField(2); } /// Payload for an unbond transaction. class PayloadUnbond extends $pb.GeneratedMessage { factory PayloadUnbond({ $core.String? validator, $core.String? delegateOwner, }) { final result = create(); if (validator != null) result.validator = validator; if (delegateOwner != null) result.delegateOwner = delegateOwner; return result; } PayloadUnbond._(); factory PayloadUnbond.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PayloadUnbond.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PayloadUnbond', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'validator') ..aOS(2, _omitFieldNames ? '' : 'delegateOwner') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadUnbond clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadUnbond copyWith(void Function(PayloadUnbond) updates) => super.copyWith((message) => updates(message as PayloadUnbond)) as PayloadUnbond; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PayloadUnbond create() => PayloadUnbond._(); @$core.override PayloadUnbond createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PayloadUnbond getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PayloadUnbond? _defaultInstance; /// The address of the validator to unbond from. @$pb.TagNumber(1) $core.String get validator => $_getSZ(0); @$pb.TagNumber(1) set validator($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasValidator() => $_has(0); @$pb.TagNumber(1) void clearValidator() => $_clearField(1); /// The address of the delegate owner. /// Optional, but required when the validator is a delegated validator.; @$pb.TagNumber(2) $core.String get delegateOwner => $_getSZ(1); @$pb.TagNumber(2) set delegateOwner($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasDelegateOwner() => $_has(1); @$pb.TagNumber(2) void clearDelegateOwner() => $_clearField(2); } /// Payload for a withdraw transaction. class PayloadWithdraw extends $pb.GeneratedMessage { factory PayloadWithdraw({ $core.String? validatorAddress, $core.String? accountAddress, $fixnum.Int64? amount, }) { final result = create(); if (validatorAddress != null) result.validatorAddress = validatorAddress; if (accountAddress != null) result.accountAddress = accountAddress; if (amount != null) result.amount = amount; return result; } PayloadWithdraw._(); factory PayloadWithdraw.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PayloadWithdraw.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PayloadWithdraw', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'validatorAddress') ..aOS(2, _omitFieldNames ? '' : 'accountAddress') ..aInt64(3, _omitFieldNames ? '' : 'amount') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadWithdraw clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadWithdraw copyWith(void Function(PayloadWithdraw) updates) => super.copyWith((message) => updates(message as PayloadWithdraw)) as PayloadWithdraw; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PayloadWithdraw create() => PayloadWithdraw._(); @$core.override PayloadWithdraw createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PayloadWithdraw getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PayloadWithdraw? _defaultInstance; /// The address of the validator to withdraw from. @$pb.TagNumber(1) $core.String get validatorAddress => $_getSZ(0); @$pb.TagNumber(1) set validatorAddress($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasValidatorAddress() => $_has(0); @$pb.TagNumber(1) void clearValidatorAddress() => $_clearField(1); /// The address of the account to withdraw to. @$pb.TagNumber(2) $core.String get accountAddress => $_getSZ(1); @$pb.TagNumber(2) set accountAddress($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAccountAddress() => $_has(1); @$pb.TagNumber(2) void clearAccountAddress() => $_clearField(2); /// The withdrawal amount in NanoPAC. @$pb.TagNumber(3) $fixnum.Int64 get amount => $_getI64(2); @$pb.TagNumber(3) set amount($fixnum.Int64 value) => $_setInt64(2, value); @$pb.TagNumber(3) $core.bool hasAmount() => $_has(2); @$pb.TagNumber(3) void clearAmount() => $_clearField(3); } /// Payload for a batch transfer transaction. class PayloadBatchTransfer extends $pb.GeneratedMessage { factory PayloadBatchTransfer({ $core.String? sender, $core.Iterable? recipients, }) { final result = create(); if (sender != null) result.sender = sender; if (recipients != null) result.recipients.addAll(recipients); return result; } PayloadBatchTransfer._(); factory PayloadBatchTransfer.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PayloadBatchTransfer.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PayloadBatchTransfer', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'sender') ..pPM(2, _omitFieldNames ? '' : 'recipients', subBuilder: Recipient.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadBatchTransfer clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PayloadBatchTransfer copyWith(void Function(PayloadBatchTransfer) updates) => super.copyWith((message) => updates(message as PayloadBatchTransfer)) as PayloadBatchTransfer; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PayloadBatchTransfer create() => PayloadBatchTransfer._(); @$core.override PayloadBatchTransfer createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PayloadBatchTransfer getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PayloadBatchTransfer? _defaultInstance; /// The sender's address. @$pb.TagNumber(1) $core.String get sender => $_getSZ(0); @$pb.TagNumber(1) set sender($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSender() => $_has(0); @$pb.TagNumber(1) void clearSender() => $_clearField(1); /// The list of recipients with their amounts. @$pb.TagNumber(2) $pb.PbList get recipients => $_getList(1); } /// Recipient is receiver with amount. class Recipient extends $pb.GeneratedMessage { factory Recipient({ $core.String? receiver, $fixnum.Int64? amount, }) { final result = create(); if (receiver != null) result.receiver = receiver; if (amount != null) result.amount = amount; return result; } Recipient._(); factory Recipient.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Recipient.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Recipient', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'receiver') ..aInt64(2, _omitFieldNames ? '' : 'amount') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Recipient clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Recipient copyWith(void Function(Recipient) updates) => super.copyWith((message) => updates(message as Recipient)) as Recipient; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Recipient create() => Recipient._(); @$core.override Recipient createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Recipient getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Recipient? _defaultInstance; /// The receiver's address. @$pb.TagNumber(1) $core.String get receiver => $_getSZ(0); @$pb.TagNumber(1) set receiver($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasReceiver() => $_has(0); @$pb.TagNumber(1) void clearReceiver() => $_clearField(1); /// The amount in NanoPAC. @$pb.TagNumber(2) $fixnum.Int64 get amount => $_getI64(1); @$pb.TagNumber(2) set amount($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasAmount() => $_has(1); @$pb.TagNumber(2) void clearAmount() => $_clearField(2); } enum TransactionInfo_Payload { transfer, bond, sortition, unbond, withdraw, batchTransfer, notSet } /// Information about a transaction. class TransactionInfo extends $pb.GeneratedMessage { factory TransactionInfo({ $core.String? id, $core.String? data, $core.int? version, $core.int? lockTime, $fixnum.Int64? value, $fixnum.Int64? fee, PayloadType? payloadType, $core.String? memo, $core.String? publicKey, $core.String? signature, $core.int? blockHeight, $core.bool? confirmed, $core.int? confirmations, PayloadTransfer? transfer, PayloadBond? bond, PayloadSortition? sortition, PayloadUnbond? unbond, PayloadWithdraw? withdraw, PayloadBatchTransfer? batchTransfer, }) { final result = create(); if (id != null) result.id = id; if (data != null) result.data = data; if (version != null) result.version = version; if (lockTime != null) result.lockTime = lockTime; if (value != null) result.value = value; if (fee != null) result.fee = fee; if (payloadType != null) result.payloadType = payloadType; if (memo != null) result.memo = memo; if (publicKey != null) result.publicKey = publicKey; if (signature != null) result.signature = signature; if (blockHeight != null) result.blockHeight = blockHeight; if (confirmed != null) result.confirmed = confirmed; if (confirmations != null) result.confirmations = confirmations; if (transfer != null) result.transfer = transfer; if (bond != null) result.bond = bond; if (sortition != null) result.sortition = sortition; if (unbond != null) result.unbond = unbond; if (withdraw != null) result.withdraw = withdraw; if (batchTransfer != null) result.batchTransfer = batchTransfer; return result; } TransactionInfo._(); factory TransactionInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory TransactionInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static const $core.Map<$core.int, TransactionInfo_Payload> _TransactionInfo_PayloadByTag = { 30: TransactionInfo_Payload.transfer, 31: TransactionInfo_Payload.bond, 32: TransactionInfo_Payload.sortition, 33: TransactionInfo_Payload.unbond, 34: TransactionInfo_Payload.withdraw, 35: TransactionInfo_Payload.batchTransfer, 0: TransactionInfo_Payload.notSet }; static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'TransactionInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..oo(0, [30, 31, 32, 33, 34, 35]) ..aOS(1, _omitFieldNames ? '' : 'id') ..aOS(2, _omitFieldNames ? '' : 'data') ..aI(3, _omitFieldNames ? '' : 'version') ..aI(4, _omitFieldNames ? '' : 'lockTime', fieldType: $pb.PbFieldType.OU3) ..aInt64(5, _omitFieldNames ? '' : 'value') ..aInt64(6, _omitFieldNames ? '' : 'fee') ..aE(7, _omitFieldNames ? '' : 'payloadType', enumValues: PayloadType.values) ..aOS(8, _omitFieldNames ? '' : 'memo') ..aOS(9, _omitFieldNames ? '' : 'publicKey') ..aOS(10, _omitFieldNames ? '' : 'signature') ..aI(11, _omitFieldNames ? '' : 'blockHeight', fieldType: $pb.PbFieldType.OU3) ..aOB(12, _omitFieldNames ? '' : 'confirmed') ..aI(13, _omitFieldNames ? '' : 'confirmations') ..aOM(30, _omitFieldNames ? '' : 'transfer', subBuilder: PayloadTransfer.create) ..aOM(31, _omitFieldNames ? '' : 'bond', subBuilder: PayloadBond.create) ..aOM(32, _omitFieldNames ? '' : 'sortition', subBuilder: PayloadSortition.create) ..aOM(33, _omitFieldNames ? '' : 'unbond', subBuilder: PayloadUnbond.create) ..aOM(34, _omitFieldNames ? '' : 'withdraw', subBuilder: PayloadWithdraw.create) ..aOM(35, _omitFieldNames ? '' : 'batchTransfer', subBuilder: PayloadBatchTransfer.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') TransactionInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') TransactionInfo copyWith(void Function(TransactionInfo) updates) => super.copyWith((message) => updates(message as TransactionInfo)) as TransactionInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static TransactionInfo create() => TransactionInfo._(); @$core.override TransactionInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static TransactionInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static TransactionInfo? _defaultInstance; @$pb.TagNumber(30) @$pb.TagNumber(31) @$pb.TagNumber(32) @$pb.TagNumber(33) @$pb.TagNumber(34) @$pb.TagNumber(35) TransactionInfo_Payload whichPayload() => _TransactionInfo_PayloadByTag[$_whichOneof(0)]!; @$pb.TagNumber(30) @$pb.TagNumber(31) @$pb.TagNumber(32) @$pb.TagNumber(33) @$pb.TagNumber(34) @$pb.TagNumber(35) void clearPayload() => $_clearField($_whichOneof(0)); /// The unique ID of the transaction. @$pb.TagNumber(1) $core.String get id => $_getSZ(0); @$pb.TagNumber(1) set id($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasId() => $_has(0); @$pb.TagNumber(1) void clearId() => $_clearField(1); /// The raw transaction data in hexadecimal format. @$pb.TagNumber(2) $core.String get data => $_getSZ(1); @$pb.TagNumber(2) set data($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasData() => $_has(1); @$pb.TagNumber(2) void clearData() => $_clearField(2); /// The version of the transaction. @$pb.TagNumber(3) $core.int get version => $_getIZ(2); @$pb.TagNumber(3) set version($core.int value) => $_setSignedInt32(2, value); @$pb.TagNumber(3) $core.bool hasVersion() => $_has(2); @$pb.TagNumber(3) void clearVersion() => $_clearField(3); /// The lock time for the transaction. @$pb.TagNumber(4) $core.int get lockTime => $_getIZ(3); @$pb.TagNumber(4) set lockTime($core.int value) => $_setUnsignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasLockTime() => $_has(3); @$pb.TagNumber(4) void clearLockTime() => $_clearField(4); /// The value of the transaction in NanoPAC. @$pb.TagNumber(5) $fixnum.Int64 get value => $_getI64(4); @$pb.TagNumber(5) set value($fixnum.Int64 value) => $_setInt64(4, value); @$pb.TagNumber(5) $core.bool hasValue() => $_has(4); @$pb.TagNumber(5) void clearValue() => $_clearField(5); /// The fee for the transaction in NanoPAC. @$pb.TagNumber(6) $fixnum.Int64 get fee => $_getI64(5); @$pb.TagNumber(6) set fee($fixnum.Int64 value) => $_setInt64(5, value); @$pb.TagNumber(6) $core.bool hasFee() => $_has(5); @$pb.TagNumber(6) void clearFee() => $_clearField(6); /// The type of transaction payload. @$pb.TagNumber(7) PayloadType get payloadType => $_getN(6); @$pb.TagNumber(7) set payloadType(PayloadType value) => $_setField(7, value); @$pb.TagNumber(7) $core.bool hasPayloadType() => $_has(6); @$pb.TagNumber(7) void clearPayloadType() => $_clearField(7); /// A memo string for the transaction. @$pb.TagNumber(8) $core.String get memo => $_getSZ(7); @$pb.TagNumber(8) set memo($core.String value) => $_setString(7, value); @$pb.TagNumber(8) $core.bool hasMemo() => $_has(7); @$pb.TagNumber(8) void clearMemo() => $_clearField(8); /// The public key associated with the transaction. @$pb.TagNumber(9) $core.String get publicKey => $_getSZ(8); @$pb.TagNumber(9) set publicKey($core.String value) => $_setString(8, value); @$pb.TagNumber(9) $core.bool hasPublicKey() => $_has(8); @$pb.TagNumber(9) void clearPublicKey() => $_clearField(9); /// The signature for the transaction. @$pb.TagNumber(10) $core.String get signature => $_getSZ(9); @$pb.TagNumber(10) set signature($core.String value) => $_setString(9, value); @$pb.TagNumber(10) $core.bool hasSignature() => $_has(9); @$pb.TagNumber(10) void clearSignature() => $_clearField(10); /// The block height containing the transaction. /// A value of zero means the transaction is unconfirmed and may still in the transaction pool. @$pb.TagNumber(11) $core.int get blockHeight => $_getIZ(10); @$pb.TagNumber(11) set blockHeight($core.int value) => $_setUnsignedInt32(10, value); @$pb.TagNumber(11) $core.bool hasBlockHeight() => $_has(10); @$pb.TagNumber(11) void clearBlockHeight() => $_clearField(11); /// Indicates whether the transaction is confirmed. @$pb.TagNumber(12) $core.bool get confirmed => $_getBF(11); @$pb.TagNumber(12) set confirmed($core.bool value) => $_setBool(11, value); @$pb.TagNumber(12) $core.bool hasConfirmed() => $_has(11); @$pb.TagNumber(12) void clearConfirmed() => $_clearField(12); /// The number of blocks that have been added to the chain after this transaction was included in a block. /// A value of zero means the transaction is unconfirmed and may still in the transaction pool. @$pb.TagNumber(13) $core.int get confirmations => $_getIZ(12); @$pb.TagNumber(13) set confirmations($core.int value) => $_setSignedInt32(12, value); @$pb.TagNumber(13) $core.bool hasConfirmations() => $_has(12); @$pb.TagNumber(13) void clearConfirmations() => $_clearField(13); /// Transfer transaction payload. @$pb.TagNumber(30) PayloadTransfer get transfer => $_getN(13); @$pb.TagNumber(30) set transfer(PayloadTransfer value) => $_setField(30, value); @$pb.TagNumber(30) $core.bool hasTransfer() => $_has(13); @$pb.TagNumber(30) void clearTransfer() => $_clearField(30); @$pb.TagNumber(30) PayloadTransfer ensureTransfer() => $_ensure(13); /// Bond transaction payload. @$pb.TagNumber(31) PayloadBond get bond => $_getN(14); @$pb.TagNumber(31) set bond(PayloadBond value) => $_setField(31, value); @$pb.TagNumber(31) $core.bool hasBond() => $_has(14); @$pb.TagNumber(31) void clearBond() => $_clearField(31); @$pb.TagNumber(31) PayloadBond ensureBond() => $_ensure(14); /// Sortition transaction payload. @$pb.TagNumber(32) PayloadSortition get sortition => $_getN(15); @$pb.TagNumber(32) set sortition(PayloadSortition value) => $_setField(32, value); @$pb.TagNumber(32) $core.bool hasSortition() => $_has(15); @$pb.TagNumber(32) void clearSortition() => $_clearField(32); @$pb.TagNumber(32) PayloadSortition ensureSortition() => $_ensure(15); /// Unbond transaction payload. @$pb.TagNumber(33) PayloadUnbond get unbond => $_getN(16); @$pb.TagNumber(33) set unbond(PayloadUnbond value) => $_setField(33, value); @$pb.TagNumber(33) $core.bool hasUnbond() => $_has(16); @$pb.TagNumber(33) void clearUnbond() => $_clearField(33); @$pb.TagNumber(33) PayloadUnbond ensureUnbond() => $_ensure(16); /// Withdraw transaction payload. @$pb.TagNumber(34) PayloadWithdraw get withdraw => $_getN(17); @$pb.TagNumber(34) set withdraw(PayloadWithdraw value) => $_setField(34, value); @$pb.TagNumber(34) $core.bool hasWithdraw() => $_has(17); @$pb.TagNumber(34) void clearWithdraw() => $_clearField(34); @$pb.TagNumber(34) PayloadWithdraw ensureWithdraw() => $_ensure(17); /// Batch Transfer transaction payload. @$pb.TagNumber(35) PayloadBatchTransfer get batchTransfer => $_getN(18); @$pb.TagNumber(35) set batchTransfer(PayloadBatchTransfer value) => $_setField(35, value); @$pb.TagNumber(35) $core.bool hasBatchTransfer() => $_has(18); @$pb.TagNumber(35) void clearBatchTransfer() => $_clearField(35); @$pb.TagNumber(35) PayloadBatchTransfer ensureBatchTransfer() => $_ensure(18); } /// Request message for decoding a raw transaction. class DecodeRawTransactionRequest extends $pb.GeneratedMessage { factory DecodeRawTransactionRequest({ $core.String? rawTransaction, }) { final result = create(); if (rawTransaction != null) result.rawTransaction = rawTransaction; return result; } DecodeRawTransactionRequest._(); factory DecodeRawTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory DecodeRawTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'DecodeRawTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'rawTransaction') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') DecodeRawTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') DecodeRawTransactionRequest copyWith( void Function(DecodeRawTransactionRequest) updates) => super.copyWith( (message) => updates(message as DecodeRawTransactionRequest)) as DecodeRawTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static DecodeRawTransactionRequest create() => DecodeRawTransactionRequest._(); @$core.override DecodeRawTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static DecodeRawTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static DecodeRawTransactionRequest? _defaultInstance; /// The raw transaction data in hexadecimal format. @$pb.TagNumber(1) $core.String get rawTransaction => $_getSZ(0); @$pb.TagNumber(1) set rawTransaction($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasRawTransaction() => $_has(0); @$pb.TagNumber(1) void clearRawTransaction() => $_clearField(1); } /// Response message contains the decoded transaction. class DecodeRawTransactionResponse extends $pb.GeneratedMessage { factory DecodeRawTransactionResponse({ TransactionInfo? transaction, }) { final result = create(); if (transaction != null) result.transaction = transaction; return result; } DecodeRawTransactionResponse._(); factory DecodeRawTransactionResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory DecodeRawTransactionResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'DecodeRawTransactionResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOM(1, _omitFieldNames ? '' : 'transaction', subBuilder: TransactionInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') DecodeRawTransactionResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') DecodeRawTransactionResponse copyWith( void Function(DecodeRawTransactionResponse) updates) => super.copyWith( (message) => updates(message as DecodeRawTransactionResponse)) as DecodeRawTransactionResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static DecodeRawTransactionResponse create() => DecodeRawTransactionResponse._(); @$core.override DecodeRawTransactionResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static DecodeRawTransactionResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static DecodeRawTransactionResponse? _defaultInstance; /// The decoded transaction information. @$pb.TagNumber(1) TransactionInfo get transaction => $_getN(0); @$pb.TagNumber(1) set transaction(TransactionInfo value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasTransaction() => $_has(0); @$pb.TagNumber(1) void clearTransaction() => $_clearField(1); @$pb.TagNumber(1) TransactionInfo ensureTransaction() => $_ensure(0); } /// Request message for checking a transaction. class CheckTransactionRequest extends $pb.GeneratedMessage { factory CheckTransactionRequest({ $core.String? rawTransaction, }) { final result = create(); if (rawTransaction != null) result.rawTransaction = rawTransaction; return result; } CheckTransactionRequest._(); factory CheckTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CheckTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CheckTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'rawTransaction') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CheckTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CheckTransactionRequest copyWith( void Function(CheckTransactionRequest) updates) => super.copyWith((message) => updates(message as CheckTransactionRequest)) as CheckTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CheckTransactionRequest create() => CheckTransactionRequest._(); @$core.override CheckTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CheckTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CheckTransactionRequest? _defaultInstance; /// The raw transaction data to be checked. @$pb.TagNumber(1) $core.String get rawTransaction => $_getSZ(0); @$pb.TagNumber(1) set rawTransaction($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasRawTransaction() => $_has(0); @$pb.TagNumber(1) void clearRawTransaction() => $_clearField(1); } /// Response message contains the result of the transaction check. class CheckTransactionResponse extends $pb.GeneratedMessage { factory CheckTransactionResponse({ $core.bool? isValid, $core.String? errorMessage, }) { final result = create(); if (isValid != null) result.isValid = isValid; if (errorMessage != null) result.errorMessage = errorMessage; return result; } CheckTransactionResponse._(); factory CheckTransactionResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CheckTransactionResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CheckTransactionResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOB(1, _omitFieldNames ? '' : 'isValid') ..aOS(2, _omitFieldNames ? '' : 'errorMessage') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CheckTransactionResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CheckTransactionResponse copyWith( void Function(CheckTransactionResponse) updates) => super.copyWith((message) => updates(message as CheckTransactionResponse)) as CheckTransactionResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CheckTransactionResponse create() => CheckTransactionResponse._(); @$core.override CheckTransactionResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CheckTransactionResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CheckTransactionResponse? _defaultInstance; /// Indicates whether the transaction is valid. @$pb.TagNumber(1) $core.bool get isValid => $_getBF(0); @$pb.TagNumber(1) set isValid($core.bool value) => $_setBool(0, value); @$pb.TagNumber(1) $core.bool hasIsValid() => $_has(0); @$pb.TagNumber(1) void clearIsValid() => $_clearField(1); /// An error message if the transaction is invalid. /// Empty if the transaction is valid. @$pb.TagNumber(2) $core.String get errorMessage => $_getSZ(1); @$pb.TagNumber(2) set errorMessage($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasErrorMessage() => $_has(1); @$pb.TagNumber(2) void clearErrorMessage() => $_clearField(2); } /// Transaction service defines various RPC methods for interacting with transactions. class TransactionApi { final $pb.RpcClient _client; TransactionApi(this._client); /// GetTransaction retrieves transaction details based on the provided request parameters. $async.Future getTransaction( $pb.ClientContext? ctx, GetTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'GetTransaction', request, GetTransactionResponse()); /// CalculateFee calculates the transaction fee based on the specified amount and payload type. $async.Future calculateFee( $pb.ClientContext? ctx, CalculateFeeRequest request) => _client.invoke( ctx, 'Transaction', 'CalculateFee', request, CalculateFeeResponse()); /// BroadcastTransaction broadcasts a signed transaction to the network. $async.Future broadcastTransaction( $pb.ClientContext? ctx, BroadcastTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'BroadcastTransaction', request, BroadcastTransactionResponse()); /// GetRawTransferTransaction retrieves raw details of a transfer transaction. $async.Future getRawTransferTransaction( $pb.ClientContext? ctx, GetRawTransferTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'GetRawTransferTransaction', request, GetRawTransactionResponse()); /// GetRawBondTransaction retrieves raw details of a bond transaction. $async.Future getRawBondTransaction( $pb.ClientContext? ctx, GetRawBondTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'GetRawBondTransaction', request, GetRawTransactionResponse()); /// GetRawUnbondTransaction retrieves raw details of an unbond transaction. $async.Future getRawUnbondTransaction( $pb.ClientContext? ctx, GetRawUnbondTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'GetRawUnbondTransaction', request, GetRawTransactionResponse()); /// GetRawWithdrawTransaction retrieves raw details of a withdraw transaction. $async.Future getRawWithdrawTransaction( $pb.ClientContext? ctx, GetRawWithdrawTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'GetRawWithdrawTransaction', request, GetRawTransactionResponse()); /// GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction. $async.Future getRawBatchTransferTransaction( $pb.ClientContext? ctx, GetRawBatchTransferTransactionRequest request) => _client.invoke( ctx, 'Transaction', 'GetRawBatchTransferTransaction', request, GetRawTransactionResponse()); /// DecodeRawTransaction accepts raw transaction and returns decoded transaction. $async.Future decodeRawTransaction( $pb.ClientContext? ctx, DecodeRawTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'DecodeRawTransaction', request, DecodeRawTransactionResponse()); /// CheckTransaction checks if the transaction is valid and can be included in the blockchain. $async.Future checkTransaction( $pb.ClientContext? ctx, CheckTransactionRequest request) => _client.invoke(ctx, 'Transaction', 'CheckTransaction', request, CheckTransactionResponse()); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: www/grpc/gen/dart/transaction.pbenum.dart ================================================ // This is a generated file - do not edit. // // Generated from transaction.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; /// Enumeration for different types of transaction payloads. class PayloadType extends $pb.ProtobufEnum { /// Unspecified payload type. static const PayloadType PAYLOAD_TYPE_UNSPECIFIED = PayloadType._(0, _omitEnumNames ? '' : 'PAYLOAD_TYPE_UNSPECIFIED'); /// Transfer payload type. static const PayloadType PAYLOAD_TYPE_TRANSFER = PayloadType._(1, _omitEnumNames ? '' : 'PAYLOAD_TYPE_TRANSFER'); /// Bond payload type. static const PayloadType PAYLOAD_TYPE_BOND = PayloadType._(2, _omitEnumNames ? '' : 'PAYLOAD_TYPE_BOND'); /// Sortition payload type. static const PayloadType PAYLOAD_TYPE_SORTITION = PayloadType._(3, _omitEnumNames ? '' : 'PAYLOAD_TYPE_SORTITION'); /// Unbond payload type. static const PayloadType PAYLOAD_TYPE_UNBOND = PayloadType._(4, _omitEnumNames ? '' : 'PAYLOAD_TYPE_UNBOND'); /// Withdraw payload type. static const PayloadType PAYLOAD_TYPE_WITHDRAW = PayloadType._(5, _omitEnumNames ? '' : 'PAYLOAD_TYPE_WITHDRAW'); /// Batch transfer payload type. static const PayloadType PAYLOAD_TYPE_BATCH_TRANSFER = PayloadType._(6, _omitEnumNames ? '' : 'PAYLOAD_TYPE_BATCH_TRANSFER'); static const $core.List values = [ PAYLOAD_TYPE_UNSPECIFIED, PAYLOAD_TYPE_TRANSFER, PAYLOAD_TYPE_BOND, PAYLOAD_TYPE_SORTITION, PAYLOAD_TYPE_UNBOND, PAYLOAD_TYPE_WITHDRAW, PAYLOAD_TYPE_BATCH_TRANSFER, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 6); static PayloadType? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const PayloadType._(super.value, super.name); } /// Enumeration for verbosity levels when requesting transaction details. class TransactionVerbosity extends $pb.ProtobufEnum { /// Request transaction data only. static const TransactionVerbosity TRANSACTION_VERBOSITY_DATA = TransactionVerbosity._( 0, _omitEnumNames ? '' : 'TRANSACTION_VERBOSITY_DATA'); /// Request detailed transaction information. static const TransactionVerbosity TRANSACTION_VERBOSITY_INFO = TransactionVerbosity._( 1, _omitEnumNames ? '' : 'TRANSACTION_VERBOSITY_INFO'); static const $core.List values = [ TRANSACTION_VERBOSITY_DATA, TRANSACTION_VERBOSITY_INFO, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 1); static TransactionVerbosity? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const TransactionVerbosity._(super.value, super.name); } const $core.bool _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names'); ================================================ FILE: www/grpc/gen/dart/transaction.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from transaction.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use payloadTypeDescriptor instead') const PayloadType$json = { '1': 'PayloadType', '2': [ {'1': 'PAYLOAD_TYPE_UNSPECIFIED', '2': 0}, {'1': 'PAYLOAD_TYPE_TRANSFER', '2': 1}, {'1': 'PAYLOAD_TYPE_BOND', '2': 2}, {'1': 'PAYLOAD_TYPE_SORTITION', '2': 3}, {'1': 'PAYLOAD_TYPE_UNBOND', '2': 4}, {'1': 'PAYLOAD_TYPE_WITHDRAW', '2': 5}, {'1': 'PAYLOAD_TYPE_BATCH_TRANSFER', '2': 6}, ], }; /// Descriptor for `PayloadType`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List payloadTypeDescriptor = $convert.base64Decode( 'CgtQYXlsb2FkVHlwZRIcChhQQVlMT0FEX1RZUEVfVU5TUEVDSUZJRUQQABIZChVQQVlMT0FEX1' 'RZUEVfVFJBTlNGRVIQARIVChFQQVlMT0FEX1RZUEVfQk9ORBACEhoKFlBBWUxPQURfVFlQRV9T' 'T1JUSVRJT04QAxIXChNQQVlMT0FEX1RZUEVfVU5CT05EEAQSGQoVUEFZTE9BRF9UWVBFX1dJVE' 'hEUkFXEAUSHwobUEFZTE9BRF9UWVBFX0JBVENIX1RSQU5TRkVSEAY='); @$core.Deprecated('Use transactionVerbosityDescriptor instead') const TransactionVerbosity$json = { '1': 'TransactionVerbosity', '2': [ {'1': 'TRANSACTION_VERBOSITY_DATA', '2': 0}, {'1': 'TRANSACTION_VERBOSITY_INFO', '2': 1}, ], }; /// Descriptor for `TransactionVerbosity`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List transactionVerbosityDescriptor = $convert.base64Decode( 'ChRUcmFuc2FjdGlvblZlcmJvc2l0eRIeChpUUkFOU0FDVElPTl9WRVJCT1NJVFlfREFUQRAAEh' '4KGlRSQU5TQUNUSU9OX1ZFUkJPU0lUWV9JTkZPEAE='); @$core.Deprecated('Use getTransactionRequestDescriptor instead') const GetTransactionRequest$json = { '1': 'GetTransactionRequest', '2': [ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'}, { '1': 'verbosity', '3': 2, '4': 1, '5': 14, '6': '.pactus.TransactionVerbosity', '10': 'verbosity' }, ], }; /// Descriptor for `GetTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTransactionRequestDescriptor = $convert.base64Decode( 'ChVHZXRUcmFuc2FjdGlvblJlcXVlc3QSDgoCaWQYASABKAlSAmlkEjoKCXZlcmJvc2l0eRgCIA' 'EoDjIcLnBhY3R1cy5UcmFuc2FjdGlvblZlcmJvc2l0eVIJdmVyYm9zaXR5'); @$core.Deprecated('Use getTransactionResponseDescriptor instead') const GetTransactionResponse$json = { '1': 'GetTransactionResponse', '2': [ {'1': 'block_height', '3': 1, '4': 1, '5': 13, '10': 'blockHeight'}, {'1': 'block_time', '3': 2, '4': 1, '5': 13, '10': 'blockTime'}, { '1': 'transaction', '3': 3, '4': 1, '5': 11, '6': '.pactus.TransactionInfo', '10': 'transaction' }, ], }; /// Descriptor for `GetTransactionResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTransactionResponseDescriptor = $convert.base64Decode( 'ChZHZXRUcmFuc2FjdGlvblJlc3BvbnNlEiEKDGJsb2NrX2hlaWdodBgBIAEoDVILYmxvY2tIZW' 'lnaHQSHQoKYmxvY2tfdGltZRgCIAEoDVIJYmxvY2tUaW1lEjkKC3RyYW5zYWN0aW9uGAMgASgL' 'MhcucGFjdHVzLlRyYW5zYWN0aW9uSW5mb1ILdHJhbnNhY3Rpb24='); @$core.Deprecated('Use calculateFeeRequestDescriptor instead') const CalculateFeeRequest$json = { '1': 'CalculateFeeRequest', '2': [ {'1': 'amount', '3': 1, '4': 1, '5': 3, '10': 'amount'}, { '1': 'payload_type', '3': 2, '4': 1, '5': 14, '6': '.pactus.PayloadType', '10': 'payloadType' }, {'1': 'fixed_amount', '3': 3, '4': 1, '5': 8, '10': 'fixedAmount'}, ], }; /// Descriptor for `CalculateFeeRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List calculateFeeRequestDescriptor = $convert.base64Decode( 'ChNDYWxjdWxhdGVGZWVSZXF1ZXN0EhYKBmFtb3VudBgBIAEoA1IGYW1vdW50EjYKDHBheWxvYW' 'RfdHlwZRgCIAEoDjITLnBhY3R1cy5QYXlsb2FkVHlwZVILcGF5bG9hZFR5cGUSIQoMZml4ZWRf' 'YW1vdW50GAMgASgIUgtmaXhlZEFtb3VudA=='); @$core.Deprecated('Use calculateFeeResponseDescriptor instead') const CalculateFeeResponse$json = { '1': 'CalculateFeeResponse', '2': [ {'1': 'amount', '3': 1, '4': 1, '5': 3, '10': 'amount'}, {'1': 'fee', '3': 2, '4': 1, '5': 3, '10': 'fee'}, ], }; /// Descriptor for `CalculateFeeResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List calculateFeeResponseDescriptor = $convert.base64Decode( 'ChRDYWxjdWxhdGVGZWVSZXNwb25zZRIWCgZhbW91bnQYASABKANSBmFtb3VudBIQCgNmZWUYAi' 'ABKANSA2ZlZQ=='); @$core.Deprecated('Use broadcastTransactionRequestDescriptor instead') const BroadcastTransactionRequest$json = { '1': 'BroadcastTransactionRequest', '2': [ { '1': 'signed_raw_transaction', '3': 1, '4': 1, '5': 9, '10': 'signedRawTransaction' }, ], }; /// Descriptor for `BroadcastTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List broadcastTransactionRequestDescriptor = $convert.base64Decode( 'ChtCcm9hZGNhc3RUcmFuc2FjdGlvblJlcXVlc3QSNAoWc2lnbmVkX3Jhd190cmFuc2FjdGlvbh' 'gBIAEoCVIUc2lnbmVkUmF3VHJhbnNhY3Rpb24='); @$core.Deprecated('Use broadcastTransactionResponseDescriptor instead') const BroadcastTransactionResponse$json = { '1': 'BroadcastTransactionResponse', '2': [ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'}, ], }; /// Descriptor for `BroadcastTransactionResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List broadcastTransactionResponseDescriptor = $convert.base64Decode( 'ChxCcm9hZGNhc3RUcmFuc2FjdGlvblJlc3BvbnNlEg4KAmlkGAEgASgJUgJpZA=='); @$core.Deprecated('Use getRawTransferTransactionRequestDescriptor instead') const GetRawTransferTransactionRequest$json = { '1': 'GetRawTransferTransactionRequest', '2': [ {'1': 'lock_time', '3': 1, '4': 1, '5': 13, '10': 'lockTime'}, {'1': 'sender', '3': 2, '4': 1, '5': 9, '10': 'sender'}, {'1': 'receiver', '3': 3, '4': 1, '5': 9, '10': 'receiver'}, {'1': 'amount', '3': 4, '4': 1, '5': 3, '10': 'amount'}, {'1': 'fee', '3': 5, '4': 1, '5': 3, '10': 'fee'}, {'1': 'memo', '3': 6, '4': 1, '5': 9, '10': 'memo'}, ], }; /// Descriptor for `GetRawTransferTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getRawTransferTransactionRequestDescriptor = $convert.base64Decode( 'CiBHZXRSYXdUcmFuc2ZlclRyYW5zYWN0aW9uUmVxdWVzdBIbCglsb2NrX3RpbWUYASABKA1SCG' 'xvY2tUaW1lEhYKBnNlbmRlchgCIAEoCVIGc2VuZGVyEhoKCHJlY2VpdmVyGAMgASgJUghyZWNl' 'aXZlchIWCgZhbW91bnQYBCABKANSBmFtb3VudBIQCgNmZWUYBSABKANSA2ZlZRISCgRtZW1vGA' 'YgASgJUgRtZW1v'); @$core.Deprecated('Use getRawBondTransactionRequestDescriptor instead') const GetRawBondTransactionRequest$json = { '1': 'GetRawBondTransactionRequest', '2': [ {'1': 'lock_time', '3': 1, '4': 1, '5': 13, '10': 'lockTime'}, {'1': 'sender', '3': 2, '4': 1, '5': 9, '10': 'sender'}, {'1': 'receiver', '3': 3, '4': 1, '5': 9, '10': 'receiver'}, {'1': 'stake', '3': 4, '4': 1, '5': 3, '10': 'stake'}, {'1': 'public_key', '3': 5, '4': 1, '5': 9, '10': 'publicKey'}, {'1': 'fee', '3': 6, '4': 1, '5': 3, '10': 'fee'}, {'1': 'memo', '3': 7, '4': 1, '5': 9, '10': 'memo'}, {'1': 'delegate_owner', '3': 8, '4': 1, '5': 9, '10': 'delegateOwner'}, {'1': 'delegate_share', '3': 9, '4': 1, '5': 3, '10': 'delegateShare'}, {'1': 'delegate_expiry', '3': 10, '4': 1, '5': 13, '10': 'delegateExpiry'}, ], }; /// Descriptor for `GetRawBondTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getRawBondTransactionRequestDescriptor = $convert.base64Decode( 'ChxHZXRSYXdCb25kVHJhbnNhY3Rpb25SZXF1ZXN0EhsKCWxvY2tfdGltZRgBIAEoDVIIbG9ja1' 'RpbWUSFgoGc2VuZGVyGAIgASgJUgZzZW5kZXISGgoIcmVjZWl2ZXIYAyABKAlSCHJlY2VpdmVy' 'EhQKBXN0YWtlGAQgASgDUgVzdGFrZRIdCgpwdWJsaWNfa2V5GAUgASgJUglwdWJsaWNLZXkSEA' 'oDZmVlGAYgASgDUgNmZWUSEgoEbWVtbxgHIAEoCVIEbWVtbxIlCg5kZWxlZ2F0ZV9vd25lchgI' 'IAEoCVINZGVsZWdhdGVPd25lchIlCg5kZWxlZ2F0ZV9zaGFyZRgJIAEoA1INZGVsZWdhdGVTaG' 'FyZRInCg9kZWxlZ2F0ZV9leHBpcnkYCiABKA1SDmRlbGVnYXRlRXhwaXJ5'); @$core.Deprecated('Use getRawUnbondTransactionRequestDescriptor instead') const GetRawUnbondTransactionRequest$json = { '1': 'GetRawUnbondTransactionRequest', '2': [ {'1': 'lock_time', '3': 1, '4': 1, '5': 13, '10': 'lockTime'}, { '1': 'validator_address', '3': 2, '4': 1, '5': 9, '10': 'validatorAddress' }, {'1': 'memo', '3': 3, '4': 1, '5': 9, '10': 'memo'}, {'1': 'delegate_owner', '3': 4, '4': 1, '5': 9, '10': 'delegateOwner'}, ], }; /// Descriptor for `GetRawUnbondTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getRawUnbondTransactionRequestDescriptor = $convert.base64Decode( 'Ch5HZXRSYXdVbmJvbmRUcmFuc2FjdGlvblJlcXVlc3QSGwoJbG9ja190aW1lGAEgASgNUghsb2' 'NrVGltZRIrChF2YWxpZGF0b3JfYWRkcmVzcxgCIAEoCVIQdmFsaWRhdG9yQWRkcmVzcxISCgRt' 'ZW1vGAMgASgJUgRtZW1vEiUKDmRlbGVnYXRlX293bmVyGAQgASgJUg1kZWxlZ2F0ZU93bmVy'); @$core.Deprecated('Use getRawWithdrawTransactionRequestDescriptor instead') const GetRawWithdrawTransactionRequest$json = { '1': 'GetRawWithdrawTransactionRequest', '2': [ {'1': 'lock_time', '3': 1, '4': 1, '5': 13, '10': 'lockTime'}, { '1': 'validator_address', '3': 2, '4': 1, '5': 9, '10': 'validatorAddress' }, {'1': 'account_address', '3': 3, '4': 1, '5': 9, '10': 'accountAddress'}, {'1': 'amount', '3': 4, '4': 1, '5': 3, '10': 'amount'}, {'1': 'fee', '3': 5, '4': 1, '5': 3, '10': 'fee'}, {'1': 'memo', '3': 6, '4': 1, '5': 9, '10': 'memo'}, ], }; /// Descriptor for `GetRawWithdrawTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getRawWithdrawTransactionRequestDescriptor = $convert.base64Decode( 'CiBHZXRSYXdXaXRoZHJhd1RyYW5zYWN0aW9uUmVxdWVzdBIbCglsb2NrX3RpbWUYASABKA1SCG' 'xvY2tUaW1lEisKEXZhbGlkYXRvcl9hZGRyZXNzGAIgASgJUhB2YWxpZGF0b3JBZGRyZXNzEicK' 'D2FjY291bnRfYWRkcmVzcxgDIAEoCVIOYWNjb3VudEFkZHJlc3MSFgoGYW1vdW50GAQgASgDUg' 'ZhbW91bnQSEAoDZmVlGAUgASgDUgNmZWUSEgoEbWVtbxgGIAEoCVIEbWVtbw=='); @$core.Deprecated('Use getRawBatchTransferTransactionRequestDescriptor instead') const GetRawBatchTransferTransactionRequest$json = { '1': 'GetRawBatchTransferTransactionRequest', '2': [ {'1': 'lock_time', '3': 1, '4': 1, '5': 13, '10': 'lockTime'}, {'1': 'sender', '3': 2, '4': 1, '5': 9, '10': 'sender'}, { '1': 'recipients', '3': 3, '4': 3, '5': 11, '6': '.pactus.Recipient', '10': 'recipients' }, {'1': 'fee', '3': 4, '4': 1, '5': 3, '10': 'fee'}, {'1': 'memo', '3': 5, '4': 1, '5': 9, '10': 'memo'}, ], }; /// Descriptor for `GetRawBatchTransferTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getRawBatchTransferTransactionRequestDescriptor = $convert.base64Decode( 'CiVHZXRSYXdCYXRjaFRyYW5zZmVyVHJhbnNhY3Rpb25SZXF1ZXN0EhsKCWxvY2tfdGltZRgBIA' 'EoDVIIbG9ja1RpbWUSFgoGc2VuZGVyGAIgASgJUgZzZW5kZXISMQoKcmVjaXBpZW50cxgDIAMo' 'CzIRLnBhY3R1cy5SZWNpcGllbnRSCnJlY2lwaWVudHMSEAoDZmVlGAQgASgDUgNmZWUSEgoEbW' 'VtbxgFIAEoCVIEbWVtbw=='); @$core.Deprecated('Use getRawTransactionResponseDescriptor instead') const GetRawTransactionResponse$json = { '1': 'GetRawTransactionResponse', '2': [ {'1': 'raw_transaction', '3': 1, '4': 1, '5': 9, '10': 'rawTransaction'}, {'1': 'id', '3': 2, '4': 1, '5': 9, '10': 'id'}, ], }; /// Descriptor for `GetRawTransactionResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getRawTransactionResponseDescriptor = $convert.base64Decode( 'ChlHZXRSYXdUcmFuc2FjdGlvblJlc3BvbnNlEicKD3Jhd190cmFuc2FjdGlvbhgBIAEoCVIOcm' 'F3VHJhbnNhY3Rpb24SDgoCaWQYAiABKAlSAmlk'); @$core.Deprecated('Use payloadTransferDescriptor instead') const PayloadTransfer$json = { '1': 'PayloadTransfer', '2': [ {'1': 'sender', '3': 1, '4': 1, '5': 9, '10': 'sender'}, {'1': 'receiver', '3': 2, '4': 1, '5': 9, '10': 'receiver'}, {'1': 'amount', '3': 3, '4': 1, '5': 3, '10': 'amount'}, ], }; /// Descriptor for `PayloadTransfer`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List payloadTransferDescriptor = $convert.base64Decode( 'Cg9QYXlsb2FkVHJhbnNmZXISFgoGc2VuZGVyGAEgASgJUgZzZW5kZXISGgoIcmVjZWl2ZXIYAi' 'ABKAlSCHJlY2VpdmVyEhYKBmFtb3VudBgDIAEoA1IGYW1vdW50'); @$core.Deprecated('Use payloadBondDescriptor instead') const PayloadBond$json = { '1': 'PayloadBond', '2': [ {'1': 'sender', '3': 1, '4': 1, '5': 9, '10': 'sender'}, {'1': 'receiver', '3': 2, '4': 1, '5': 9, '10': 'receiver'}, {'1': 'stake', '3': 3, '4': 1, '5': 3, '10': 'stake'}, {'1': 'public_key', '3': 4, '4': 1, '5': 9, '10': 'publicKey'}, {'1': 'is_delegated', '3': 5, '4': 1, '5': 8, '10': 'isDelegated'}, {'1': 'delegate_owner', '3': 6, '4': 1, '5': 9, '10': 'delegateOwner'}, {'1': 'delegate_share', '3': 7, '4': 1, '5': 3, '10': 'delegateShare'}, {'1': 'delegate_expiry', '3': 8, '4': 1, '5': 13, '10': 'delegateExpiry'}, ], }; /// Descriptor for `PayloadBond`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List payloadBondDescriptor = $convert.base64Decode( 'CgtQYXlsb2FkQm9uZBIWCgZzZW5kZXIYASABKAlSBnNlbmRlchIaCghyZWNlaXZlchgCIAEoCV' 'IIcmVjZWl2ZXISFAoFc3Rha2UYAyABKANSBXN0YWtlEh0KCnB1YmxpY19rZXkYBCABKAlSCXB1' 'YmxpY0tleRIhCgxpc19kZWxlZ2F0ZWQYBSABKAhSC2lzRGVsZWdhdGVkEiUKDmRlbGVnYXRlX2' '93bmVyGAYgASgJUg1kZWxlZ2F0ZU93bmVyEiUKDmRlbGVnYXRlX3NoYXJlGAcgASgDUg1kZWxl' 'Z2F0ZVNoYXJlEicKD2RlbGVnYXRlX2V4cGlyeRgIIAEoDVIOZGVsZWdhdGVFeHBpcnk='); @$core.Deprecated('Use payloadSortitionDescriptor instead') const PayloadSortition$json = { '1': 'PayloadSortition', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, {'1': 'proof', '3': 2, '4': 1, '5': 9, '10': 'proof'}, ], }; /// Descriptor for `PayloadSortition`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List payloadSortitionDescriptor = $convert.base64Decode( 'ChBQYXlsb2FkU29ydGl0aW9uEhgKB2FkZHJlc3MYASABKAlSB2FkZHJlc3MSFAoFcHJvb2YYAi' 'ABKAlSBXByb29m'); @$core.Deprecated('Use payloadUnbondDescriptor instead') const PayloadUnbond$json = { '1': 'PayloadUnbond', '2': [ {'1': 'validator', '3': 1, '4': 1, '5': 9, '10': 'validator'}, {'1': 'delegate_owner', '3': 2, '4': 1, '5': 9, '10': 'delegateOwner'}, ], }; /// Descriptor for `PayloadUnbond`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List payloadUnbondDescriptor = $convert.base64Decode( 'Cg1QYXlsb2FkVW5ib25kEhwKCXZhbGlkYXRvchgBIAEoCVIJdmFsaWRhdG9yEiUKDmRlbGVnYX' 'RlX293bmVyGAIgASgJUg1kZWxlZ2F0ZU93bmVy'); @$core.Deprecated('Use payloadWithdrawDescriptor instead') const PayloadWithdraw$json = { '1': 'PayloadWithdraw', '2': [ { '1': 'validator_address', '3': 1, '4': 1, '5': 9, '10': 'validatorAddress' }, {'1': 'account_address', '3': 2, '4': 1, '5': 9, '10': 'accountAddress'}, {'1': 'amount', '3': 3, '4': 1, '5': 3, '10': 'amount'}, ], }; /// Descriptor for `PayloadWithdraw`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List payloadWithdrawDescriptor = $convert.base64Decode( 'Cg9QYXlsb2FkV2l0aGRyYXcSKwoRdmFsaWRhdG9yX2FkZHJlc3MYASABKAlSEHZhbGlkYXRvck' 'FkZHJlc3MSJwoPYWNjb3VudF9hZGRyZXNzGAIgASgJUg5hY2NvdW50QWRkcmVzcxIWCgZhbW91' 'bnQYAyABKANSBmFtb3VudA=='); @$core.Deprecated('Use payloadBatchTransferDescriptor instead') const PayloadBatchTransfer$json = { '1': 'PayloadBatchTransfer', '2': [ {'1': 'sender', '3': 1, '4': 1, '5': 9, '10': 'sender'}, { '1': 'recipients', '3': 2, '4': 3, '5': 11, '6': '.pactus.Recipient', '10': 'recipients' }, ], }; /// Descriptor for `PayloadBatchTransfer`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List payloadBatchTransferDescriptor = $convert.base64Decode( 'ChRQYXlsb2FkQmF0Y2hUcmFuc2ZlchIWCgZzZW5kZXIYASABKAlSBnNlbmRlchIxCgpyZWNpcG' 'llbnRzGAIgAygLMhEucGFjdHVzLlJlY2lwaWVudFIKcmVjaXBpZW50cw=='); @$core.Deprecated('Use recipientDescriptor instead') const Recipient$json = { '1': 'Recipient', '2': [ {'1': 'receiver', '3': 1, '4': 1, '5': 9, '10': 'receiver'}, {'1': 'amount', '3': 2, '4': 1, '5': 3, '10': 'amount'}, ], }; /// Descriptor for `Recipient`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List recipientDescriptor = $convert.base64Decode( 'CglSZWNpcGllbnQSGgoIcmVjZWl2ZXIYASABKAlSCHJlY2VpdmVyEhYKBmFtb3VudBgCIAEoA1' 'IGYW1vdW50'); @$core.Deprecated('Use transactionInfoDescriptor instead') const TransactionInfo$json = { '1': 'TransactionInfo', '2': [ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'}, {'1': 'data', '3': 2, '4': 1, '5': 9, '10': 'data'}, {'1': 'version', '3': 3, '4': 1, '5': 5, '10': 'version'}, {'1': 'lock_time', '3': 4, '4': 1, '5': 13, '10': 'lockTime'}, {'1': 'value', '3': 5, '4': 1, '5': 3, '10': 'value'}, {'1': 'fee', '3': 6, '4': 1, '5': 3, '10': 'fee'}, { '1': 'payload_type', '3': 7, '4': 1, '5': 14, '6': '.pactus.PayloadType', '10': 'payloadType' }, { '1': 'transfer', '3': 30, '4': 1, '5': 11, '6': '.pactus.PayloadTransfer', '9': 0, '10': 'transfer' }, { '1': 'bond', '3': 31, '4': 1, '5': 11, '6': '.pactus.PayloadBond', '9': 0, '10': 'bond' }, { '1': 'sortition', '3': 32, '4': 1, '5': 11, '6': '.pactus.PayloadSortition', '9': 0, '10': 'sortition' }, { '1': 'unbond', '3': 33, '4': 1, '5': 11, '6': '.pactus.PayloadUnbond', '9': 0, '10': 'unbond' }, { '1': 'withdraw', '3': 34, '4': 1, '5': 11, '6': '.pactus.PayloadWithdraw', '9': 0, '10': 'withdraw' }, { '1': 'batch_transfer', '3': 35, '4': 1, '5': 11, '6': '.pactus.PayloadBatchTransfer', '9': 0, '10': 'batchTransfer' }, {'1': 'memo', '3': 8, '4': 1, '5': 9, '10': 'memo'}, {'1': 'public_key', '3': 9, '4': 1, '5': 9, '10': 'publicKey'}, {'1': 'signature', '3': 10, '4': 1, '5': 9, '10': 'signature'}, {'1': 'block_height', '3': 11, '4': 1, '5': 13, '10': 'blockHeight'}, {'1': 'confirmed', '3': 12, '4': 1, '5': 8, '10': 'confirmed'}, {'1': 'confirmations', '3': 13, '4': 1, '5': 5, '10': 'confirmations'}, ], '8': [ {'1': 'payload'}, ], }; /// Descriptor for `TransactionInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List transactionInfoDescriptor = $convert.base64Decode( 'Cg9UcmFuc2FjdGlvbkluZm8SDgoCaWQYASABKAlSAmlkEhIKBGRhdGEYAiABKAlSBGRhdGESGA' 'oHdmVyc2lvbhgDIAEoBVIHdmVyc2lvbhIbCglsb2NrX3RpbWUYBCABKA1SCGxvY2tUaW1lEhQK' 'BXZhbHVlGAUgASgDUgV2YWx1ZRIQCgNmZWUYBiABKANSA2ZlZRI2CgxwYXlsb2FkX3R5cGUYBy' 'ABKA4yEy5wYWN0dXMuUGF5bG9hZFR5cGVSC3BheWxvYWRUeXBlEjUKCHRyYW5zZmVyGB4gASgL' 'MhcucGFjdHVzLlBheWxvYWRUcmFuc2ZlckgAUgh0cmFuc2ZlchIpCgRib25kGB8gASgLMhMucG' 'FjdHVzLlBheWxvYWRCb25kSABSBGJvbmQSOAoJc29ydGl0aW9uGCAgASgLMhgucGFjdHVzLlBh' 'eWxvYWRTb3J0aXRpb25IAFIJc29ydGl0aW9uEi8KBnVuYm9uZBghIAEoCzIVLnBhY3R1cy5QYX' 'lsb2FkVW5ib25kSABSBnVuYm9uZBI1Cgh3aXRoZHJhdxgiIAEoCzIXLnBhY3R1cy5QYXlsb2Fk' 'V2l0aGRyYXdIAFIId2l0aGRyYXcSRQoOYmF0Y2hfdHJhbnNmZXIYIyABKAsyHC5wYWN0dXMuUG' 'F5bG9hZEJhdGNoVHJhbnNmZXJIAFINYmF0Y2hUcmFuc2ZlchISCgRtZW1vGAggASgJUgRtZW1v' 'Eh0KCnB1YmxpY19rZXkYCSABKAlSCXB1YmxpY0tleRIcCglzaWduYXR1cmUYCiABKAlSCXNpZ2' '5hdHVyZRIhCgxibG9ja19oZWlnaHQYCyABKA1SC2Jsb2NrSGVpZ2h0EhwKCWNvbmZpcm1lZBgM' 'IAEoCFIJY29uZmlybWVkEiQKDWNvbmZpcm1hdGlvbnMYDSABKAVSDWNvbmZpcm1hdGlvbnNCCQ' 'oHcGF5bG9hZA=='); @$core.Deprecated('Use decodeRawTransactionRequestDescriptor instead') const DecodeRawTransactionRequest$json = { '1': 'DecodeRawTransactionRequest', '2': [ {'1': 'raw_transaction', '3': 1, '4': 1, '5': 9, '10': 'rawTransaction'}, ], }; /// Descriptor for `DecodeRawTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List decodeRawTransactionRequestDescriptor = $convert.base64Decode( 'ChtEZWNvZGVSYXdUcmFuc2FjdGlvblJlcXVlc3QSJwoPcmF3X3RyYW5zYWN0aW9uGAEgASgJUg' '5yYXdUcmFuc2FjdGlvbg=='); @$core.Deprecated('Use decodeRawTransactionResponseDescriptor instead') const DecodeRawTransactionResponse$json = { '1': 'DecodeRawTransactionResponse', '2': [ { '1': 'transaction', '3': 1, '4': 1, '5': 11, '6': '.pactus.TransactionInfo', '10': 'transaction' }, ], }; /// Descriptor for `DecodeRawTransactionResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List decodeRawTransactionResponseDescriptor = $convert.base64Decode( 'ChxEZWNvZGVSYXdUcmFuc2FjdGlvblJlc3BvbnNlEjkKC3RyYW5zYWN0aW9uGAEgASgLMhcucG' 'FjdHVzLlRyYW5zYWN0aW9uSW5mb1ILdHJhbnNhY3Rpb24='); @$core.Deprecated('Use checkTransactionRequestDescriptor instead') const CheckTransactionRequest$json = { '1': 'CheckTransactionRequest', '2': [ {'1': 'raw_transaction', '3': 1, '4': 1, '5': 9, '10': 'rawTransaction'}, ], }; /// Descriptor for `CheckTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List checkTransactionRequestDescriptor = $convert.base64Decode( 'ChdDaGVja1RyYW5zYWN0aW9uUmVxdWVzdBInCg9yYXdfdHJhbnNhY3Rpb24YASABKAlSDnJhd1' 'RyYW5zYWN0aW9u'); @$core.Deprecated('Use checkTransactionResponseDescriptor instead') const CheckTransactionResponse$json = { '1': 'CheckTransactionResponse', '2': [ {'1': 'is_valid', '3': 1, '4': 1, '5': 8, '10': 'isValid'}, {'1': 'error_message', '3': 2, '4': 1, '5': 9, '10': 'errorMessage'}, ], }; /// Descriptor for `CheckTransactionResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List checkTransactionResponseDescriptor = $convert.base64Decode( 'ChhDaGVja1RyYW5zYWN0aW9uUmVzcG9uc2USGQoIaXNfdmFsaWQYASABKAhSB2lzVmFsaWQSIw' 'oNZXJyb3JfbWVzc2FnZRgCIAEoCVIMZXJyb3JNZXNzYWdl'); const $core.Map<$core.String, $core.dynamic> TransactionServiceBase$json = { '1': 'Transaction', '2': [ { '1': 'GetTransaction', '2': '.pactus.GetTransactionRequest', '3': '.pactus.GetTransactionResponse' }, { '1': 'CalculateFee', '2': '.pactus.CalculateFeeRequest', '3': '.pactus.CalculateFeeResponse' }, { '1': 'BroadcastTransaction', '2': '.pactus.BroadcastTransactionRequest', '3': '.pactus.BroadcastTransactionResponse' }, { '1': 'GetRawTransferTransaction', '2': '.pactus.GetRawTransferTransactionRequest', '3': '.pactus.GetRawTransactionResponse' }, { '1': 'GetRawBondTransaction', '2': '.pactus.GetRawBondTransactionRequest', '3': '.pactus.GetRawTransactionResponse' }, { '1': 'GetRawUnbondTransaction', '2': '.pactus.GetRawUnbondTransactionRequest', '3': '.pactus.GetRawTransactionResponse' }, { '1': 'GetRawWithdrawTransaction', '2': '.pactus.GetRawWithdrawTransactionRequest', '3': '.pactus.GetRawTransactionResponse' }, { '1': 'GetRawBatchTransferTransaction', '2': '.pactus.GetRawBatchTransferTransactionRequest', '3': '.pactus.GetRawTransactionResponse' }, { '1': 'DecodeRawTransaction', '2': '.pactus.DecodeRawTransactionRequest', '3': '.pactus.DecodeRawTransactionResponse' }, { '1': 'CheckTransaction', '2': '.pactus.CheckTransactionRequest', '3': '.pactus.CheckTransactionResponse' }, ], }; @$core.Deprecated('Use transactionServiceDescriptor instead') const $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> TransactionServiceBase$messageJson = { '.pactus.GetTransactionRequest': GetTransactionRequest$json, '.pactus.GetTransactionResponse': GetTransactionResponse$json, '.pactus.TransactionInfo': TransactionInfo$json, '.pactus.PayloadTransfer': PayloadTransfer$json, '.pactus.PayloadBond': PayloadBond$json, '.pactus.PayloadSortition': PayloadSortition$json, '.pactus.PayloadUnbond': PayloadUnbond$json, '.pactus.PayloadWithdraw': PayloadWithdraw$json, '.pactus.PayloadBatchTransfer': PayloadBatchTransfer$json, '.pactus.Recipient': Recipient$json, '.pactus.CalculateFeeRequest': CalculateFeeRequest$json, '.pactus.CalculateFeeResponse': CalculateFeeResponse$json, '.pactus.BroadcastTransactionRequest': BroadcastTransactionRequest$json, '.pactus.BroadcastTransactionResponse': BroadcastTransactionResponse$json, '.pactus.GetRawTransferTransactionRequest': GetRawTransferTransactionRequest$json, '.pactus.GetRawTransactionResponse': GetRawTransactionResponse$json, '.pactus.GetRawBondTransactionRequest': GetRawBondTransactionRequest$json, '.pactus.GetRawUnbondTransactionRequest': GetRawUnbondTransactionRequest$json, '.pactus.GetRawWithdrawTransactionRequest': GetRawWithdrawTransactionRequest$json, '.pactus.GetRawBatchTransferTransactionRequest': GetRawBatchTransferTransactionRequest$json, '.pactus.DecodeRawTransactionRequest': DecodeRawTransactionRequest$json, '.pactus.DecodeRawTransactionResponse': DecodeRawTransactionResponse$json, '.pactus.CheckTransactionRequest': CheckTransactionRequest$json, '.pactus.CheckTransactionResponse': CheckTransactionResponse$json, }; /// Descriptor for `Transaction`. Decode as a `google.protobuf.ServiceDescriptorProto`. final $typed_data.Uint8List transactionServiceDescriptor = $convert.base64Decode( 'CgtUcmFuc2FjdGlvbhJPCg5HZXRUcmFuc2FjdGlvbhIdLnBhY3R1cy5HZXRUcmFuc2FjdGlvbl' 'JlcXVlc3QaHi5wYWN0dXMuR2V0VHJhbnNhY3Rpb25SZXNwb25zZRJJCgxDYWxjdWxhdGVGZWUS' 'Gy5wYWN0dXMuQ2FsY3VsYXRlRmVlUmVxdWVzdBocLnBhY3R1cy5DYWxjdWxhdGVGZWVSZXNwb2' '5zZRJhChRCcm9hZGNhc3RUcmFuc2FjdGlvbhIjLnBhY3R1cy5Ccm9hZGNhc3RUcmFuc2FjdGlv' 'blJlcXVlc3QaJC5wYWN0dXMuQnJvYWRjYXN0VHJhbnNhY3Rpb25SZXNwb25zZRJoChlHZXRSYX' 'dUcmFuc2ZlclRyYW5zYWN0aW9uEigucGFjdHVzLkdldFJhd1RyYW5zZmVyVHJhbnNhY3Rpb25S' 'ZXF1ZXN0GiEucGFjdHVzLkdldFJhd1RyYW5zYWN0aW9uUmVzcG9uc2USYAoVR2V0UmF3Qm9uZF' 'RyYW5zYWN0aW9uEiQucGFjdHVzLkdldFJhd0JvbmRUcmFuc2FjdGlvblJlcXVlc3QaIS5wYWN0' 'dXMuR2V0UmF3VHJhbnNhY3Rpb25SZXNwb25zZRJkChdHZXRSYXdVbmJvbmRUcmFuc2FjdGlvbh' 'ImLnBhY3R1cy5HZXRSYXdVbmJvbmRUcmFuc2FjdGlvblJlcXVlc3QaIS5wYWN0dXMuR2V0UmF3' 'VHJhbnNhY3Rpb25SZXNwb25zZRJoChlHZXRSYXdXaXRoZHJhd1RyYW5zYWN0aW9uEigucGFjdH' 'VzLkdldFJhd1dpdGhkcmF3VHJhbnNhY3Rpb25SZXF1ZXN0GiEucGFjdHVzLkdldFJhd1RyYW5z' 'YWN0aW9uUmVzcG9uc2UScgoeR2V0UmF3QmF0Y2hUcmFuc2ZlclRyYW5zYWN0aW9uEi0ucGFjdH' 'VzLkdldFJhd0JhdGNoVHJhbnNmZXJUcmFuc2FjdGlvblJlcXVlc3QaIS5wYWN0dXMuR2V0UmF3' 'VHJhbnNhY3Rpb25SZXNwb25zZRJhChREZWNvZGVSYXdUcmFuc2FjdGlvbhIjLnBhY3R1cy5EZW' 'NvZGVSYXdUcmFuc2FjdGlvblJlcXVlc3QaJC5wYWN0dXMuRGVjb2RlUmF3VHJhbnNhY3Rpb25S' 'ZXNwb25zZRJVChBDaGVja1RyYW5zYWN0aW9uEh8ucGFjdHVzLkNoZWNrVHJhbnNhY3Rpb25SZX' 'F1ZXN0GiAucGFjdHVzLkNoZWNrVHJhbnNhY3Rpb25SZXNwb25zZQ=='); ================================================ FILE: www/grpc/gen/dart/transaction.pbserver.dart ================================================ // This is a generated file - do not edit. // // Generated from transaction.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'transaction.pb.dart' as $0; import 'transaction.pbjson.dart'; export 'transaction.pb.dart'; abstract class TransactionServiceBase extends $pb.GeneratedService { $async.Future<$0.GetTransactionResponse> getTransaction( $pb.ServerContext ctx, $0.GetTransactionRequest request); $async.Future<$0.CalculateFeeResponse> calculateFee( $pb.ServerContext ctx, $0.CalculateFeeRequest request); $async.Future<$0.BroadcastTransactionResponse> broadcastTransaction( $pb.ServerContext ctx, $0.BroadcastTransactionRequest request); $async.Future<$0.GetRawTransactionResponse> getRawTransferTransaction( $pb.ServerContext ctx, $0.GetRawTransferTransactionRequest request); $async.Future<$0.GetRawTransactionResponse> getRawBondTransaction( $pb.ServerContext ctx, $0.GetRawBondTransactionRequest request); $async.Future<$0.GetRawTransactionResponse> getRawUnbondTransaction( $pb.ServerContext ctx, $0.GetRawUnbondTransactionRequest request); $async.Future<$0.GetRawTransactionResponse> getRawWithdrawTransaction( $pb.ServerContext ctx, $0.GetRawWithdrawTransactionRequest request); $async.Future<$0.GetRawTransactionResponse> getRawBatchTransferTransaction( $pb.ServerContext ctx, $0.GetRawBatchTransferTransactionRequest request); $async.Future<$0.DecodeRawTransactionResponse> decodeRawTransaction( $pb.ServerContext ctx, $0.DecodeRawTransactionRequest request); $async.Future<$0.CheckTransactionResponse> checkTransaction( $pb.ServerContext ctx, $0.CheckTransactionRequest request); $pb.GeneratedMessage createRequest($core.String methodName) { switch (methodName) { case 'GetTransaction': return $0.GetTransactionRequest(); case 'CalculateFee': return $0.CalculateFeeRequest(); case 'BroadcastTransaction': return $0.BroadcastTransactionRequest(); case 'GetRawTransferTransaction': return $0.GetRawTransferTransactionRequest(); case 'GetRawBondTransaction': return $0.GetRawBondTransactionRequest(); case 'GetRawUnbondTransaction': return $0.GetRawUnbondTransactionRequest(); case 'GetRawWithdrawTransaction': return $0.GetRawWithdrawTransactionRequest(); case 'GetRawBatchTransferTransaction': return $0.GetRawBatchTransferTransactionRequest(); case 'DecodeRawTransaction': return $0.DecodeRawTransactionRequest(); case 'CheckTransaction': return $0.CheckTransactionRequest(); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $async.Future<$pb.GeneratedMessage> handleCall($pb.ServerContext ctx, $core.String methodName, $pb.GeneratedMessage request) { switch (methodName) { case 'GetTransaction': return getTransaction(ctx, request as $0.GetTransactionRequest); case 'CalculateFee': return calculateFee(ctx, request as $0.CalculateFeeRequest); case 'BroadcastTransaction': return broadcastTransaction( ctx, request as $0.BroadcastTransactionRequest); case 'GetRawTransferTransaction': return getRawTransferTransaction( ctx, request as $0.GetRawTransferTransactionRequest); case 'GetRawBondTransaction': return getRawBondTransaction( ctx, request as $0.GetRawBondTransactionRequest); case 'GetRawUnbondTransaction': return getRawUnbondTransaction( ctx, request as $0.GetRawUnbondTransactionRequest); case 'GetRawWithdrawTransaction': return getRawWithdrawTransaction( ctx, request as $0.GetRawWithdrawTransactionRequest); case 'GetRawBatchTransferTransaction': return getRawBatchTransferTransaction( ctx, request as $0.GetRawBatchTransferTransactionRequest); case 'DecodeRawTransaction': return decodeRawTransaction( ctx, request as $0.DecodeRawTransactionRequest); case 'CheckTransaction': return checkTransaction(ctx, request as $0.CheckTransactionRequest); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $core.Map<$core.String, $core.dynamic> get $json => TransactionServiceBase$json; $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> get $messageJson => TransactionServiceBase$messageJson; } ================================================ FILE: www/grpc/gen/dart/utils.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from utils.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// Request message for signing a message with a private key. class SignMessageWithPrivateKeyRequest extends $pb.GeneratedMessage { factory SignMessageWithPrivateKeyRequest({ $core.String? privateKey, $core.String? message, }) { final result = create(); if (privateKey != null) result.privateKey = privateKey; if (message != null) result.message = message; return result; } SignMessageWithPrivateKeyRequest._(); factory SignMessageWithPrivateKeyRequest.fromBuffer( $core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignMessageWithPrivateKeyRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignMessageWithPrivateKeyRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'privateKey') ..aOS(2, _omitFieldNames ? '' : 'message') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageWithPrivateKeyRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageWithPrivateKeyRequest copyWith( void Function(SignMessageWithPrivateKeyRequest) updates) => super.copyWith( (message) => updates(message as SignMessageWithPrivateKeyRequest)) as SignMessageWithPrivateKeyRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignMessageWithPrivateKeyRequest create() => SignMessageWithPrivateKeyRequest._(); @$core.override SignMessageWithPrivateKeyRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignMessageWithPrivateKeyRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor( create); static SignMessageWithPrivateKeyRequest? _defaultInstance; /// The private key to sign the message. @$pb.TagNumber(1) $core.String get privateKey => $_getSZ(0); @$pb.TagNumber(1) set privateKey($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasPrivateKey() => $_has(0); @$pb.TagNumber(1) void clearPrivateKey() => $_clearField(1); /// The message content to be signed. @$pb.TagNumber(2) $core.String get message => $_getSZ(1); @$pb.TagNumber(2) set message($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasMessage() => $_has(1); @$pb.TagNumber(2) void clearMessage() => $_clearField(2); } /// Response message contains the signature generated from the message. class SignMessageWithPrivateKeyResponse extends $pb.GeneratedMessage { factory SignMessageWithPrivateKeyResponse({ $core.String? signature, }) { final result = create(); if (signature != null) result.signature = signature; return result; } SignMessageWithPrivateKeyResponse._(); factory SignMessageWithPrivateKeyResponse.fromBuffer( $core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignMessageWithPrivateKeyResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignMessageWithPrivateKeyResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'signature') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageWithPrivateKeyResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageWithPrivateKeyResponse copyWith( void Function(SignMessageWithPrivateKeyResponse) updates) => super.copyWith((message) => updates(message as SignMessageWithPrivateKeyResponse)) as SignMessageWithPrivateKeyResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignMessageWithPrivateKeyResponse create() => SignMessageWithPrivateKeyResponse._(); @$core.override SignMessageWithPrivateKeyResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignMessageWithPrivateKeyResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor( create); static SignMessageWithPrivateKeyResponse? _defaultInstance; /// The resulting signature in hexadecimal format. @$pb.TagNumber(1) $core.String get signature => $_getSZ(0); @$pb.TagNumber(1) set signature($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSignature() => $_has(0); @$pb.TagNumber(1) void clearSignature() => $_clearField(1); } /// Request message for verifying a message signature. class VerifyMessageRequest extends $pb.GeneratedMessage { factory VerifyMessageRequest({ $core.String? message, $core.String? signature, $core.String? publicKey, }) { final result = create(); if (message != null) result.message = message; if (signature != null) result.signature = signature; if (publicKey != null) result.publicKey = publicKey; return result; } VerifyMessageRequest._(); factory VerifyMessageRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory VerifyMessageRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'VerifyMessageRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'message') ..aOS(2, _omitFieldNames ? '' : 'signature') ..aOS(3, _omitFieldNames ? '' : 'publicKey') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') VerifyMessageRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') VerifyMessageRequest copyWith(void Function(VerifyMessageRequest) updates) => super.copyWith((message) => updates(message as VerifyMessageRequest)) as VerifyMessageRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static VerifyMessageRequest create() => VerifyMessageRequest._(); @$core.override VerifyMessageRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static VerifyMessageRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static VerifyMessageRequest? _defaultInstance; /// The original message content that was signed. @$pb.TagNumber(1) $core.String get message => $_getSZ(0); @$pb.TagNumber(1) set message($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasMessage() => $_has(0); @$pb.TagNumber(1) void clearMessage() => $_clearField(1); /// The signature to verify in hexadecimal format. @$pb.TagNumber(2) $core.String get signature => $_getSZ(1); @$pb.TagNumber(2) set signature($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasSignature() => $_has(1); @$pb.TagNumber(2) void clearSignature() => $_clearField(2); /// The public key of the signer. @$pb.TagNumber(3) $core.String get publicKey => $_getSZ(2); @$pb.TagNumber(3) set publicKey($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasPublicKey() => $_has(2); @$pb.TagNumber(3) void clearPublicKey() => $_clearField(3); } /// Response message contains the verification result. class VerifyMessageResponse extends $pb.GeneratedMessage { factory VerifyMessageResponse({ $core.bool? isValid, }) { final result = create(); if (isValid != null) result.isValid = isValid; return result; } VerifyMessageResponse._(); factory VerifyMessageResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory VerifyMessageResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'VerifyMessageResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOB(1, _omitFieldNames ? '' : 'isValid') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') VerifyMessageResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') VerifyMessageResponse copyWith( void Function(VerifyMessageResponse) updates) => super.copyWith((message) => updates(message as VerifyMessageResponse)) as VerifyMessageResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static VerifyMessageResponse create() => VerifyMessageResponse._(); @$core.override VerifyMessageResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static VerifyMessageResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static VerifyMessageResponse? _defaultInstance; /// Boolean indicating whether the signature is valid for the given message and public key. @$pb.TagNumber(1) $core.bool get isValid => $_getBF(0); @$pb.TagNumber(1) set isValid($core.bool value) => $_setBool(0, value); @$pb.TagNumber(1) $core.bool hasIsValid() => $_has(0); @$pb.TagNumber(1) void clearIsValid() => $_clearField(1); } /// Request message for aggregating multiple BLS public keys. class PublicKeyAggregationRequest extends $pb.GeneratedMessage { factory PublicKeyAggregationRequest({ $core.Iterable<$core.String>? publicKeys, }) { final result = create(); if (publicKeys != null) result.publicKeys.addAll(publicKeys); return result; } PublicKeyAggregationRequest._(); factory PublicKeyAggregationRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PublicKeyAggregationRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PublicKeyAggregationRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..pPS(1, _omitFieldNames ? '' : 'publicKeys') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PublicKeyAggregationRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PublicKeyAggregationRequest copyWith( void Function(PublicKeyAggregationRequest) updates) => super.copyWith( (message) => updates(message as PublicKeyAggregationRequest)) as PublicKeyAggregationRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PublicKeyAggregationRequest create() => PublicKeyAggregationRequest._(); @$core.override PublicKeyAggregationRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PublicKeyAggregationRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PublicKeyAggregationRequest? _defaultInstance; /// List of BLS public keys to be aggregated. @$pb.TagNumber(1) $pb.PbList<$core.String> get publicKeys => $_getList(0); } /// Response message contains the aggregated BLS public key result. class PublicKeyAggregationResponse extends $pb.GeneratedMessage { factory PublicKeyAggregationResponse({ $core.String? publicKey, $core.String? address, }) { final result = create(); if (publicKey != null) result.publicKey = publicKey; if (address != null) result.address = address; return result; } PublicKeyAggregationResponse._(); factory PublicKeyAggregationResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory PublicKeyAggregationResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'PublicKeyAggregationResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'publicKey') ..aOS(2, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PublicKeyAggregationResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PublicKeyAggregationResponse copyWith( void Function(PublicKeyAggregationResponse) updates) => super.copyWith( (message) => updates(message as PublicKeyAggregationResponse)) as PublicKeyAggregationResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static PublicKeyAggregationResponse create() => PublicKeyAggregationResponse._(); @$core.override PublicKeyAggregationResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static PublicKeyAggregationResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static PublicKeyAggregationResponse? _defaultInstance; /// The aggregated BLS public key. @$pb.TagNumber(1) $core.String get publicKey => $_getSZ(0); @$pb.TagNumber(1) set publicKey($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasPublicKey() => $_has(0); @$pb.TagNumber(1) void clearPublicKey() => $_clearField(1); /// The blockchain address derived from the aggregated public key. @$pb.TagNumber(2) $core.String get address => $_getSZ(1); @$pb.TagNumber(2) set address($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAddress() => $_has(1); @$pb.TagNumber(2) void clearAddress() => $_clearField(2); } /// Request message for aggregating multiple BLS signatures. class SignatureAggregationRequest extends $pb.GeneratedMessage { factory SignatureAggregationRequest({ $core.Iterable<$core.String>? signatures, }) { final result = create(); if (signatures != null) result.signatures.addAll(signatures); return result; } SignatureAggregationRequest._(); factory SignatureAggregationRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignatureAggregationRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignatureAggregationRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..pPS(1, _omitFieldNames ? '' : 'signatures') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignatureAggregationRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignatureAggregationRequest copyWith( void Function(SignatureAggregationRequest) updates) => super.copyWith( (message) => updates(message as SignatureAggregationRequest)) as SignatureAggregationRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignatureAggregationRequest create() => SignatureAggregationRequest._(); @$core.override SignatureAggregationRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignatureAggregationRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SignatureAggregationRequest? _defaultInstance; /// List of BLS signatures to be aggregated. @$pb.TagNumber(1) $pb.PbList<$core.String> get signatures => $_getList(0); } /// Response message contains the aggregated BLS signature. class SignatureAggregationResponse extends $pb.GeneratedMessage { factory SignatureAggregationResponse({ $core.String? signature, }) { final result = create(); if (signature != null) result.signature = signature; return result; } SignatureAggregationResponse._(); factory SignatureAggregationResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignatureAggregationResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignatureAggregationResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'signature') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignatureAggregationResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignatureAggregationResponse copyWith( void Function(SignatureAggregationResponse) updates) => super.copyWith( (message) => updates(message as SignatureAggregationResponse)) as SignatureAggregationResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignatureAggregationResponse create() => SignatureAggregationResponse._(); @$core.override SignatureAggregationResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignatureAggregationResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SignatureAggregationResponse? _defaultInstance; /// The aggregated BLS signature in hexadecimal format. @$pb.TagNumber(1) $core.String get signature => $_getSZ(0); @$pb.TagNumber(1) set signature($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSignature() => $_has(0); @$pb.TagNumber(1) void clearSignature() => $_clearField(1); } /// Utils service defines RPC methods for utility functions such as message /// signing, verification, and other cryptographic operations. class UtilsApi { final $pb.RpcClient _client; UtilsApi(this._client); /// SignMessageWithPrivateKey signs a message with the provided private key. $async.Future signMessageWithPrivateKey( $pb.ClientContext? ctx, SignMessageWithPrivateKeyRequest request) => _client.invoke( ctx, 'Utils', 'SignMessageWithPrivateKey', request, SignMessageWithPrivateKeyResponse()); /// VerifyMessage verifies a signature against the public key and message. $async.Future verifyMessage( $pb.ClientContext? ctx, VerifyMessageRequest request) => _client.invoke( ctx, 'Utils', 'VerifyMessage', request, VerifyMessageResponse()); /// PublicKeyAggregation aggregates multiple BLS public keys into a single key. $async.Future publicKeyAggregation( $pb.ClientContext? ctx, PublicKeyAggregationRequest request) => _client.invoke(ctx, 'Utils', 'PublicKeyAggregation', request, PublicKeyAggregationResponse()); /// SignatureAggregation aggregates multiple BLS signatures into a single signature. $async.Future signatureAggregation( $pb.ClientContext? ctx, SignatureAggregationRequest request) => _client.invoke(ctx, 'Utils', 'SignatureAggregation', request, SignatureAggregationResponse()); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: www/grpc/gen/dart/utils.pbenum.dart ================================================ // This is a generated file - do not edit. // // Generated from utils.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports ================================================ FILE: www/grpc/gen/dart/utils.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from utils.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use signMessageWithPrivateKeyRequestDescriptor instead') const SignMessageWithPrivateKeyRequest$json = { '1': 'SignMessageWithPrivateKeyRequest', '2': [ {'1': 'private_key', '3': 1, '4': 1, '5': 9, '10': 'privateKey'}, {'1': 'message', '3': 2, '4': 1, '5': 9, '10': 'message'}, ], }; /// Descriptor for `SignMessageWithPrivateKeyRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signMessageWithPrivateKeyRequestDescriptor = $convert.base64Decode( 'CiBTaWduTWVzc2FnZVdpdGhQcml2YXRlS2V5UmVxdWVzdBIfCgtwcml2YXRlX2tleRgBIAEoCV' 'IKcHJpdmF0ZUtleRIYCgdtZXNzYWdlGAIgASgJUgdtZXNzYWdl'); @$core.Deprecated('Use signMessageWithPrivateKeyResponseDescriptor instead') const SignMessageWithPrivateKeyResponse$json = { '1': 'SignMessageWithPrivateKeyResponse', '2': [ {'1': 'signature', '3': 1, '4': 1, '5': 9, '10': 'signature'}, ], }; /// Descriptor for `SignMessageWithPrivateKeyResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signMessageWithPrivateKeyResponseDescriptor = $convert.base64Decode( 'CiFTaWduTWVzc2FnZVdpdGhQcml2YXRlS2V5UmVzcG9uc2USHAoJc2lnbmF0dXJlGAEgASgJUg' 'lzaWduYXR1cmU='); @$core.Deprecated('Use verifyMessageRequestDescriptor instead') const VerifyMessageRequest$json = { '1': 'VerifyMessageRequest', '2': [ {'1': 'message', '3': 1, '4': 1, '5': 9, '10': 'message'}, {'1': 'signature', '3': 2, '4': 1, '5': 9, '10': 'signature'}, {'1': 'public_key', '3': 3, '4': 1, '5': 9, '10': 'publicKey'}, ], }; /// Descriptor for `VerifyMessageRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List verifyMessageRequestDescriptor = $convert.base64Decode( 'ChRWZXJpZnlNZXNzYWdlUmVxdWVzdBIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlEhwKCXNpZ2' '5hdHVyZRgCIAEoCVIJc2lnbmF0dXJlEh0KCnB1YmxpY19rZXkYAyABKAlSCXB1YmxpY0tleQ=='); @$core.Deprecated('Use verifyMessageResponseDescriptor instead') const VerifyMessageResponse$json = { '1': 'VerifyMessageResponse', '2': [ {'1': 'is_valid', '3': 1, '4': 1, '5': 8, '10': 'isValid'}, ], }; /// Descriptor for `VerifyMessageResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List verifyMessageResponseDescriptor = $convert.base64Decode( 'ChVWZXJpZnlNZXNzYWdlUmVzcG9uc2USGQoIaXNfdmFsaWQYASABKAhSB2lzVmFsaWQ='); @$core.Deprecated('Use publicKeyAggregationRequestDescriptor instead') const PublicKeyAggregationRequest$json = { '1': 'PublicKeyAggregationRequest', '2': [ {'1': 'public_keys', '3': 1, '4': 3, '5': 9, '10': 'publicKeys'}, ], }; /// Descriptor for `PublicKeyAggregationRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List publicKeyAggregationRequestDescriptor = $convert.base64Decode( 'ChtQdWJsaWNLZXlBZ2dyZWdhdGlvblJlcXVlc3QSHwoLcHVibGljX2tleXMYASADKAlSCnB1Ym' 'xpY0tleXM='); @$core.Deprecated('Use publicKeyAggregationResponseDescriptor instead') const PublicKeyAggregationResponse$json = { '1': 'PublicKeyAggregationResponse', '2': [ {'1': 'public_key', '3': 1, '4': 1, '5': 9, '10': 'publicKey'}, {'1': 'address', '3': 2, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `PublicKeyAggregationResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List publicKeyAggregationResponseDescriptor = $convert.base64Decode( 'ChxQdWJsaWNLZXlBZ2dyZWdhdGlvblJlc3BvbnNlEh0KCnB1YmxpY19rZXkYASABKAlSCXB1Ym' 'xpY0tleRIYCgdhZGRyZXNzGAIgASgJUgdhZGRyZXNz'); @$core.Deprecated('Use signatureAggregationRequestDescriptor instead') const SignatureAggregationRequest$json = { '1': 'SignatureAggregationRequest', '2': [ {'1': 'signatures', '3': 1, '4': 3, '5': 9, '10': 'signatures'}, ], }; /// Descriptor for `SignatureAggregationRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signatureAggregationRequestDescriptor = $convert.base64Decode( 'ChtTaWduYXR1cmVBZ2dyZWdhdGlvblJlcXVlc3QSHgoKc2lnbmF0dXJlcxgBIAMoCVIKc2lnbm' 'F0dXJlcw=='); @$core.Deprecated('Use signatureAggregationResponseDescriptor instead') const SignatureAggregationResponse$json = { '1': 'SignatureAggregationResponse', '2': [ {'1': 'signature', '3': 1, '4': 1, '5': 9, '10': 'signature'}, ], }; /// Descriptor for `SignatureAggregationResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signatureAggregationResponseDescriptor = $convert.base64Decode( 'ChxTaWduYXR1cmVBZ2dyZWdhdGlvblJlc3BvbnNlEhwKCXNpZ25hdHVyZRgBIAEoCVIJc2lnbm' 'F0dXJl'); const $core.Map<$core.String, $core.dynamic> UtilsServiceBase$json = { '1': 'Utils', '2': [ { '1': 'SignMessageWithPrivateKey', '2': '.pactus.SignMessageWithPrivateKeyRequest', '3': '.pactus.SignMessageWithPrivateKeyResponse' }, { '1': 'VerifyMessage', '2': '.pactus.VerifyMessageRequest', '3': '.pactus.VerifyMessageResponse' }, { '1': 'PublicKeyAggregation', '2': '.pactus.PublicKeyAggregationRequest', '3': '.pactus.PublicKeyAggregationResponse' }, { '1': 'SignatureAggregation', '2': '.pactus.SignatureAggregationRequest', '3': '.pactus.SignatureAggregationResponse' }, ], }; @$core.Deprecated('Use utilsServiceDescriptor instead') const $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> UtilsServiceBase$messageJson = { '.pactus.SignMessageWithPrivateKeyRequest': SignMessageWithPrivateKeyRequest$json, '.pactus.SignMessageWithPrivateKeyResponse': SignMessageWithPrivateKeyResponse$json, '.pactus.VerifyMessageRequest': VerifyMessageRequest$json, '.pactus.VerifyMessageResponse': VerifyMessageResponse$json, '.pactus.PublicKeyAggregationRequest': PublicKeyAggregationRequest$json, '.pactus.PublicKeyAggregationResponse': PublicKeyAggregationResponse$json, '.pactus.SignatureAggregationRequest': SignatureAggregationRequest$json, '.pactus.SignatureAggregationResponse': SignatureAggregationResponse$json, }; /// Descriptor for `Utils`. Decode as a `google.protobuf.ServiceDescriptorProto`. final $typed_data.Uint8List utilsServiceDescriptor = $convert.base64Decode( 'CgVVdGlscxJwChlTaWduTWVzc2FnZVdpdGhQcml2YXRlS2V5EigucGFjdHVzLlNpZ25NZXNzYW' 'dlV2l0aFByaXZhdGVLZXlSZXF1ZXN0GikucGFjdHVzLlNpZ25NZXNzYWdlV2l0aFByaXZhdGVL' 'ZXlSZXNwb25zZRJMCg1WZXJpZnlNZXNzYWdlEhwucGFjdHVzLlZlcmlmeU1lc3NhZ2VSZXF1ZX' 'N0Gh0ucGFjdHVzLlZlcmlmeU1lc3NhZ2VSZXNwb25zZRJhChRQdWJsaWNLZXlBZ2dyZWdhdGlv' 'bhIjLnBhY3R1cy5QdWJsaWNLZXlBZ2dyZWdhdGlvblJlcXVlc3QaJC5wYWN0dXMuUHVibGljS2' 'V5QWdncmVnYXRpb25SZXNwb25zZRJhChRTaWduYXR1cmVBZ2dyZWdhdGlvbhIjLnBhY3R1cy5T' 'aWduYXR1cmVBZ2dyZWdhdGlvblJlcXVlc3QaJC5wYWN0dXMuU2lnbmF0dXJlQWdncmVnYXRpb2' '5SZXNwb25zZQ=='); ================================================ FILE: www/grpc/gen/dart/utils.pbserver.dart ================================================ // This is a generated file - do not edit. // // Generated from utils.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'utils.pb.dart' as $0; import 'utils.pbjson.dart'; export 'utils.pb.dart'; abstract class UtilsServiceBase extends $pb.GeneratedService { $async.Future<$0.SignMessageWithPrivateKeyResponse> signMessageWithPrivateKey( $pb.ServerContext ctx, $0.SignMessageWithPrivateKeyRequest request); $async.Future<$0.VerifyMessageResponse> verifyMessage( $pb.ServerContext ctx, $0.VerifyMessageRequest request); $async.Future<$0.PublicKeyAggregationResponse> publicKeyAggregation( $pb.ServerContext ctx, $0.PublicKeyAggregationRequest request); $async.Future<$0.SignatureAggregationResponse> signatureAggregation( $pb.ServerContext ctx, $0.SignatureAggregationRequest request); $pb.GeneratedMessage createRequest($core.String methodName) { switch (methodName) { case 'SignMessageWithPrivateKey': return $0.SignMessageWithPrivateKeyRequest(); case 'VerifyMessage': return $0.VerifyMessageRequest(); case 'PublicKeyAggregation': return $0.PublicKeyAggregationRequest(); case 'SignatureAggregation': return $0.SignatureAggregationRequest(); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $async.Future<$pb.GeneratedMessage> handleCall($pb.ServerContext ctx, $core.String methodName, $pb.GeneratedMessage request) { switch (methodName) { case 'SignMessageWithPrivateKey': return signMessageWithPrivateKey( ctx, request as $0.SignMessageWithPrivateKeyRequest); case 'VerifyMessage': return verifyMessage(ctx, request as $0.VerifyMessageRequest); case 'PublicKeyAggregation': return publicKeyAggregation( ctx, request as $0.PublicKeyAggregationRequest); case 'SignatureAggregation': return signatureAggregation( ctx, request as $0.SignatureAggregationRequest); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $core.Map<$core.String, $core.dynamic> get $json => UtilsServiceBase$json; $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> get $messageJson => UtilsServiceBase$messageJson; } ================================================ FILE: www/grpc/gen/dart/wallet.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from wallet.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'transaction.pbenum.dart' as $0; import 'wallet.pbenum.dart'; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; export 'wallet.pbenum.dart'; /// AddressInfo contains detailed information about a wallet address. class AddressInfo extends $pb.GeneratedMessage { factory AddressInfo({ $core.String? address, $core.String? publicKey, $core.String? label, $core.String? path, }) { final result = create(); if (address != null) result.address = address; if (publicKey != null) result.publicKey = publicKey; if (label != null) result.label = label; if (path != null) result.path = path; return result; } AddressInfo._(); factory AddressInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory AddressInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'AddressInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..aOS(2, _omitFieldNames ? '' : 'publicKey') ..aOS(3, _omitFieldNames ? '' : 'label') ..aOS(4, _omitFieldNames ? '' : 'path') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') AddressInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') AddressInfo copyWith(void Function(AddressInfo) updates) => super.copyWith((message) => updates(message as AddressInfo)) as AddressInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static AddressInfo create() => AddressInfo._(); @$core.override AddressInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static AddressInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static AddressInfo? _defaultInstance; /// The address string. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); /// The public key associated with the address. @$pb.TagNumber(2) $core.String get publicKey => $_getSZ(1); @$pb.TagNumber(2) set publicKey($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPublicKey() => $_has(1); @$pb.TagNumber(2) void clearPublicKey() => $_clearField(2); /// A human-readable label associated with the address. @$pb.TagNumber(3) $core.String get label => $_getSZ(2); @$pb.TagNumber(3) set label($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasLabel() => $_has(2); @$pb.TagNumber(3) void clearLabel() => $_clearField(3); /// The Hierarchical Deterministic (HD) path of the address within the wallet. @$pb.TagNumber(4) $core.String get path => $_getSZ(3); @$pb.TagNumber(4) set path($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasPath() => $_has(3); @$pb.TagNumber(4) void clearPath() => $_clearField(4); } /// Request message for generating a new wallet address. class GetNewAddressRequest extends $pb.GeneratedMessage { factory GetNewAddressRequest({ $core.String? walletName, AddressType? addressType, $core.String? label, $core.String? password, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (addressType != null) result.addressType = addressType; if (label != null) result.label = label; if (password != null) result.password = password; return result; } GetNewAddressRequest._(); factory GetNewAddressRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetNewAddressRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetNewAddressRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aE(2, _omitFieldNames ? '' : 'addressType', enumValues: AddressType.values) ..aOS(3, _omitFieldNames ? '' : 'label') ..aOS(4, _omitFieldNames ? '' : 'password') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNewAddressRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNewAddressRequest copyWith(void Function(GetNewAddressRequest) updates) => super.copyWith((message) => updates(message as GetNewAddressRequest)) as GetNewAddressRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetNewAddressRequest create() => GetNewAddressRequest._(); @$core.override GetNewAddressRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetNewAddressRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetNewAddressRequest? _defaultInstance; /// The name of the wallet to generate a new address. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The type of address to generate. @$pb.TagNumber(2) AddressType get addressType => $_getN(1); @$pb.TagNumber(2) set addressType(AddressType value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasAddressType() => $_has(1); @$pb.TagNumber(2) void clearAddressType() => $_clearField(2); /// A label for the new address. @$pb.TagNumber(3) $core.String get label => $_getSZ(2); @$pb.TagNumber(3) set label($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasLabel() => $_has(2); @$pb.TagNumber(3) void clearLabel() => $_clearField(3); /// Password for the new address. It's required when address_type is Ed25519 type. @$pb.TagNumber(4) $core.String get password => $_getSZ(3); @$pb.TagNumber(4) set password($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasPassword() => $_has(3); @$pb.TagNumber(4) void clearPassword() => $_clearField(4); } /// Response message contains newly generated address information. class GetNewAddressResponse extends $pb.GeneratedMessage { factory GetNewAddressResponse({ $core.String? walletName, AddressInfo? addr, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (addr != null) result.addr = addr; return result; } GetNewAddressResponse._(); factory GetNewAddressResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetNewAddressResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetNewAddressResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOM(2, _omitFieldNames ? '' : 'addr', subBuilder: AddressInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNewAddressResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetNewAddressResponse copyWith( void Function(GetNewAddressResponse) updates) => super.copyWith((message) => updates(message as GetNewAddressResponse)) as GetNewAddressResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetNewAddressResponse create() => GetNewAddressResponse._(); @$core.override GetNewAddressResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetNewAddressResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetNewAddressResponse? _defaultInstance; /// The name of the wallet where address was generated. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Detailed information about the new address. @$pb.TagNumber(2) AddressInfo get addr => $_getN(1); @$pb.TagNumber(2) set addr(AddressInfo value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasAddr() => $_has(1); @$pb.TagNumber(2) void clearAddr() => $_clearField(2); @$pb.TagNumber(2) AddressInfo ensureAddr() => $_ensure(1); } /// Request message for restoring a wallet from mnemonic (seed phrase). class RestoreWalletRequest extends $pb.GeneratedMessage { factory RestoreWalletRequest({ $core.String? walletName, $core.String? mnemonic, $core.String? password, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (mnemonic != null) result.mnemonic = mnemonic; if (password != null) result.password = password; return result; } RestoreWalletRequest._(); factory RestoreWalletRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory RestoreWalletRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'RestoreWalletRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'mnemonic') ..aOS(3, _omitFieldNames ? '' : 'password') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') RestoreWalletRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') RestoreWalletRequest copyWith(void Function(RestoreWalletRequest) updates) => super.copyWith((message) => updates(message as RestoreWalletRequest)) as RestoreWalletRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static RestoreWalletRequest create() => RestoreWalletRequest._(); @$core.override RestoreWalletRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static RestoreWalletRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static RestoreWalletRequest? _defaultInstance; /// The name for the restored wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The mnemonic (seed phrase) for wallet recovery. @$pb.TagNumber(2) $core.String get mnemonic => $_getSZ(1); @$pb.TagNumber(2) set mnemonic($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasMnemonic() => $_has(1); @$pb.TagNumber(2) void clearMnemonic() => $_clearField(2); /// Password to secure the restored wallet. @$pb.TagNumber(3) $core.String get password => $_getSZ(2); @$pb.TagNumber(3) set password($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasPassword() => $_has(2); @$pb.TagNumber(3) void clearPassword() => $_clearField(3); } /// Response message confirming wallet restoration. class RestoreWalletResponse extends $pb.GeneratedMessage { factory RestoreWalletResponse({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } RestoreWalletResponse._(); factory RestoreWalletResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory RestoreWalletResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'RestoreWalletResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') RestoreWalletResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') RestoreWalletResponse copyWith( void Function(RestoreWalletResponse) updates) => super.copyWith((message) => updates(message as RestoreWalletResponse)) as RestoreWalletResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static RestoreWalletResponse create() => RestoreWalletResponse._(); @$core.override RestoreWalletResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static RestoreWalletResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static RestoreWalletResponse? _defaultInstance; /// The name of the restored wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Request message for creating a new wallet. class CreateWalletRequest extends $pb.GeneratedMessage { factory CreateWalletRequest({ $core.String? walletName, $core.String? password, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (password != null) result.password = password; return result; } CreateWalletRequest._(); factory CreateWalletRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CreateWalletRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CreateWalletRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'password') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CreateWalletRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CreateWalletRequest copyWith(void Function(CreateWalletRequest) updates) => super.copyWith((message) => updates(message as CreateWalletRequest)) as CreateWalletRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CreateWalletRequest create() => CreateWalletRequest._(); @$core.override CreateWalletRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CreateWalletRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CreateWalletRequest? _defaultInstance; /// The name for the new wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Password to secure the new wallet. @$pb.TagNumber(2) $core.String get password => $_getSZ(1); @$pb.TagNumber(2) set password($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPassword() => $_has(1); @$pb.TagNumber(2) void clearPassword() => $_clearField(2); } /// Response message contains wallet recovery mnemonic (seed phrase). class CreateWalletResponse extends $pb.GeneratedMessage { factory CreateWalletResponse({ $core.String? walletName, $core.String? mnemonic, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (mnemonic != null) result.mnemonic = mnemonic; return result; } CreateWalletResponse._(); factory CreateWalletResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory CreateWalletResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'CreateWalletResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'mnemonic') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CreateWalletResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') CreateWalletResponse copyWith(void Function(CreateWalletResponse) updates) => super.copyWith((message) => updates(message as CreateWalletResponse)) as CreateWalletResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static CreateWalletResponse create() => CreateWalletResponse._(); @$core.override CreateWalletResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static CreateWalletResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static CreateWalletResponse? _defaultInstance; /// The name for the new wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The mnemonic (seed phrase) for wallet recovery. @$pb.TagNumber(2) $core.String get mnemonic => $_getSZ(1); @$pb.TagNumber(2) set mnemonic($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasMnemonic() => $_has(1); @$pb.TagNumber(2) void clearMnemonic() => $_clearField(2); } /// Request message for loading an existing wallet. /// Deprecated: It will be removed in a future version. class LoadWalletRequest extends $pb.GeneratedMessage { factory LoadWalletRequest({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } LoadWalletRequest._(); factory LoadWalletRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory LoadWalletRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'LoadWalletRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') LoadWalletRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') LoadWalletRequest copyWith(void Function(LoadWalletRequest) updates) => super.copyWith((message) => updates(message as LoadWalletRequest)) as LoadWalletRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static LoadWalletRequest create() => LoadWalletRequest._(); @$core.override LoadWalletRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static LoadWalletRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static LoadWalletRequest? _defaultInstance; /// The name of the wallet to load. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Response message confirming wallet loaded. /// Deprecated: It will be removed in a future version. class LoadWalletResponse extends $pb.GeneratedMessage { factory LoadWalletResponse({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } LoadWalletResponse._(); factory LoadWalletResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory LoadWalletResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'LoadWalletResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') LoadWalletResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') LoadWalletResponse copyWith(void Function(LoadWalletResponse) updates) => super.copyWith((message) => updates(message as LoadWalletResponse)) as LoadWalletResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static LoadWalletResponse create() => LoadWalletResponse._(); @$core.override LoadWalletResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static LoadWalletResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static LoadWalletResponse? _defaultInstance; /// The name of the loaded wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Request message for unloading a wallet. /// Deprecated: It will be removed in a future version. class UnloadWalletRequest extends $pb.GeneratedMessage { factory UnloadWalletRequest({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } UnloadWalletRequest._(); factory UnloadWalletRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory UnloadWalletRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'UnloadWalletRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UnloadWalletRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UnloadWalletRequest copyWith(void Function(UnloadWalletRequest) updates) => super.copyWith((message) => updates(message as UnloadWalletRequest)) as UnloadWalletRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static UnloadWalletRequest create() => UnloadWalletRequest._(); @$core.override UnloadWalletRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static UnloadWalletRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static UnloadWalletRequest? _defaultInstance; /// The name of the wallet to unload. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Response message confirming wallet unloading. /// Deprecated: It will be removed in a future version. class UnloadWalletResponse extends $pb.GeneratedMessage { factory UnloadWalletResponse({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } UnloadWalletResponse._(); factory UnloadWalletResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory UnloadWalletResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'UnloadWalletResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UnloadWalletResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UnloadWalletResponse copyWith(void Function(UnloadWalletResponse) updates) => super.copyWith((message) => updates(message as UnloadWalletResponse)) as UnloadWalletResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static UnloadWalletResponse create() => UnloadWalletResponse._(); @$core.override UnloadWalletResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static UnloadWalletResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static UnloadWalletResponse? _defaultInstance; /// The name of the unloaded wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Request message for obtaining the validator address associated with a public key. class GetValidatorAddressRequest extends $pb.GeneratedMessage { factory GetValidatorAddressRequest({ $core.String? publicKey, }) { final result = create(); if (publicKey != null) result.publicKey = publicKey; return result; } GetValidatorAddressRequest._(); factory GetValidatorAddressRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorAddressRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorAddressRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'publicKey') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressRequest copyWith( void Function(GetValidatorAddressRequest) updates) => super.copyWith( (message) => updates(message as GetValidatorAddressRequest)) as GetValidatorAddressRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorAddressRequest create() => GetValidatorAddressRequest._(); @$core.override GetValidatorAddressRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorAddressRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorAddressRequest? _defaultInstance; /// The public key of the validator. @$pb.TagNumber(1) $core.String get publicKey => $_getSZ(0); @$pb.TagNumber(1) set publicKey($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasPublicKey() => $_has(0); @$pb.TagNumber(1) void clearPublicKey() => $_clearField(1); } /// Response message containing the validator address corresponding to a public key. class GetValidatorAddressResponse extends $pb.GeneratedMessage { factory GetValidatorAddressResponse({ $core.String? address, }) { final result = create(); if (address != null) result.address = address; return result; } GetValidatorAddressResponse._(); factory GetValidatorAddressResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetValidatorAddressResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetValidatorAddressResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetValidatorAddressResponse copyWith( void Function(GetValidatorAddressResponse) updates) => super.copyWith( (message) => updates(message as GetValidatorAddressResponse)) as GetValidatorAddressResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetValidatorAddressResponse create() => GetValidatorAddressResponse._(); @$core.override GetValidatorAddressResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetValidatorAddressResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetValidatorAddressResponse? _defaultInstance; /// The validator address associated with the public key. @$pb.TagNumber(1) $core.String get address => $_getSZ(0); @$pb.TagNumber(1) set address($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasAddress() => $_has(0); @$pb.TagNumber(1) void clearAddress() => $_clearField(1); } /// Request message for signing a raw transaction. class SignRawTransactionRequest extends $pb.GeneratedMessage { factory SignRawTransactionRequest({ $core.String? walletName, $core.String? rawTransaction, $core.String? password, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (rawTransaction != null) result.rawTransaction = rawTransaction; if (password != null) result.password = password; return result; } SignRawTransactionRequest._(); factory SignRawTransactionRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignRawTransactionRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignRawTransactionRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'rawTransaction') ..aOS(3, _omitFieldNames ? '' : 'password') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignRawTransactionRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignRawTransactionRequest copyWith( void Function(SignRawTransactionRequest) updates) => super.copyWith((message) => updates(message as SignRawTransactionRequest)) as SignRawTransactionRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignRawTransactionRequest create() => SignRawTransactionRequest._(); @$core.override SignRawTransactionRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignRawTransactionRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SignRawTransactionRequest? _defaultInstance; /// The name of the wallet used for signing. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The raw transaction data to be signed. @$pb.TagNumber(2) $core.String get rawTransaction => $_getSZ(1); @$pb.TagNumber(2) set rawTransaction($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasRawTransaction() => $_has(1); @$pb.TagNumber(2) void clearRawTransaction() => $_clearField(2); /// Wallet password required for signing. @$pb.TagNumber(3) $core.String get password => $_getSZ(2); @$pb.TagNumber(3) set password($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasPassword() => $_has(2); @$pb.TagNumber(3) void clearPassword() => $_clearField(3); } /// Response message contains the transaction ID and signed raw transaction. class SignRawTransactionResponse extends $pb.GeneratedMessage { factory SignRawTransactionResponse({ $core.String? transactionId, $core.String? signedRawTransaction, }) { final result = create(); if (transactionId != null) result.transactionId = transactionId; if (signedRawTransaction != null) result.signedRawTransaction = signedRawTransaction; return result; } SignRawTransactionResponse._(); factory SignRawTransactionResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignRawTransactionResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignRawTransactionResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'transactionId') ..aOS(2, _omitFieldNames ? '' : 'signedRawTransaction') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignRawTransactionResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignRawTransactionResponse copyWith( void Function(SignRawTransactionResponse) updates) => super.copyWith( (message) => updates(message as SignRawTransactionResponse)) as SignRawTransactionResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignRawTransactionResponse create() => SignRawTransactionResponse._(); @$core.override SignRawTransactionResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignRawTransactionResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SignRawTransactionResponse? _defaultInstance; /// The ID of the signed transaction. @$pb.TagNumber(1) $core.String get transactionId => $_getSZ(0); @$pb.TagNumber(1) set transactionId($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasTransactionId() => $_has(0); @$pb.TagNumber(1) void clearTransactionId() => $_clearField(1); /// The signed raw transaction data. @$pb.TagNumber(2) $core.String get signedRawTransaction => $_getSZ(1); @$pb.TagNumber(2) set signedRawTransaction($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasSignedRawTransaction() => $_has(1); @$pb.TagNumber(2) void clearSignedRawTransaction() => $_clearField(2); } /// Request message for obtaining the total available balance of a wallet. class GetTotalBalanceRequest extends $pb.GeneratedMessage { factory GetTotalBalanceRequest({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } GetTotalBalanceRequest._(); factory GetTotalBalanceRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTotalBalanceRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTotalBalanceRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalBalanceRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalBalanceRequest copyWith( void Function(GetTotalBalanceRequest) updates) => super.copyWith((message) => updates(message as GetTotalBalanceRequest)) as GetTotalBalanceRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTotalBalanceRequest create() => GetTotalBalanceRequest._(); @$core.override GetTotalBalanceRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTotalBalanceRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTotalBalanceRequest? _defaultInstance; /// The name of the wallet to get the total balance. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Response message contains the total available balance of the wallet. class GetTotalBalanceResponse extends $pb.GeneratedMessage { factory GetTotalBalanceResponse({ $core.String? walletName, $fixnum.Int64? totalBalance, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (totalBalance != null) result.totalBalance = totalBalance; return result; } GetTotalBalanceResponse._(); factory GetTotalBalanceResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTotalBalanceResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTotalBalanceResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aInt64(2, _omitFieldNames ? '' : 'totalBalance') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalBalanceResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalBalanceResponse copyWith( void Function(GetTotalBalanceResponse) updates) => super.copyWith((message) => updates(message as GetTotalBalanceResponse)) as GetTotalBalanceResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTotalBalanceResponse create() => GetTotalBalanceResponse._(); @$core.override GetTotalBalanceResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTotalBalanceResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTotalBalanceResponse? _defaultInstance; /// The name of the queried wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The total balance of the wallet in NanoPAC. @$pb.TagNumber(2) $fixnum.Int64 get totalBalance => $_getI64(1); @$pb.TagNumber(2) set totalBalance($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasTotalBalance() => $_has(1); @$pb.TagNumber(2) void clearTotalBalance() => $_clearField(2); } /// Request message to sign an arbitrary message. class SignMessageRequest extends $pb.GeneratedMessage { factory SignMessageRequest({ $core.String? walletName, $core.String? password, $core.String? address, $core.String? message, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (password != null) result.password = password; if (address != null) result.address = address; if (message != null) result.message = message; return result; } SignMessageRequest._(); factory SignMessageRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignMessageRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignMessageRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'password') ..aOS(3, _omitFieldNames ? '' : 'address') ..aOS(4, _omitFieldNames ? '' : 'message') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageRequest copyWith(void Function(SignMessageRequest) updates) => super.copyWith((message) => updates(message as SignMessageRequest)) as SignMessageRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignMessageRequest create() => SignMessageRequest._(); @$core.override SignMessageRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignMessageRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SignMessageRequest? _defaultInstance; /// The name of the wallet to sign with. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Wallet password required for signing. @$pb.TagNumber(2) $core.String get password => $_getSZ(1); @$pb.TagNumber(2) set password($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPassword() => $_has(1); @$pb.TagNumber(2) void clearPassword() => $_clearField(2); /// The address whose private key should be used for signing the message. @$pb.TagNumber(3) $core.String get address => $_getSZ(2); @$pb.TagNumber(3) set address($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasAddress() => $_has(2); @$pb.TagNumber(3) void clearAddress() => $_clearField(3); /// The arbitrary message to be signed. @$pb.TagNumber(4) $core.String get message => $_getSZ(3); @$pb.TagNumber(4) set message($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasMessage() => $_has(3); @$pb.TagNumber(4) void clearMessage() => $_clearField(4); } /// Response message contains message signature. class SignMessageResponse extends $pb.GeneratedMessage { factory SignMessageResponse({ $core.String? signature, }) { final result = create(); if (signature != null) result.signature = signature; return result; } SignMessageResponse._(); factory SignMessageResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SignMessageResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SignMessageResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'signature') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SignMessageResponse copyWith(void Function(SignMessageResponse) updates) => super.copyWith((message) => updates(message as SignMessageResponse)) as SignMessageResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SignMessageResponse create() => SignMessageResponse._(); @$core.override SignMessageResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SignMessageResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SignMessageResponse? _defaultInstance; /// The signature in hexadecimal format. @$pb.TagNumber(1) $core.String get signature => $_getSZ(0); @$pb.TagNumber(1) set signature($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasSignature() => $_has(0); @$pb.TagNumber(1) void clearSignature() => $_clearField(1); } /// Request message for obtaining the total stake of a wallet. class GetTotalStakeRequest extends $pb.GeneratedMessage { factory GetTotalStakeRequest({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } GetTotalStakeRequest._(); factory GetTotalStakeRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTotalStakeRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTotalStakeRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalStakeRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalStakeRequest copyWith(void Function(GetTotalStakeRequest) updates) => super.copyWith((message) => updates(message as GetTotalStakeRequest)) as GetTotalStakeRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTotalStakeRequest create() => GetTotalStakeRequest._(); @$core.override GetTotalStakeRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTotalStakeRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTotalStakeRequest? _defaultInstance; /// The name of the wallet to get the total stake. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Response message contains the total stake of the wallet. class GetTotalStakeResponse extends $pb.GeneratedMessage { factory GetTotalStakeResponse({ $core.String? walletName, $fixnum.Int64? totalStake, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (totalStake != null) result.totalStake = totalStake; return result; } GetTotalStakeResponse._(); factory GetTotalStakeResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetTotalStakeResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetTotalStakeResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aInt64(2, _omitFieldNames ? '' : 'totalStake') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalStakeResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetTotalStakeResponse copyWith( void Function(GetTotalStakeResponse) updates) => super.copyWith((message) => updates(message as GetTotalStakeResponse)) as GetTotalStakeResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetTotalStakeResponse create() => GetTotalStakeResponse._(); @$core.override GetTotalStakeResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetTotalStakeResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetTotalStakeResponse? _defaultInstance; /// The name of the queried wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The total stake amount in NanoPAC. @$pb.TagNumber(2) $fixnum.Int64 get totalStake => $_getI64(1); @$pb.TagNumber(2) set totalStake($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasTotalStake() => $_has(1); @$pb.TagNumber(2) void clearTotalStake() => $_clearField(2); } /// Request message for getting address information. class GetAddressInfoRequest extends $pb.GeneratedMessage { factory GetAddressInfoRequest({ $core.String? walletName, $core.String? address, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (address != null) result.address = address; return result; } GetAddressInfoRequest._(); factory GetAddressInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetAddressInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetAddressInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAddressInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAddressInfoRequest copyWith( void Function(GetAddressInfoRequest) updates) => super.copyWith((message) => updates(message as GetAddressInfoRequest)) as GetAddressInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetAddressInfoRequest create() => GetAddressInfoRequest._(); @$core.override GetAddressInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetAddressInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetAddressInfoRequest? _defaultInstance; /// The name of the wallet containing the address. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The address to query. @$pb.TagNumber(2) $core.String get address => $_getSZ(1); @$pb.TagNumber(2) set address($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAddress() => $_has(1); @$pb.TagNumber(2) void clearAddress() => $_clearField(2); } /// Response message contains address details. class GetAddressInfoResponse extends $pb.GeneratedMessage { factory GetAddressInfoResponse({ $core.String? walletName, AddressInfo? addr, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (addr != null) result.addr = addr; return result; } GetAddressInfoResponse._(); factory GetAddressInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetAddressInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetAddressInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOM(2, _omitFieldNames ? '' : 'addr', subBuilder: AddressInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAddressInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetAddressInfoResponse copyWith( void Function(GetAddressInfoResponse) updates) => super.copyWith((message) => updates(message as GetAddressInfoResponse)) as GetAddressInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetAddressInfoResponse create() => GetAddressInfoResponse._(); @$core.override GetAddressInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetAddressInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetAddressInfoResponse? _defaultInstance; /// The name of the wallet containing the address. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Detailed information about the address. @$pb.TagNumber(2) AddressInfo get addr => $_getN(1); @$pb.TagNumber(2) set addr(AddressInfo value) => $_setField(2, value); @$pb.TagNumber(2) $core.bool hasAddr() => $_has(1); @$pb.TagNumber(2) void clearAddr() => $_clearField(2); @$pb.TagNumber(2) AddressInfo ensureAddr() => $_ensure(1); } /// Request message for setting address label. class SetAddressLabelRequest extends $pb.GeneratedMessage { factory SetAddressLabelRequest({ $core.String? walletName, $core.String? password, $core.String? address, $core.String? label, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (password != null) result.password = password; if (address != null) result.address = address; if (label != null) result.label = label; return result; } SetAddressLabelRequest._(); factory SetAddressLabelRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SetAddressLabelRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SetAddressLabelRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'password') ..aOS(3, _omitFieldNames ? '' : 'address') ..aOS(4, _omitFieldNames ? '' : 'label') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetAddressLabelRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetAddressLabelRequest copyWith( void Function(SetAddressLabelRequest) updates) => super.copyWith((message) => updates(message as SetAddressLabelRequest)) as SetAddressLabelRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SetAddressLabelRequest create() => SetAddressLabelRequest._(); @$core.override SetAddressLabelRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SetAddressLabelRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SetAddressLabelRequest? _defaultInstance; /// The name of the wallet containing the address. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Wallet password required for modification. @$pb.TagNumber(2) $core.String get password => $_getSZ(1); @$pb.TagNumber(2) set password($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPassword() => $_has(1); @$pb.TagNumber(2) void clearPassword() => $_clearField(2); /// The address to label. @$pb.TagNumber(3) $core.String get address => $_getSZ(2); @$pb.TagNumber(3) set address($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasAddress() => $_has(2); @$pb.TagNumber(3) void clearAddress() => $_clearField(3); /// The new label for the address. @$pb.TagNumber(4) $core.String get label => $_getSZ(3); @$pb.TagNumber(4) set label($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasLabel() => $_has(3); @$pb.TagNumber(4) void clearLabel() => $_clearField(4); } /// Response message for updated address label. class SetAddressLabelResponse extends $pb.GeneratedMessage { factory SetAddressLabelResponse({ $core.String? walletName, $core.String? address, $core.String? label, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (address != null) result.address = address; if (label != null) result.label = label; return result; } SetAddressLabelResponse._(); factory SetAddressLabelResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SetAddressLabelResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SetAddressLabelResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'address') ..aOS(3, _omitFieldNames ? '' : 'label') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetAddressLabelResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetAddressLabelResponse copyWith( void Function(SetAddressLabelResponse) updates) => super.copyWith((message) => updates(message as SetAddressLabelResponse)) as SetAddressLabelResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SetAddressLabelResponse create() => SetAddressLabelResponse._(); @$core.override SetAddressLabelResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SetAddressLabelResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SetAddressLabelResponse? _defaultInstance; /// The name of the wallet where the address label was updated. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The address where the label was updated. @$pb.TagNumber(2) $core.String get address => $_getSZ(1); @$pb.TagNumber(2) set address($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAddress() => $_has(1); @$pb.TagNumber(2) void clearAddress() => $_clearField(2); /// The new label for the address. @$pb.TagNumber(3) $core.String get label => $_getSZ(2); @$pb.TagNumber(3) set label($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasLabel() => $_has(2); @$pb.TagNumber(3) void clearLabel() => $_clearField(3); } /// Request message for listing wallets. class ListWalletsRequest extends $pb.GeneratedMessage { factory ListWalletsRequest() => create(); ListWalletsRequest._(); factory ListWalletsRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListWalletsRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListWalletsRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListWalletsRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListWalletsRequest copyWith(void Function(ListWalletsRequest) updates) => super.copyWith((message) => updates(message as ListWalletsRequest)) as ListWalletsRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListWalletsRequest create() => ListWalletsRequest._(); @$core.override ListWalletsRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListWalletsRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListWalletsRequest? _defaultInstance; } /// Response message contains wallet names. class ListWalletsResponse extends $pb.GeneratedMessage { factory ListWalletsResponse({ $core.Iterable<$core.String>? wallets, }) { final result = create(); if (wallets != null) result.wallets.addAll(wallets); return result; } ListWalletsResponse._(); factory ListWalletsResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListWalletsResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListWalletsResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..pPS(1, _omitFieldNames ? '' : 'wallets') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListWalletsResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListWalletsResponse copyWith(void Function(ListWalletsResponse) updates) => super.copyWith((message) => updates(message as ListWalletsResponse)) as ListWalletsResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListWalletsResponse create() => ListWalletsResponse._(); @$core.override ListWalletsResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListWalletsResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListWalletsResponse? _defaultInstance; /// Array of wallet names. @$pb.TagNumber(1) $pb.PbList<$core.String> get wallets => $_getList(0); } /// Request message for getting wallet information. class GetWalletInfoRequest extends $pb.GeneratedMessage { factory GetWalletInfoRequest({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } GetWalletInfoRequest._(); factory GetWalletInfoRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetWalletInfoRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetWalletInfoRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetWalletInfoRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetWalletInfoRequest copyWith(void Function(GetWalletInfoRequest) updates) => super.copyWith((message) => updates(message as GetWalletInfoRequest)) as GetWalletInfoRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetWalletInfoRequest create() => GetWalletInfoRequest._(); @$core.override GetWalletInfoRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetWalletInfoRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetWalletInfoRequest? _defaultInstance; /// The name of the wallet to query. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Response message contains wallet details. class GetWalletInfoResponse extends $pb.GeneratedMessage { factory GetWalletInfoResponse({ $core.String? walletName, $core.int? version, $core.String? network, $core.bool? encrypted, $core.String? uuid, $fixnum.Int64? createdAt, $fixnum.Int64? defaultFee, $core.String? driver, $core.String? path, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (version != null) result.version = version; if (network != null) result.network = network; if (encrypted != null) result.encrypted = encrypted; if (uuid != null) result.uuid = uuid; if (createdAt != null) result.createdAt = createdAt; if (defaultFee != null) result.defaultFee = defaultFee; if (driver != null) result.driver = driver; if (path != null) result.path = path; return result; } GetWalletInfoResponse._(); factory GetWalletInfoResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetWalletInfoResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetWalletInfoResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aI(2, _omitFieldNames ? '' : 'version') ..aOS(3, _omitFieldNames ? '' : 'network') ..aOB(4, _omitFieldNames ? '' : 'encrypted') ..aOS(5, _omitFieldNames ? '' : 'uuid') ..aInt64(6, _omitFieldNames ? '' : 'createdAt') ..aInt64(7, _omitFieldNames ? '' : 'defaultFee') ..aOS(8, _omitFieldNames ? '' : 'driver') ..aOS(9, _omitFieldNames ? '' : 'path') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetWalletInfoResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetWalletInfoResponse copyWith( void Function(GetWalletInfoResponse) updates) => super.copyWith((message) => updates(message as GetWalletInfoResponse)) as GetWalletInfoResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetWalletInfoResponse create() => GetWalletInfoResponse._(); @$core.override GetWalletInfoResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetWalletInfoResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetWalletInfoResponse? _defaultInstance; /// The name of the wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The wallet format version. @$pb.TagNumber(2) $core.int get version => $_getIZ(1); @$pb.TagNumber(2) set version($core.int value) => $_setSignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasVersion() => $_has(1); @$pb.TagNumber(2) void clearVersion() => $_clearField(2); /// The network the wallet is connected to (e.g., mainnet, testnet). @$pb.TagNumber(3) $core.String get network => $_getSZ(2); @$pb.TagNumber(3) set network($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasNetwork() => $_has(2); @$pb.TagNumber(3) void clearNetwork() => $_clearField(3); /// Indicates if the wallet is encrypted. @$pb.TagNumber(4) $core.bool get encrypted => $_getBF(3); @$pb.TagNumber(4) set encrypted($core.bool value) => $_setBool(3, value); @$pb.TagNumber(4) $core.bool hasEncrypted() => $_has(3); @$pb.TagNumber(4) void clearEncrypted() => $_clearField(4); /// A unique identifier of the wallet. @$pb.TagNumber(5) $core.String get uuid => $_getSZ(4); @$pb.TagNumber(5) set uuid($core.String value) => $_setString(4, value); @$pb.TagNumber(5) $core.bool hasUuid() => $_has(4); @$pb.TagNumber(5) void clearUuid() => $_clearField(5); /// Unix timestamp of wallet creation. @$pb.TagNumber(6) $fixnum.Int64 get createdAt => $_getI64(5); @$pb.TagNumber(6) set createdAt($fixnum.Int64 value) => $_setInt64(5, value); @$pb.TagNumber(6) $core.bool hasCreatedAt() => $_has(5); @$pb.TagNumber(6) void clearCreatedAt() => $_clearField(6); /// The default fee of the wallet. @$pb.TagNumber(7) $fixnum.Int64 get defaultFee => $_getI64(6); @$pb.TagNumber(7) set defaultFee($fixnum.Int64 value) => $_setInt64(6, value); @$pb.TagNumber(7) $core.bool hasDefaultFee() => $_has(6); @$pb.TagNumber(7) void clearDefaultFee() => $_clearField(7); /// The storage driver used by the wallet (e.g., SQLite, Legacy JSON ). @$pb.TagNumber(8) $core.String get driver => $_getSZ(7); @$pb.TagNumber(8) set driver($core.String value) => $_setString(7, value); @$pb.TagNumber(8) $core.bool hasDriver() => $_has(7); @$pb.TagNumber(8) void clearDriver() => $_clearField(8); /// Path to the wallet file or storage location. @$pb.TagNumber(9) $core.String get path => $_getSZ(8); @$pb.TagNumber(9) set path($core.String value) => $_setString(8, value); @$pb.TagNumber(9) $core.bool hasPath() => $_has(8); @$pb.TagNumber(9) void clearPath() => $_clearField(9); } /// Request message for listing wallet addresses. class ListAddressesRequest extends $pb.GeneratedMessage { factory ListAddressesRequest({ $core.String? walletName, $core.Iterable? addressTypes, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (addressTypes != null) result.addressTypes.addAll(addressTypes); return result; } ListAddressesRequest._(); factory ListAddressesRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListAddressesRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListAddressesRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..pc( 2, _omitFieldNames ? '' : 'addressTypes', $pb.PbFieldType.KE, valueOf: AddressType.valueOf, enumValues: AddressType.values, defaultEnumValue: AddressType.ADDRESS_TYPE_TREASURY) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListAddressesRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListAddressesRequest copyWith(void Function(ListAddressesRequest) updates) => super.copyWith((message) => updates(message as ListAddressesRequest)) as ListAddressesRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListAddressesRequest create() => ListAddressesRequest._(); @$core.override ListAddressesRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListAddressesRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListAddressesRequest? _defaultInstance; /// The name of the queried wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Filter addresses by their types. If empty, all address types are included. @$pb.TagNumber(2) $pb.PbList get addressTypes => $_getList(1); } /// Response message contains wallet addresses. class ListAddressesResponse extends $pb.GeneratedMessage { factory ListAddressesResponse({ $core.String? walletName, $core.Iterable? addrs, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (addrs != null) result.addrs.addAll(addrs); return result; } ListAddressesResponse._(); factory ListAddressesResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListAddressesResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListAddressesResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..pPM(2, _omitFieldNames ? '' : 'addrs', subBuilder: AddressInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListAddressesResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListAddressesResponse copyWith( void Function(ListAddressesResponse) updates) => super.copyWith((message) => updates(message as ListAddressesResponse)) as ListAddressesResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListAddressesResponse create() => ListAddressesResponse._(); @$core.override ListAddressesResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListAddressesResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListAddressesResponse? _defaultInstance; /// The name of the queried wallet. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// List of all addresses in the wallet with their details. @$pb.TagNumber(2) $pb.PbList get addrs => $_getList(1); } /// Request message for updating wallet password. class UpdatePasswordRequest extends $pb.GeneratedMessage { factory UpdatePasswordRequest({ $core.String? walletName, $core.String? oldPassword, $core.String? newPassword, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (oldPassword != null) result.oldPassword = oldPassword; if (newPassword != null) result.newPassword = newPassword; return result; } UpdatePasswordRequest._(); factory UpdatePasswordRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory UpdatePasswordRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'UpdatePasswordRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'oldPassword') ..aOS(3, _omitFieldNames ? '' : 'newPassword') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UpdatePasswordRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UpdatePasswordRequest copyWith( void Function(UpdatePasswordRequest) updates) => super.copyWith((message) => updates(message as UpdatePasswordRequest)) as UpdatePasswordRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static UpdatePasswordRequest create() => UpdatePasswordRequest._(); @$core.override UpdatePasswordRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static UpdatePasswordRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static UpdatePasswordRequest? _defaultInstance; /// The name of the wallet whose password will be updated. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The current wallet password. @$pb.TagNumber(2) $core.String get oldPassword => $_getSZ(1); @$pb.TagNumber(2) set oldPassword($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasOldPassword() => $_has(1); @$pb.TagNumber(2) void clearOldPassword() => $_clearField(2); /// The new wallet password. @$pb.TagNumber(3) $core.String get newPassword => $_getSZ(2); @$pb.TagNumber(3) set newPassword($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasNewPassword() => $_has(2); @$pb.TagNumber(3) void clearNewPassword() => $_clearField(3); } /// Response message confirming wallet password update. class UpdatePasswordResponse extends $pb.GeneratedMessage { factory UpdatePasswordResponse({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } UpdatePasswordResponse._(); factory UpdatePasswordResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory UpdatePasswordResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'UpdatePasswordResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UpdatePasswordResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') UpdatePasswordResponse copyWith( void Function(UpdatePasswordResponse) updates) => super.copyWith((message) => updates(message as UpdatePasswordResponse)) as UpdatePasswordResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static UpdatePasswordResponse create() => UpdatePasswordResponse._(); @$core.override UpdatePasswordResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static UpdatePasswordResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static UpdatePasswordResponse? _defaultInstance; /// The name of the wallet whose password was updated. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// WalletTransactionInfo contains information about a transaction in a wallet. class WalletTransactionInfo extends $pb.GeneratedMessage { factory WalletTransactionInfo({ $fixnum.Int64? no, $core.String? txId, $core.String? sender, $core.String? receiver, TxDirection? direction, $fixnum.Int64? amount, $fixnum.Int64? fee, $core.String? memo, TransactionStatus? status, $core.int? blockHeight, $0.PayloadType? payloadType, $core.List<$core.int>? data, $core.String? comment, $fixnum.Int64? createdAt, $fixnum.Int64? updatedAt, }) { final result = create(); if (no != null) result.no = no; if (txId != null) result.txId = txId; if (sender != null) result.sender = sender; if (receiver != null) result.receiver = receiver; if (direction != null) result.direction = direction; if (amount != null) result.amount = amount; if (fee != null) result.fee = fee; if (memo != null) result.memo = memo; if (status != null) result.status = status; if (blockHeight != null) result.blockHeight = blockHeight; if (payloadType != null) result.payloadType = payloadType; if (data != null) result.data = data; if (comment != null) result.comment = comment; if (createdAt != null) result.createdAt = createdAt; if (updatedAt != null) result.updatedAt = updatedAt; return result; } WalletTransactionInfo._(); factory WalletTransactionInfo.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory WalletTransactionInfo.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'WalletTransactionInfo', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'no') ..aOS(2, _omitFieldNames ? '' : 'txId') ..aOS(3, _omitFieldNames ? '' : 'sender') ..aOS(4, _omitFieldNames ? '' : 'receiver') ..aE(5, _omitFieldNames ? '' : 'direction', enumValues: TxDirection.values) ..aInt64(6, _omitFieldNames ? '' : 'amount') ..aInt64(7, _omitFieldNames ? '' : 'fee') ..aOS(8, _omitFieldNames ? '' : 'memo') ..aE(9, _omitFieldNames ? '' : 'status', enumValues: TransactionStatus.values) ..aI(10, _omitFieldNames ? '' : 'blockHeight', fieldType: $pb.PbFieldType.OU3) ..aE<$0.PayloadType>(11, _omitFieldNames ? '' : 'payloadType', enumValues: $0.PayloadType.values) ..a<$core.List<$core.int>>( 12, _omitFieldNames ? '' : 'data', $pb.PbFieldType.OY) ..aOS(13, _omitFieldNames ? '' : 'comment') ..aInt64(14, _omitFieldNames ? '' : 'createdAt') ..aInt64(15, _omitFieldNames ? '' : 'updatedAt') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') WalletTransactionInfo clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') WalletTransactionInfo copyWith( void Function(WalletTransactionInfo) updates) => super.copyWith((message) => updates(message as WalletTransactionInfo)) as WalletTransactionInfo; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static WalletTransactionInfo create() => WalletTransactionInfo._(); @$core.override WalletTransactionInfo createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static WalletTransactionInfo getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static WalletTransactionInfo? _defaultInstance; /// A sequence number for the transaction in the wallet. @$pb.TagNumber(1) $fixnum.Int64 get no => $_getI64(0); @$pb.TagNumber(1) set no($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasNo() => $_has(0); @$pb.TagNumber(1) void clearNo() => $_clearField(1); /// The unique ID of the transaction. @$pb.TagNumber(2) $core.String get txId => $_getSZ(1); @$pb.TagNumber(2) set txId($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasTxId() => $_has(1); @$pb.TagNumber(2) void clearTxId() => $_clearField(2); /// The sender's address. @$pb.TagNumber(3) $core.String get sender => $_getSZ(2); @$pb.TagNumber(3) set sender($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasSender() => $_has(2); @$pb.TagNumber(3) void clearSender() => $_clearField(3); /// The receiver's address. @$pb.TagNumber(4) $core.String get receiver => $_getSZ(3); @$pb.TagNumber(4) set receiver($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasReceiver() => $_has(3); @$pb.TagNumber(4) void clearReceiver() => $_clearField(4); /// The direction of the transaction relative to the wallet. @$pb.TagNumber(5) TxDirection get direction => $_getN(4); @$pb.TagNumber(5) set direction(TxDirection value) => $_setField(5, value); @$pb.TagNumber(5) $core.bool hasDirection() => $_has(4); @$pb.TagNumber(5) void clearDirection() => $_clearField(5); /// The amount involved in the transaction in NanoPAC. @$pb.TagNumber(6) $fixnum.Int64 get amount => $_getI64(5); @$pb.TagNumber(6) set amount($fixnum.Int64 value) => $_setInt64(5, value); @$pb.TagNumber(6) $core.bool hasAmount() => $_has(5); @$pb.TagNumber(6) void clearAmount() => $_clearField(6); /// The transaction fee in NanoPAC. @$pb.TagNumber(7) $fixnum.Int64 get fee => $_getI64(6); @$pb.TagNumber(7) set fee($fixnum.Int64 value) => $_setInt64(6, value); @$pb.TagNumber(7) $core.bool hasFee() => $_has(6); @$pb.TagNumber(7) void clearFee() => $_clearField(7); /// A memo string for the transaction. @$pb.TagNumber(8) $core.String get memo => $_getSZ(7); @$pb.TagNumber(8) set memo($core.String value) => $_setString(7, value); @$pb.TagNumber(8) $core.bool hasMemo() => $_has(7); @$pb.TagNumber(8) void clearMemo() => $_clearField(8); /// The current status of the transaction. @$pb.TagNumber(9) TransactionStatus get status => $_getN(8); @$pb.TagNumber(9) set status(TransactionStatus value) => $_setField(9, value); @$pb.TagNumber(9) $core.bool hasStatus() => $_has(8); @$pb.TagNumber(9) void clearStatus() => $_clearField(9); /// The block height containing the transaction. @$pb.TagNumber(10) $core.int get blockHeight => $_getIZ(9); @$pb.TagNumber(10) set blockHeight($core.int value) => $_setUnsignedInt32(9, value); @$pb.TagNumber(10) $core.bool hasBlockHeight() => $_has(9); @$pb.TagNumber(10) void clearBlockHeight() => $_clearField(10); /// The type of transaction payload. @$pb.TagNumber(11) $0.PayloadType get payloadType => $_getN(10); @$pb.TagNumber(11) set payloadType($0.PayloadType value) => $_setField(11, value); @$pb.TagNumber(11) $core.bool hasPayloadType() => $_has(10); @$pb.TagNumber(11) void clearPayloadType() => $_clearField(11); /// The raw transaction data. @$pb.TagNumber(12) $core.List<$core.int> get data => $_getN(11); @$pb.TagNumber(12) set data($core.List<$core.int> value) => $_setBytes(11, value); @$pb.TagNumber(12) $core.bool hasData() => $_has(11); @$pb.TagNumber(12) void clearData() => $_clearField(12); /// A comment associated with the transaction in the wallet. @$pb.TagNumber(13) $core.String get comment => $_getSZ(12); @$pb.TagNumber(13) set comment($core.String value) => $_setString(12, value); @$pb.TagNumber(13) $core.bool hasComment() => $_has(12); @$pb.TagNumber(13) void clearComment() => $_clearField(13); /// Unix timestamp of when the transaction was created. @$pb.TagNumber(14) $fixnum.Int64 get createdAt => $_getI64(13); @$pb.TagNumber(14) set createdAt($fixnum.Int64 value) => $_setInt64(13, value); @$pb.TagNumber(14) $core.bool hasCreatedAt() => $_has(13); @$pb.TagNumber(14) void clearCreatedAt() => $_clearField(14); /// Unix timestamp of when the transaction was last updated. @$pb.TagNumber(15) $fixnum.Int64 get updatedAt => $_getI64(14); @$pb.TagNumber(15) set updatedAt($fixnum.Int64 value) => $_setInt64(14, value); @$pb.TagNumber(15) $core.bool hasUpdatedAt() => $_has(14); @$pb.TagNumber(15) void clearUpdatedAt() => $_clearField(15); } /// Request message for listing transactions of a wallet, optionally filtered by a specific address. class ListTransactionsRequest extends $pb.GeneratedMessage { factory ListTransactionsRequest({ $core.String? walletName, $core.String? address, TxDirection? direction, $core.int? count, $core.int? skip, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (address != null) result.address = address; if (direction != null) result.direction = direction; if (count != null) result.count = count; if (skip != null) result.skip = skip; return result; } ListTransactionsRequest._(); factory ListTransactionsRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListTransactionsRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListTransactionsRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'address') ..aE(3, _omitFieldNames ? '' : 'direction', enumValues: TxDirection.values) ..aI(4, _omitFieldNames ? '' : 'count') ..aI(5, _omitFieldNames ? '' : 'skip') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListTransactionsRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListTransactionsRequest copyWith( void Function(ListTransactionsRequest) updates) => super.copyWith((message) => updates(message as ListTransactionsRequest)) as ListTransactionsRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListTransactionsRequest create() => ListTransactionsRequest._(); @$core.override ListTransactionsRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListTransactionsRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListTransactionsRequest? _defaultInstance; /// The name of the wallet to query transactions for. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Optional: The address to filter transactions. /// If empty or set to '*', transactions for all addresses in the wallet are included. @$pb.TagNumber(2) $core.String get address => $_getSZ(1); @$pb.TagNumber(2) set address($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasAddress() => $_has(1); @$pb.TagNumber(2) void clearAddress() => $_clearField(2); /// Filter transactions by direction relative to the wallet. /// Defaults to any direction if not set. @$pb.TagNumber(3) TxDirection get direction => $_getN(2); @$pb.TagNumber(3) set direction(TxDirection value) => $_setField(3, value); @$pb.TagNumber(3) $core.bool hasDirection() => $_has(2); @$pb.TagNumber(3) void clearDirection() => $_clearField(3); /// Optional: The maximum number of transactions to return. /// Defaults to 10 if not set. @$pb.TagNumber(4) $core.int get count => $_getIZ(3); @$pb.TagNumber(4) set count($core.int value) => $_setSignedInt32(3, value); @$pb.TagNumber(4) $core.bool hasCount() => $_has(3); @$pb.TagNumber(4) void clearCount() => $_clearField(4); /// Optional: The number of transactions to skip (for pagination). /// Defaults to 0 if not set. @$pb.TagNumber(5) $core.int get skip => $_getIZ(4); @$pb.TagNumber(5) set skip($core.int value) => $_setSignedInt32(4, value); @$pb.TagNumber(5) $core.bool hasSkip() => $_has(4); @$pb.TagNumber(5) void clearSkip() => $_clearField(5); } /// Response message containing a list of transactions. class ListTransactionsResponse extends $pb.GeneratedMessage { factory ListTransactionsResponse({ $core.String? walletName, $core.Iterable? txs, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (txs != null) result.txs.addAll(txs); return result; } ListTransactionsResponse._(); factory ListTransactionsResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListTransactionsResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListTransactionsResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..pPM(2, _omitFieldNames ? '' : 'txs', subBuilder: WalletTransactionInfo.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListTransactionsResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListTransactionsResponse copyWith( void Function(ListTransactionsResponse) updates) => super.copyWith((message) => updates(message as ListTransactionsResponse)) as ListTransactionsResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListTransactionsResponse create() => ListTransactionsResponse._(); @$core.override ListTransactionsResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListTransactionsResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListTransactionsResponse? _defaultInstance; /// The name of the wallet queried. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// List of transactions for the wallet, filtered by the specified address if provided. @$pb.TagNumber(2) $pb.PbList get txs => $_getList(1); } /// Request message for setting default fee. class SetDefaultFeeRequest extends $pb.GeneratedMessage { factory SetDefaultFeeRequest({ $core.String? walletName, $fixnum.Int64? amount, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (amount != null) result.amount = amount; return result; } SetDefaultFeeRequest._(); factory SetDefaultFeeRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SetDefaultFeeRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SetDefaultFeeRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aInt64(2, _omitFieldNames ? '' : 'amount') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetDefaultFeeRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetDefaultFeeRequest copyWith(void Function(SetDefaultFeeRequest) updates) => super.copyWith((message) => updates(message as SetDefaultFeeRequest)) as SetDefaultFeeRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SetDefaultFeeRequest create() => SetDefaultFeeRequest._(); @$core.override SetDefaultFeeRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SetDefaultFeeRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SetDefaultFeeRequest? _defaultInstance; /// The name of the wallet to set the default fee. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// The default fee amount in NanoPAC. @$pb.TagNumber(2) $fixnum.Int64 get amount => $_getI64(1); @$pb.TagNumber(2) set amount($fixnum.Int64 value) => $_setInt64(1, value); @$pb.TagNumber(2) $core.bool hasAmount() => $_has(1); @$pb.TagNumber(2) void clearAmount() => $_clearField(2); } /// Response message for updated default fee. class SetDefaultFeeResponse extends $pb.GeneratedMessage { factory SetDefaultFeeResponse({ $core.String? walletName, }) { final result = create(); if (walletName != null) result.walletName = walletName; return result; } SetDefaultFeeResponse._(); factory SetDefaultFeeResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SetDefaultFeeResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SetDefaultFeeResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetDefaultFeeResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SetDefaultFeeResponse copyWith( void Function(SetDefaultFeeResponse) updates) => super.copyWith((message) => updates(message as SetDefaultFeeResponse)) as SetDefaultFeeResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SetDefaultFeeResponse create() => SetDefaultFeeResponse._(); @$core.override SetDefaultFeeResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SetDefaultFeeResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SetDefaultFeeResponse? _defaultInstance; /// The name of the wallet where the default fee was updated. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); } /// Request message for getting mnemonic. class GetMnemonicRequest extends $pb.GeneratedMessage { factory GetMnemonicRequest({ $core.String? walletName, $core.String? password, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (password != null) result.password = password; return result; } GetMnemonicRequest._(); factory GetMnemonicRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetMnemonicRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetMnemonicRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'password') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetMnemonicRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetMnemonicRequest copyWith(void Function(GetMnemonicRequest) updates) => super.copyWith((message) => updates(message as GetMnemonicRequest)) as GetMnemonicRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetMnemonicRequest create() => GetMnemonicRequest._(); @$core.override GetMnemonicRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetMnemonicRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetMnemonicRequest? _defaultInstance; /// The name of the wallet to get the mnemonic. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Wallet password. @$pb.TagNumber(2) $core.String get password => $_getSZ(1); @$pb.TagNumber(2) set password($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPassword() => $_has(1); @$pb.TagNumber(2) void clearPassword() => $_clearField(2); } /// Response message contains mnemonic. class GetMnemonicResponse extends $pb.GeneratedMessage { factory GetMnemonicResponse({ $core.String? mnemonic, }) { final result = create(); if (mnemonic != null) result.mnemonic = mnemonic; return result; } GetMnemonicResponse._(); factory GetMnemonicResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetMnemonicResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetMnemonicResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'mnemonic') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetMnemonicResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetMnemonicResponse copyWith(void Function(GetMnemonicResponse) updates) => super.copyWith((message) => updates(message as GetMnemonicResponse)) as GetMnemonicResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetMnemonicResponse create() => GetMnemonicResponse._(); @$core.override GetMnemonicResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetMnemonicResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetMnemonicResponse? _defaultInstance; /// The mnemonic (seed phrase). @$pb.TagNumber(1) $core.String get mnemonic => $_getSZ(0); @$pb.TagNumber(1) set mnemonic($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasMnemonic() => $_has(0); @$pb.TagNumber(1) void clearMnemonic() => $_clearField(1); } /// Request message for getting private key. class GetPrivateKeyRequest extends $pb.GeneratedMessage { factory GetPrivateKeyRequest({ $core.String? walletName, $core.String? password, $core.String? address, }) { final result = create(); if (walletName != null) result.walletName = walletName; if (password != null) result.password = password; if (address != null) result.address = address; return result; } GetPrivateKeyRequest._(); factory GetPrivateKeyRequest.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetPrivateKeyRequest.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetPrivateKeyRequest', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'walletName') ..aOS(2, _omitFieldNames ? '' : 'password') ..aOS(3, _omitFieldNames ? '' : 'address') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPrivateKeyRequest clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPrivateKeyRequest copyWith(void Function(GetPrivateKeyRequest) updates) => super.copyWith((message) => updates(message as GetPrivateKeyRequest)) as GetPrivateKeyRequest; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetPrivateKeyRequest create() => GetPrivateKeyRequest._(); @$core.override GetPrivateKeyRequest createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetPrivateKeyRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetPrivateKeyRequest? _defaultInstance; /// The name of the wallet containing the address. @$pb.TagNumber(1) $core.String get walletName => $_getSZ(0); @$pb.TagNumber(1) set walletName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasWalletName() => $_has(0); @$pb.TagNumber(1) void clearWalletName() => $_clearField(1); /// Wallet password. @$pb.TagNumber(2) $core.String get password => $_getSZ(1); @$pb.TagNumber(2) set password($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasPassword() => $_has(1); @$pb.TagNumber(2) void clearPassword() => $_clearField(2); /// The address to get the private key. @$pb.TagNumber(3) $core.String get address => $_getSZ(2); @$pb.TagNumber(3) set address($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasAddress() => $_has(2); @$pb.TagNumber(3) void clearAddress() => $_clearField(3); } /// Response message contains private key. class GetPrivateKeyResponse extends $pb.GeneratedMessage { factory GetPrivateKeyResponse({ $core.String? privateKey, }) { final result = create(); if (privateKey != null) result.privateKey = privateKey; return result; } GetPrivateKeyResponse._(); factory GetPrivateKeyResponse.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory GetPrivateKeyResponse.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'GetPrivateKeyResponse', package: const $pb.PackageName(_omitMessageNames ? '' : 'pactus'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'privateKey') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPrivateKeyResponse clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') GetPrivateKeyResponse copyWith( void Function(GetPrivateKeyResponse) updates) => super.copyWith((message) => updates(message as GetPrivateKeyResponse)) as GetPrivateKeyResponse; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static GetPrivateKeyResponse create() => GetPrivateKeyResponse._(); @$core.override GetPrivateKeyResponse createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static GetPrivateKeyResponse getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static GetPrivateKeyResponse? _defaultInstance; /// The private key in hexadecimal format. @$pb.TagNumber(1) $core.String get privateKey => $_getSZ(0); @$pb.TagNumber(1) set privateKey($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasPrivateKey() => $_has(0); @$pb.TagNumber(1) void clearPrivateKey() => $_clearField(1); } /// Wallet service provides RPC methods for wallet management operations. class WalletApi { final $pb.RpcClient _client; WalletApi(this._client); /// CreateWallet creates a new wallet with the specified parameters. $async.Future createWallet( $pb.ClientContext? ctx, CreateWalletRequest request) => _client.invoke( ctx, 'Wallet', 'CreateWallet', request, CreateWalletResponse()); /// RestoreWallet restores an existing wallet with the given mnemonic. $async.Future restoreWallet( $pb.ClientContext? ctx, RestoreWalletRequest request) => _client.invoke( ctx, 'Wallet', 'RestoreWallet', request, RestoreWalletResponse()); /// LoadWallet loads an existing wallet with the given name. /// deprecated: It will be removed in a future version. $async.Future loadWallet( $pb.ClientContext? ctx, LoadWalletRequest request) => _client.invoke( ctx, 'Wallet', 'LoadWallet', request, LoadWalletResponse()); /// UnloadWallet unloads a currently loaded wallet with the specified name. /// deprecated: It will be removed in a future version. $async.Future unloadWallet( $pb.ClientContext? ctx, UnloadWalletRequest request) => _client.invoke( ctx, 'Wallet', 'UnloadWallet', request, UnloadWalletResponse()); /// ListWallets returns a list of all available wallets. $async.Future listWallets( $pb.ClientContext? ctx, ListWalletsRequest request) => _client.invoke( ctx, 'Wallet', 'ListWallets', request, ListWalletsResponse()); /// GetWalletInfo returns detailed information about a specific wallet. $async.Future getWalletInfo( $pb.ClientContext? ctx, GetWalletInfoRequest request) => _client.invoke( ctx, 'Wallet', 'GetWalletInfo', request, GetWalletInfoResponse()); /// UpdatePassword updates the password of an existing wallet. $async.Future updatePassword( $pb.ClientContext? ctx, UpdatePasswordRequest request) => _client.invoke( ctx, 'Wallet', 'UpdatePassword', request, UpdatePasswordResponse()); /// GetTotalBalance returns the total available balance of the wallet. $async.Future getTotalBalance( $pb.ClientContext? ctx, GetTotalBalanceRequest request) => _client.invoke( ctx, 'Wallet', 'GetTotalBalance', request, GetTotalBalanceResponse()); /// GetTotalStake returns the total stake amount in the wallet. $async.Future getTotalStake( $pb.ClientContext? ctx, GetTotalStakeRequest request) => _client.invoke( ctx, 'Wallet', 'GetTotalStake', request, GetTotalStakeResponse()); /// GetValidatorAddress retrieves the validator address associated with a public key. /// Deprecated: Will move into utils. $async.Future getValidatorAddress( $pb.ClientContext? ctx, GetValidatorAddressRequest request) => _client.invoke(ctx, 'Wallet', 'GetValidatorAddress', request, GetValidatorAddressResponse()); /// GetAddressInfo returns detailed information about a specific address. $async.Future getAddressInfo( $pb.ClientContext? ctx, GetAddressInfoRequest request) => _client.invoke( ctx, 'Wallet', 'GetAddressInfo', request, GetAddressInfoResponse()); /// SetAddressLabel sets or updates the label for a given address. $async.Future setAddressLabel( $pb.ClientContext? ctx, SetAddressLabelRequest request) => _client.invoke( ctx, 'Wallet', 'SetAddressLabel', request, SetAddressLabelResponse()); /// GetNewAddress generates a new address for the specified wallet. $async.Future getNewAddress( $pb.ClientContext? ctx, GetNewAddressRequest request) => _client.invoke( ctx, 'Wallet', 'GetNewAddress', request, GetNewAddressResponse()); /// ListAddresses returns all addresses in the specified wallet. $async.Future listAddresses( $pb.ClientContext? ctx, ListAddressesRequest request) => _client.invoke( ctx, 'Wallet', 'ListAddresses', request, ListAddressesResponse()); /// SignMessage signs an arbitrary message using a wallet's private key. $async.Future signMessage( $pb.ClientContext? ctx, SignMessageRequest request) => _client.invoke( ctx, 'Wallet', 'SignMessage', request, SignMessageResponse()); /// SignRawTransaction signs a raw transaction for a specified wallet. $async.Future signRawTransaction( $pb.ClientContext? ctx, SignRawTransactionRequest request) => _client.invoke(ctx, 'Wallet', 'SignRawTransaction', request, SignRawTransactionResponse()); /// ListTransactions returns a list of transactions for a wallet, /// optionally filtered by a specific address, with pagination support. $async.Future listTransactions( $pb.ClientContext? ctx, ListTransactionsRequest request) => _client.invoke(ctx, 'Wallet', 'ListTransactions', request, ListTransactionsResponse()); /// SetDefaultFee sets the default fee for the wallet. $async.Future setDefaultFee( $pb.ClientContext? ctx, SetDefaultFeeRequest request) => _client.invoke( ctx, 'Wallet', 'SetDefaultFee', request, SetDefaultFeeResponse()); /// GetMnemonic returns the mnemonic (seed phrase) for the wallet. $async.Future getMnemonic( $pb.ClientContext? ctx, GetMnemonicRequest request) => _client.invoke( ctx, 'Wallet', 'GetMnemonic', request, GetMnemonicResponse()); /// GetPrivateKey returns the private key for a given address. $async.Future getPrivateKey( $pb.ClientContext? ctx, GetPrivateKeyRequest request) => _client.invoke( ctx, 'Wallet', 'GetPrivateKey', request, GetPrivateKeyResponse()); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: www/grpc/gen/dart/wallet.pbenum.dart ================================================ // This is a generated file - do not edit. // // Generated from wallet.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; /// AddressType defines different types of blockchain addresses. class AddressType extends $pb.ProtobufEnum { /// Treasury address type. /// Should not be used to generate new addresses. static const AddressType ADDRESS_TYPE_TREASURY = AddressType._(0, _omitEnumNames ? '' : 'ADDRESS_TYPE_TREASURY'); /// Validator address type used for validator nodes. static const AddressType ADDRESS_TYPE_VALIDATOR = AddressType._(1, _omitEnumNames ? '' : 'ADDRESS_TYPE_VALIDATOR'); /// Account address type with BLS signature scheme. static const AddressType ADDRESS_TYPE_BLS_ACCOUNT = AddressType._(2, _omitEnumNames ? '' : 'ADDRESS_TYPE_BLS_ACCOUNT'); /// Account address type with Ed25519 signature scheme. /// Note: Generating a new Ed25519 address requires the wallet password. static const AddressType ADDRESS_TYPE_ED25519_ACCOUNT = AddressType._(3, _omitEnumNames ? '' : 'ADDRESS_TYPE_ED25519_ACCOUNT'); static const $core.List values = [ ADDRESS_TYPE_TREASURY, ADDRESS_TYPE_VALIDATOR, ADDRESS_TYPE_BLS_ACCOUNT, ADDRESS_TYPE_ED25519_ACCOUNT, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 3); static AddressType? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const AddressType._(super.value, super.name); } /// TxDirection indicates the direction of a transaction relative to the wallet. class TxDirection extends $pb.ProtobufEnum { /// include both incoming and outgoing transactions. static const TxDirection TX_DIRECTION_ANY = TxDirection._(0, _omitEnumNames ? '' : 'TX_DIRECTION_ANY'); /// Include only incoming transactions where the wallet receives funds. static const TxDirection TX_DIRECTION_INCOMING = TxDirection._(1, _omitEnumNames ? '' : 'TX_DIRECTION_INCOMING'); /// Include only outgoing transactions where the wallet sends funds. static const TxDirection TX_DIRECTION_OUTGOING = TxDirection._(2, _omitEnumNames ? '' : 'TX_DIRECTION_OUTGOING'); static const $core.List values = [ TX_DIRECTION_ANY, TX_DIRECTION_INCOMING, TX_DIRECTION_OUTGOING, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 2); static TxDirection? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const TxDirection._(super.value, super.name); } /// TransactionStatus defines the status of a transaction. class TransactionStatus extends $pb.ProtobufEnum { /// Pending status for transactions in the mempool. static const TransactionStatus TRANSACTION_STATUS_PENDING = TransactionStatus._( 0, _omitEnumNames ? '' : 'TRANSACTION_STATUS_PENDING'); /// Confirmed status for transactions included in a block. static const TransactionStatus TRANSACTION_STATUS_CONFIRMED = TransactionStatus._( 1, _omitEnumNames ? '' : 'TRANSACTION_STATUS_CONFIRMED'); /// Failed status for transactions that were not successful. static const TransactionStatus TRANSACTION_STATUS_FAILED = TransactionStatus._( -1, _omitEnumNames ? '' : 'TRANSACTION_STATUS_FAILED'); static const $core.List values = [ TRANSACTION_STATUS_PENDING, TRANSACTION_STATUS_CONFIRMED, TRANSACTION_STATUS_FAILED, ]; static final $core.Map<$core.int, TransactionStatus> _byValue = $pb.ProtobufEnum.initByValue(values); static TransactionStatus? valueOf($core.int value) => _byValue[value]; const TransactionStatus._(super.value, super.name); } const $core.bool _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names'); ================================================ FILE: www/grpc/gen/dart/wallet.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from wallet.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use addressTypeDescriptor instead') const AddressType$json = { '1': 'AddressType', '2': [ {'1': 'ADDRESS_TYPE_TREASURY', '2': 0}, {'1': 'ADDRESS_TYPE_VALIDATOR', '2': 1}, {'1': 'ADDRESS_TYPE_BLS_ACCOUNT', '2': 2}, {'1': 'ADDRESS_TYPE_ED25519_ACCOUNT', '2': 3}, ], }; /// Descriptor for `AddressType`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List addressTypeDescriptor = $convert.base64Decode( 'CgtBZGRyZXNzVHlwZRIZChVBRERSRVNTX1RZUEVfVFJFQVNVUlkQABIaChZBRERSRVNTX1RZUE' 'VfVkFMSURBVE9SEAESHAoYQUREUkVTU19UWVBFX0JMU19BQ0NPVU5UEAISIAocQUREUkVTU19U' 'WVBFX0VEMjU1MTlfQUNDT1VOVBAD'); @$core.Deprecated('Use txDirectionDescriptor instead') const TxDirection$json = { '1': 'TxDirection', '2': [ {'1': 'TX_DIRECTION_ANY', '2': 0}, {'1': 'TX_DIRECTION_INCOMING', '2': 1}, {'1': 'TX_DIRECTION_OUTGOING', '2': 2}, ], }; /// Descriptor for `TxDirection`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List txDirectionDescriptor = $convert.base64Decode( 'CgtUeERpcmVjdGlvbhIUChBUWF9ESVJFQ1RJT05fQU5ZEAASGQoVVFhfRElSRUNUSU9OX0lOQ0' '9NSU5HEAESGQoVVFhfRElSRUNUSU9OX09VVEdPSU5HEAI='); @$core.Deprecated('Use transactionStatusDescriptor instead') const TransactionStatus$json = { '1': 'TransactionStatus', '2': [ {'1': 'TRANSACTION_STATUS_PENDING', '2': 0}, {'1': 'TRANSACTION_STATUS_CONFIRMED', '2': 1}, {'1': 'TRANSACTION_STATUS_FAILED', '2': -1}, ], }; /// Descriptor for `TransactionStatus`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List transactionStatusDescriptor = $convert.base64Decode( 'ChFUcmFuc2FjdGlvblN0YXR1cxIeChpUUkFOU0FDVElPTl9TVEFUVVNfUEVORElORxAAEiAKHF' 'RSQU5TQUNUSU9OX1NUQVRVU19DT05GSVJNRUQQARImChlUUkFOU0FDVElPTl9TVEFUVVNfRkFJ' 'TEVEEP///////////wE='); @$core.Deprecated('Use addressInfoDescriptor instead') const AddressInfo$json = { '1': 'AddressInfo', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, {'1': 'public_key', '3': 2, '4': 1, '5': 9, '10': 'publicKey'}, {'1': 'label', '3': 3, '4': 1, '5': 9, '10': 'label'}, {'1': 'path', '3': 4, '4': 1, '5': 9, '10': 'path'}, ], }; /// Descriptor for `AddressInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List addressInfoDescriptor = $convert.base64Decode( 'CgtBZGRyZXNzSW5mbxIYCgdhZGRyZXNzGAEgASgJUgdhZGRyZXNzEh0KCnB1YmxpY19rZXkYAi' 'ABKAlSCXB1YmxpY0tleRIUCgVsYWJlbBgDIAEoCVIFbGFiZWwSEgoEcGF0aBgEIAEoCVIEcGF0' 'aA=='); @$core.Deprecated('Use getNewAddressRequestDescriptor instead') const GetNewAddressRequest$json = { '1': 'GetNewAddressRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, { '1': 'address_type', '3': 2, '4': 1, '5': 14, '6': '.pactus.AddressType', '10': 'addressType' }, {'1': 'label', '3': 3, '4': 1, '5': 9, '10': 'label'}, {'1': 'password', '3': 4, '4': 1, '5': 9, '10': 'password'}, ], }; /// Descriptor for `GetNewAddressRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getNewAddressRequestDescriptor = $convert.base64Decode( 'ChRHZXROZXdBZGRyZXNzUmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZR' 'I2CgxhZGRyZXNzX3R5cGUYAiABKA4yEy5wYWN0dXMuQWRkcmVzc1R5cGVSC2FkZHJlc3NUeXBl' 'EhQKBWxhYmVsGAMgASgJUgVsYWJlbBIaCghwYXNzd29yZBgEIAEoCVIIcGFzc3dvcmQ='); @$core.Deprecated('Use getNewAddressResponseDescriptor instead') const GetNewAddressResponse$json = { '1': 'GetNewAddressResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, { '1': 'addr', '3': 2, '4': 1, '5': 11, '6': '.pactus.AddressInfo', '10': 'addr' }, ], }; /// Descriptor for `GetNewAddressResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getNewAddressResponseDescriptor = $convert.base64Decode( 'ChVHZXROZXdBZGRyZXNzUmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'USJwoEYWRkchgCIAEoCzITLnBhY3R1cy5BZGRyZXNzSW5mb1IEYWRkcg=='); @$core.Deprecated('Use restoreWalletRequestDescriptor instead') const RestoreWalletRequest$json = { '1': 'RestoreWalletRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'mnemonic', '3': 2, '4': 1, '5': 9, '10': 'mnemonic'}, {'1': 'password', '3': 3, '4': 1, '5': 9, '10': 'password'}, ], }; /// Descriptor for `RestoreWalletRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List restoreWalletRequestDescriptor = $convert.base64Decode( 'ChRSZXN0b3JlV2FsbGV0UmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZR' 'IaCghtbmVtb25pYxgCIAEoCVIIbW5lbW9uaWMSGgoIcGFzc3dvcmQYAyABKAlSCHBhc3N3b3Jk'); @$core.Deprecated('Use restoreWalletResponseDescriptor instead') const RestoreWalletResponse$json = { '1': 'RestoreWalletResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `RestoreWalletResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List restoreWalletResponseDescriptor = $convert.base64Decode( 'ChVSZXN0b3JlV2FsbGV0UmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'U='); @$core.Deprecated('Use createWalletRequestDescriptor instead') const CreateWalletRequest$json = { '1': 'CreateWalletRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'password', '3': 2, '4': 1, '5': 9, '10': 'password'}, ], }; /// Descriptor for `CreateWalletRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List createWalletRequestDescriptor = $convert.base64Decode( 'ChNDcmVhdGVXYWxsZXRSZXF1ZXN0Eh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZXROYW1lEh' 'oKCHBhc3N3b3JkGAIgASgJUghwYXNzd29yZA=='); @$core.Deprecated('Use createWalletResponseDescriptor instead') const CreateWalletResponse$json = { '1': 'CreateWalletResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'mnemonic', '3': 2, '4': 1, '5': 9, '10': 'mnemonic'}, ], }; /// Descriptor for `CreateWalletResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List createWalletResponseDescriptor = $convert.base64Decode( 'ChRDcmVhdGVXYWxsZXRSZXNwb25zZRIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZR' 'IaCghtbmVtb25pYxgCIAEoCVIIbW5lbW9uaWM='); @$core.Deprecated('Use loadWalletRequestDescriptor instead') const LoadWalletRequest$json = { '1': 'LoadWalletRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `LoadWalletRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List loadWalletRequestDescriptor = $convert.base64Decode( 'ChFMb2FkV2FsbGV0UmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZQ=='); @$core.Deprecated('Use loadWalletResponseDescriptor instead') const LoadWalletResponse$json = { '1': 'LoadWalletResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `LoadWalletResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List loadWalletResponseDescriptor = $convert.base64Decode( 'ChJMb2FkV2FsbGV0UmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbWU='); @$core.Deprecated('Use unloadWalletRequestDescriptor instead') const UnloadWalletRequest$json = { '1': 'UnloadWalletRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `UnloadWalletRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List unloadWalletRequestDescriptor = $convert.base64Decode( 'ChNVbmxvYWRXYWxsZXRSZXF1ZXN0Eh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZXROYW1l'); @$core.Deprecated('Use unloadWalletResponseDescriptor instead') const UnloadWalletResponse$json = { '1': 'UnloadWalletResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `UnloadWalletResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List unloadWalletResponseDescriptor = $convert.base64Decode( 'ChRVbmxvYWRXYWxsZXRSZXNwb25zZRIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZQ' '=='); @$core.Deprecated('Use getValidatorAddressRequestDescriptor instead') const GetValidatorAddressRequest$json = { '1': 'GetValidatorAddressRequest', '2': [ {'1': 'public_key', '3': 1, '4': 1, '5': 9, '10': 'publicKey'}, ], }; /// Descriptor for `GetValidatorAddressRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorAddressRequestDescriptor = $convert.base64Decode( 'ChpHZXRWYWxpZGF0b3JBZGRyZXNzUmVxdWVzdBIdCgpwdWJsaWNfa2V5GAEgASgJUglwdWJsaW' 'NLZXk='); @$core.Deprecated('Use getValidatorAddressResponseDescriptor instead') const GetValidatorAddressResponse$json = { '1': 'GetValidatorAddressResponse', '2': [ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `GetValidatorAddressResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getValidatorAddressResponseDescriptor = $convert.base64Decode( 'ChtHZXRWYWxpZGF0b3JBZGRyZXNzUmVzcG9uc2USGAoHYWRkcmVzcxgBIAEoCVIHYWRkcmVzcw' '=='); @$core.Deprecated('Use signRawTransactionRequestDescriptor instead') const SignRawTransactionRequest$json = { '1': 'SignRawTransactionRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'raw_transaction', '3': 2, '4': 1, '5': 9, '10': 'rawTransaction'}, {'1': 'password', '3': 3, '4': 1, '5': 9, '10': 'password'}, ], }; /// Descriptor for `SignRawTransactionRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signRawTransactionRequestDescriptor = $convert.base64Decode( 'ChlTaWduUmF3VHJhbnNhY3Rpb25SZXF1ZXN0Eh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZX' 'ROYW1lEicKD3Jhd190cmFuc2FjdGlvbhgCIAEoCVIOcmF3VHJhbnNhY3Rpb24SGgoIcGFzc3dv' 'cmQYAyABKAlSCHBhc3N3b3Jk'); @$core.Deprecated('Use signRawTransactionResponseDescriptor instead') const SignRawTransactionResponse$json = { '1': 'SignRawTransactionResponse', '2': [ {'1': 'transaction_id', '3': 1, '4': 1, '5': 9, '10': 'transactionId'}, { '1': 'signed_raw_transaction', '3': 2, '4': 1, '5': 9, '10': 'signedRawTransaction' }, ], }; /// Descriptor for `SignRawTransactionResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signRawTransactionResponseDescriptor = $convert.base64Decode( 'ChpTaWduUmF3VHJhbnNhY3Rpb25SZXNwb25zZRIlCg50cmFuc2FjdGlvbl9pZBgBIAEoCVINdH' 'JhbnNhY3Rpb25JZBI0ChZzaWduZWRfcmF3X3RyYW5zYWN0aW9uGAIgASgJUhRzaWduZWRSYXdU' 'cmFuc2FjdGlvbg=='); @$core.Deprecated('Use getTotalBalanceRequestDescriptor instead') const GetTotalBalanceRequest$json = { '1': 'GetTotalBalanceRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `GetTotalBalanceRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTotalBalanceRequestDescriptor = $convert.base64Decode( 'ChZHZXRUb3RhbEJhbGFuY2VSZXF1ZXN0Eh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZXROYW' '1l'); @$core.Deprecated('Use getTotalBalanceResponseDescriptor instead') const GetTotalBalanceResponse$json = { '1': 'GetTotalBalanceResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'total_balance', '3': 2, '4': 1, '5': 3, '10': 'totalBalance'}, ], }; /// Descriptor for `GetTotalBalanceResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTotalBalanceResponseDescriptor = $convert.base64Decode( 'ChdHZXRUb3RhbEJhbGFuY2VSZXNwb25zZRIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0Tm' 'FtZRIjCg10b3RhbF9iYWxhbmNlGAIgASgDUgx0b3RhbEJhbGFuY2U='); @$core.Deprecated('Use signMessageRequestDescriptor instead') const SignMessageRequest$json = { '1': 'SignMessageRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'password', '3': 2, '4': 1, '5': 9, '10': 'password'}, {'1': 'address', '3': 3, '4': 1, '5': 9, '10': 'address'}, {'1': 'message', '3': 4, '4': 1, '5': 9, '10': 'message'}, ], }; /// Descriptor for `SignMessageRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signMessageRequestDescriptor = $convert.base64Decode( 'ChJTaWduTWVzc2FnZVJlcXVlc3QSHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbWUSGg' 'oIcGFzc3dvcmQYAiABKAlSCHBhc3N3b3JkEhgKB2FkZHJlc3MYAyABKAlSB2FkZHJlc3MSGAoH' 'bWVzc2FnZRgEIAEoCVIHbWVzc2FnZQ=='); @$core.Deprecated('Use signMessageResponseDescriptor instead') const SignMessageResponse$json = { '1': 'SignMessageResponse', '2': [ {'1': 'signature', '3': 1, '4': 1, '5': 9, '10': 'signature'}, ], }; /// Descriptor for `SignMessageResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List signMessageResponseDescriptor = $convert.base64Decode( 'ChNTaWduTWVzc2FnZVJlc3BvbnNlEhwKCXNpZ25hdHVyZRgBIAEoCVIJc2lnbmF0dXJl'); @$core.Deprecated('Use getTotalStakeRequestDescriptor instead') const GetTotalStakeRequest$json = { '1': 'GetTotalStakeRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `GetTotalStakeRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTotalStakeRequestDescriptor = $convert.base64Decode( 'ChRHZXRUb3RhbFN0YWtlUmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZQ' '=='); @$core.Deprecated('Use getTotalStakeResponseDescriptor instead') const GetTotalStakeResponse$json = { '1': 'GetTotalStakeResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'total_stake', '3': 2, '4': 1, '5': 3, '10': 'totalStake'}, ], }; /// Descriptor for `GetTotalStakeResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getTotalStakeResponseDescriptor = $convert.base64Decode( 'ChVHZXRUb3RhbFN0YWtlUmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'USHwoLdG90YWxfc3Rha2UYAiABKANSCnRvdGFsU3Rha2U='); @$core.Deprecated('Use getAddressInfoRequestDescriptor instead') const GetAddressInfoRequest$json = { '1': 'GetAddressInfoRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'address', '3': 2, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `GetAddressInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getAddressInfoRequestDescriptor = $convert.base64Decode( 'ChVHZXRBZGRyZXNzSW5mb1JlcXVlc3QSHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'USGAoHYWRkcmVzcxgCIAEoCVIHYWRkcmVzcw=='); @$core.Deprecated('Use getAddressInfoResponseDescriptor instead') const GetAddressInfoResponse$json = { '1': 'GetAddressInfoResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, { '1': 'addr', '3': 2, '4': 1, '5': 11, '6': '.pactus.AddressInfo', '10': 'addr' }, ], }; /// Descriptor for `GetAddressInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getAddressInfoResponseDescriptor = $convert.base64Decode( 'ChZHZXRBZGRyZXNzSW5mb1Jlc3BvbnNlEh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZXROYW' '1lEicKBGFkZHIYAiABKAsyEy5wYWN0dXMuQWRkcmVzc0luZm9SBGFkZHI='); @$core.Deprecated('Use setAddressLabelRequestDescriptor instead') const SetAddressLabelRequest$json = { '1': 'SetAddressLabelRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'password', '3': 2, '4': 1, '5': 9, '10': 'password'}, {'1': 'address', '3': 3, '4': 1, '5': 9, '10': 'address'}, {'1': 'label', '3': 4, '4': 1, '5': 9, '10': 'label'}, ], }; /// Descriptor for `SetAddressLabelRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List setAddressLabelRequestDescriptor = $convert.base64Decode( 'ChZTZXRBZGRyZXNzTGFiZWxSZXF1ZXN0Eh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZXROYW' '1lEhoKCHBhc3N3b3JkGAIgASgJUghwYXNzd29yZBIYCgdhZGRyZXNzGAMgASgJUgdhZGRyZXNz' 'EhQKBWxhYmVsGAQgASgJUgVsYWJlbA=='); @$core.Deprecated('Use setAddressLabelResponseDescriptor instead') const SetAddressLabelResponse$json = { '1': 'SetAddressLabelResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'address', '3': 2, '4': 1, '5': 9, '10': 'address'}, {'1': 'label', '3': 3, '4': 1, '5': 9, '10': 'label'}, ], }; /// Descriptor for `SetAddressLabelResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List setAddressLabelResponseDescriptor = $convert.base64Decode( 'ChdTZXRBZGRyZXNzTGFiZWxSZXNwb25zZRIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0Tm' 'FtZRIYCgdhZGRyZXNzGAIgASgJUgdhZGRyZXNzEhQKBWxhYmVsGAMgASgJUgVsYWJlbA=='); @$core.Deprecated('Use listWalletsRequestDescriptor instead') const ListWalletsRequest$json = { '1': 'ListWalletsRequest', }; /// Descriptor for `ListWalletsRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listWalletsRequestDescriptor = $convert.base64Decode('ChJMaXN0V2FsbGV0c1JlcXVlc3Q='); @$core.Deprecated('Use listWalletsResponseDescriptor instead') const ListWalletsResponse$json = { '1': 'ListWalletsResponse', '2': [ {'1': 'wallets', '3': 1, '4': 3, '5': 9, '10': 'wallets'}, ], }; /// Descriptor for `ListWalletsResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listWalletsResponseDescriptor = $convert.base64Decode( 'ChNMaXN0V2FsbGV0c1Jlc3BvbnNlEhgKB3dhbGxldHMYASADKAlSB3dhbGxldHM='); @$core.Deprecated('Use getWalletInfoRequestDescriptor instead') const GetWalletInfoRequest$json = { '1': 'GetWalletInfoRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `GetWalletInfoRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getWalletInfoRequestDescriptor = $convert.base64Decode( 'ChRHZXRXYWxsZXRJbmZvUmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZQ' '=='); @$core.Deprecated('Use getWalletInfoResponseDescriptor instead') const GetWalletInfoResponse$json = { '1': 'GetWalletInfoResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'version', '3': 2, '4': 1, '5': 5, '10': 'version'}, {'1': 'network', '3': 3, '4': 1, '5': 9, '10': 'network'}, {'1': 'encrypted', '3': 4, '4': 1, '5': 8, '10': 'encrypted'}, {'1': 'uuid', '3': 5, '4': 1, '5': 9, '10': 'uuid'}, {'1': 'created_at', '3': 6, '4': 1, '5': 3, '10': 'createdAt'}, {'1': 'default_fee', '3': 7, '4': 1, '5': 3, '10': 'defaultFee'}, {'1': 'driver', '3': 8, '4': 1, '5': 9, '10': 'driver'}, {'1': 'path', '3': 9, '4': 1, '5': 9, '10': 'path'}, ], }; /// Descriptor for `GetWalletInfoResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getWalletInfoResponseDescriptor = $convert.base64Decode( 'ChVHZXRXYWxsZXRJbmZvUmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'USGAoHdmVyc2lvbhgCIAEoBVIHdmVyc2lvbhIYCgduZXR3b3JrGAMgASgJUgduZXR3b3JrEhwK' 'CWVuY3J5cHRlZBgEIAEoCFIJZW5jcnlwdGVkEhIKBHV1aWQYBSABKAlSBHV1aWQSHQoKY3JlYX' 'RlZF9hdBgGIAEoA1IJY3JlYXRlZEF0Eh8KC2RlZmF1bHRfZmVlGAcgASgDUgpkZWZhdWx0RmVl' 'EhYKBmRyaXZlchgIIAEoCVIGZHJpdmVyEhIKBHBhdGgYCSABKAlSBHBhdGg='); @$core.Deprecated('Use listAddressesRequestDescriptor instead') const ListAddressesRequest$json = { '1': 'ListAddressesRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, { '1': 'address_types', '3': 2, '4': 3, '5': 14, '6': '.pactus.AddressType', '10': 'addressTypes' }, ], }; /// Descriptor for `ListAddressesRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listAddressesRequestDescriptor = $convert.base64Decode( 'ChRMaXN0QWRkcmVzc2VzUmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZR' 'I4Cg1hZGRyZXNzX3R5cGVzGAIgAygOMhMucGFjdHVzLkFkZHJlc3NUeXBlUgxhZGRyZXNzVHlw' 'ZXM='); @$core.Deprecated('Use listAddressesResponseDescriptor instead') const ListAddressesResponse$json = { '1': 'ListAddressesResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, { '1': 'addrs', '3': 2, '4': 3, '5': 11, '6': '.pactus.AddressInfo', '10': 'addrs' }, ], }; /// Descriptor for `ListAddressesResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listAddressesResponseDescriptor = $convert.base64Decode( 'ChVMaXN0QWRkcmVzc2VzUmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'USKQoFYWRkcnMYAiADKAsyEy5wYWN0dXMuQWRkcmVzc0luZm9SBWFkZHJz'); @$core.Deprecated('Use updatePasswordRequestDescriptor instead') const UpdatePasswordRequest$json = { '1': 'UpdatePasswordRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'old_password', '3': 2, '4': 1, '5': 9, '10': 'oldPassword'}, {'1': 'new_password', '3': 3, '4': 1, '5': 9, '10': 'newPassword'}, ], }; /// Descriptor for `UpdatePasswordRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List updatePasswordRequestDescriptor = $convert.base64Decode( 'ChVVcGRhdGVQYXNzd29yZFJlcXVlc3QSHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'USIQoMb2xkX3Bhc3N3b3JkGAIgASgJUgtvbGRQYXNzd29yZBIhCgxuZXdfcGFzc3dvcmQYAyAB' 'KAlSC25ld1Bhc3N3b3Jk'); @$core.Deprecated('Use updatePasswordResponseDescriptor instead') const UpdatePasswordResponse$json = { '1': 'UpdatePasswordResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `UpdatePasswordResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List updatePasswordResponseDescriptor = $convert.base64Decode( 'ChZVcGRhdGVQYXNzd29yZFJlc3BvbnNlEh8KC3dhbGxldF9uYW1lGAEgASgJUgp3YWxsZXROYW' '1l'); @$core.Deprecated('Use walletTransactionInfoDescriptor instead') const WalletTransactionInfo$json = { '1': 'WalletTransactionInfo', '2': [ {'1': 'no', '3': 1, '4': 1, '5': 3, '10': 'no'}, {'1': 'tx_id', '3': 2, '4': 1, '5': 9, '10': 'txId'}, {'1': 'sender', '3': 3, '4': 1, '5': 9, '10': 'sender'}, {'1': 'receiver', '3': 4, '4': 1, '5': 9, '10': 'receiver'}, { '1': 'direction', '3': 5, '4': 1, '5': 14, '6': '.pactus.TxDirection', '10': 'direction' }, {'1': 'amount', '3': 6, '4': 1, '5': 3, '10': 'amount'}, {'1': 'fee', '3': 7, '4': 1, '5': 3, '10': 'fee'}, {'1': 'memo', '3': 8, '4': 1, '5': 9, '10': 'memo'}, { '1': 'status', '3': 9, '4': 1, '5': 14, '6': '.pactus.TransactionStatus', '10': 'status' }, {'1': 'block_height', '3': 10, '4': 1, '5': 13, '10': 'blockHeight'}, { '1': 'payload_type', '3': 11, '4': 1, '5': 14, '6': '.pactus.PayloadType', '10': 'payloadType' }, {'1': 'data', '3': 12, '4': 1, '5': 12, '10': 'data'}, {'1': 'comment', '3': 13, '4': 1, '5': 9, '10': 'comment'}, {'1': 'created_at', '3': 14, '4': 1, '5': 3, '10': 'createdAt'}, {'1': 'updated_at', '3': 15, '4': 1, '5': 3, '10': 'updatedAt'}, ], }; /// Descriptor for `WalletTransactionInfo`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List walletTransactionInfoDescriptor = $convert.base64Decode( 'ChVXYWxsZXRUcmFuc2FjdGlvbkluZm8SDgoCbm8YASABKANSAm5vEhMKBXR4X2lkGAIgASgJUg' 'R0eElkEhYKBnNlbmRlchgDIAEoCVIGc2VuZGVyEhoKCHJlY2VpdmVyGAQgASgJUghyZWNlaXZl' 'chIxCglkaXJlY3Rpb24YBSABKA4yEy5wYWN0dXMuVHhEaXJlY3Rpb25SCWRpcmVjdGlvbhIWCg' 'ZhbW91bnQYBiABKANSBmFtb3VudBIQCgNmZWUYByABKANSA2ZlZRISCgRtZW1vGAggASgJUgRt' 'ZW1vEjEKBnN0YXR1cxgJIAEoDjIZLnBhY3R1cy5UcmFuc2FjdGlvblN0YXR1c1IGc3RhdHVzEi' 'EKDGJsb2NrX2hlaWdodBgKIAEoDVILYmxvY2tIZWlnaHQSNgoMcGF5bG9hZF90eXBlGAsgASgO' 'MhMucGFjdHVzLlBheWxvYWRUeXBlUgtwYXlsb2FkVHlwZRISCgRkYXRhGAwgASgMUgRkYXRhEh' 'gKB2NvbW1lbnQYDSABKAlSB2NvbW1lbnQSHQoKY3JlYXRlZF9hdBgOIAEoA1IJY3JlYXRlZEF0' 'Eh0KCnVwZGF0ZWRfYXQYDyABKANSCXVwZGF0ZWRBdA=='); @$core.Deprecated('Use listTransactionsRequestDescriptor instead') const ListTransactionsRequest$json = { '1': 'ListTransactionsRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'address', '3': 2, '4': 1, '5': 9, '10': 'address'}, { '1': 'direction', '3': 3, '4': 1, '5': 14, '6': '.pactus.TxDirection', '10': 'direction' }, {'1': 'count', '3': 4, '4': 1, '5': 5, '10': 'count'}, {'1': 'skip', '3': 5, '4': 1, '5': 5, '10': 'skip'}, ], }; /// Descriptor for `ListTransactionsRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listTransactionsRequestDescriptor = $convert.base64Decode( 'ChdMaXN0VHJhbnNhY3Rpb25zUmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0Tm' 'FtZRIYCgdhZGRyZXNzGAIgASgJUgdhZGRyZXNzEjEKCWRpcmVjdGlvbhgDIAEoDjITLnBhY3R1' 'cy5UeERpcmVjdGlvblIJZGlyZWN0aW9uEhQKBWNvdW50GAQgASgFUgVjb3VudBISCgRza2lwGA' 'UgASgFUgRza2lw'); @$core.Deprecated('Use listTransactionsResponseDescriptor instead') const ListTransactionsResponse$json = { '1': 'ListTransactionsResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, { '1': 'txs', '3': 2, '4': 3, '5': 11, '6': '.pactus.WalletTransactionInfo', '10': 'txs' }, ], }; /// Descriptor for `ListTransactionsResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listTransactionsResponseDescriptor = $convert.base64Decode( 'ChhMaXN0VHJhbnNhY3Rpb25zUmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE' '5hbWUSLwoDdHhzGAIgAygLMh0ucGFjdHVzLldhbGxldFRyYW5zYWN0aW9uSW5mb1IDdHhz'); @$core.Deprecated('Use setDefaultFeeRequestDescriptor instead') const SetDefaultFeeRequest$json = { '1': 'SetDefaultFeeRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'amount', '3': 2, '4': 1, '5': 3, '10': 'amount'}, ], }; /// Descriptor for `SetDefaultFeeRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List setDefaultFeeRequestDescriptor = $convert.base64Decode( 'ChRTZXREZWZhdWx0RmVlUmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZR' 'IWCgZhbW91bnQYAiABKANSBmFtb3VudA=='); @$core.Deprecated('Use setDefaultFeeResponseDescriptor instead') const SetDefaultFeeResponse$json = { '1': 'SetDefaultFeeResponse', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, ], }; /// Descriptor for `SetDefaultFeeResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List setDefaultFeeResponseDescriptor = $convert.base64Decode( 'ChVTZXREZWZhdWx0RmVlUmVzcG9uc2USHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbW' 'U='); @$core.Deprecated('Use getMnemonicRequestDescriptor instead') const GetMnemonicRequest$json = { '1': 'GetMnemonicRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'password', '3': 2, '4': 1, '5': 9, '10': 'password'}, ], }; /// Descriptor for `GetMnemonicRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getMnemonicRequestDescriptor = $convert.base64Decode( 'ChJHZXRNbmVtb25pY1JlcXVlc3QSHwoLd2FsbGV0X25hbWUYASABKAlSCndhbGxldE5hbWUSGg' 'oIcGFzc3dvcmQYAiABKAlSCHBhc3N3b3Jk'); @$core.Deprecated('Use getMnemonicResponseDescriptor instead') const GetMnemonicResponse$json = { '1': 'GetMnemonicResponse', '2': [ {'1': 'mnemonic', '3': 1, '4': 1, '5': 9, '10': 'mnemonic'}, ], }; /// Descriptor for `GetMnemonicResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getMnemonicResponseDescriptor = $convert.base64Decode( 'ChNHZXRNbmVtb25pY1Jlc3BvbnNlEhoKCG1uZW1vbmljGAEgASgJUghtbmVtb25pYw=='); @$core.Deprecated('Use getPrivateKeyRequestDescriptor instead') const GetPrivateKeyRequest$json = { '1': 'GetPrivateKeyRequest', '2': [ {'1': 'wallet_name', '3': 1, '4': 1, '5': 9, '10': 'walletName'}, {'1': 'password', '3': 2, '4': 1, '5': 9, '10': 'password'}, {'1': 'address', '3': 3, '4': 1, '5': 9, '10': 'address'}, ], }; /// Descriptor for `GetPrivateKeyRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getPrivateKeyRequestDescriptor = $convert.base64Decode( 'ChRHZXRQcml2YXRlS2V5UmVxdWVzdBIfCgt3YWxsZXRfbmFtZRgBIAEoCVIKd2FsbGV0TmFtZR' 'IaCghwYXNzd29yZBgCIAEoCVIIcGFzc3dvcmQSGAoHYWRkcmVzcxgDIAEoCVIHYWRkcmVzcw=='); @$core.Deprecated('Use getPrivateKeyResponseDescriptor instead') const GetPrivateKeyResponse$json = { '1': 'GetPrivateKeyResponse', '2': [ {'1': 'private_key', '3': 1, '4': 1, '5': 9, '10': 'privateKey'}, ], }; /// Descriptor for `GetPrivateKeyResponse`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List getPrivateKeyResponseDescriptor = $convert.base64Decode( 'ChVHZXRQcml2YXRlS2V5UmVzcG9uc2USHwoLcHJpdmF0ZV9rZXkYASABKAlSCnByaXZhdGVLZX' 'k='); const $core.Map<$core.String, $core.dynamic> WalletServiceBase$json = { '1': 'Wallet', '2': [ { '1': 'CreateWallet', '2': '.pactus.CreateWalletRequest', '3': '.pactus.CreateWalletResponse' }, { '1': 'RestoreWallet', '2': '.pactus.RestoreWalletRequest', '3': '.pactus.RestoreWalletResponse' }, { '1': 'LoadWallet', '2': '.pactus.LoadWalletRequest', '3': '.pactus.LoadWalletResponse' }, { '1': 'UnloadWallet', '2': '.pactus.UnloadWalletRequest', '3': '.pactus.UnloadWalletResponse' }, { '1': 'ListWallets', '2': '.pactus.ListWalletsRequest', '3': '.pactus.ListWalletsResponse' }, { '1': 'GetWalletInfo', '2': '.pactus.GetWalletInfoRequest', '3': '.pactus.GetWalletInfoResponse' }, { '1': 'UpdatePassword', '2': '.pactus.UpdatePasswordRequest', '3': '.pactus.UpdatePasswordResponse' }, { '1': 'GetTotalBalance', '2': '.pactus.GetTotalBalanceRequest', '3': '.pactus.GetTotalBalanceResponse' }, { '1': 'GetTotalStake', '2': '.pactus.GetTotalStakeRequest', '3': '.pactus.GetTotalStakeResponse' }, { '1': 'GetValidatorAddress', '2': '.pactus.GetValidatorAddressRequest', '3': '.pactus.GetValidatorAddressResponse' }, { '1': 'GetAddressInfo', '2': '.pactus.GetAddressInfoRequest', '3': '.pactus.GetAddressInfoResponse' }, { '1': 'SetAddressLabel', '2': '.pactus.SetAddressLabelRequest', '3': '.pactus.SetAddressLabelResponse' }, { '1': 'GetNewAddress', '2': '.pactus.GetNewAddressRequest', '3': '.pactus.GetNewAddressResponse' }, { '1': 'ListAddresses', '2': '.pactus.ListAddressesRequest', '3': '.pactus.ListAddressesResponse' }, { '1': 'SignMessage', '2': '.pactus.SignMessageRequest', '3': '.pactus.SignMessageResponse' }, { '1': 'SignRawTransaction', '2': '.pactus.SignRawTransactionRequest', '3': '.pactus.SignRawTransactionResponse' }, { '1': 'ListTransactions', '2': '.pactus.ListTransactionsRequest', '3': '.pactus.ListTransactionsResponse' }, { '1': 'SetDefaultFee', '2': '.pactus.SetDefaultFeeRequest', '3': '.pactus.SetDefaultFeeResponse' }, { '1': 'GetMnemonic', '2': '.pactus.GetMnemonicRequest', '3': '.pactus.GetMnemonicResponse' }, { '1': 'GetPrivateKey', '2': '.pactus.GetPrivateKeyRequest', '3': '.pactus.GetPrivateKeyResponse' }, ], }; @$core.Deprecated('Use walletServiceDescriptor instead') const $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> WalletServiceBase$messageJson = { '.pactus.CreateWalletRequest': CreateWalletRequest$json, '.pactus.CreateWalletResponse': CreateWalletResponse$json, '.pactus.RestoreWalletRequest': RestoreWalletRequest$json, '.pactus.RestoreWalletResponse': RestoreWalletResponse$json, '.pactus.LoadWalletRequest': LoadWalletRequest$json, '.pactus.LoadWalletResponse': LoadWalletResponse$json, '.pactus.UnloadWalletRequest': UnloadWalletRequest$json, '.pactus.UnloadWalletResponse': UnloadWalletResponse$json, '.pactus.ListWalletsRequest': ListWalletsRequest$json, '.pactus.ListWalletsResponse': ListWalletsResponse$json, '.pactus.GetWalletInfoRequest': GetWalletInfoRequest$json, '.pactus.GetWalletInfoResponse': GetWalletInfoResponse$json, '.pactus.UpdatePasswordRequest': UpdatePasswordRequest$json, '.pactus.UpdatePasswordResponse': UpdatePasswordResponse$json, '.pactus.GetTotalBalanceRequest': GetTotalBalanceRequest$json, '.pactus.GetTotalBalanceResponse': GetTotalBalanceResponse$json, '.pactus.GetTotalStakeRequest': GetTotalStakeRequest$json, '.pactus.GetTotalStakeResponse': GetTotalStakeResponse$json, '.pactus.GetValidatorAddressRequest': GetValidatorAddressRequest$json, '.pactus.GetValidatorAddressResponse': GetValidatorAddressResponse$json, '.pactus.GetAddressInfoRequest': GetAddressInfoRequest$json, '.pactus.GetAddressInfoResponse': GetAddressInfoResponse$json, '.pactus.AddressInfo': AddressInfo$json, '.pactus.SetAddressLabelRequest': SetAddressLabelRequest$json, '.pactus.SetAddressLabelResponse': SetAddressLabelResponse$json, '.pactus.GetNewAddressRequest': GetNewAddressRequest$json, '.pactus.GetNewAddressResponse': GetNewAddressResponse$json, '.pactus.ListAddressesRequest': ListAddressesRequest$json, '.pactus.ListAddressesResponse': ListAddressesResponse$json, '.pactus.SignMessageRequest': SignMessageRequest$json, '.pactus.SignMessageResponse': SignMessageResponse$json, '.pactus.SignRawTransactionRequest': SignRawTransactionRequest$json, '.pactus.SignRawTransactionResponse': SignRawTransactionResponse$json, '.pactus.ListTransactionsRequest': ListTransactionsRequest$json, '.pactus.ListTransactionsResponse': ListTransactionsResponse$json, '.pactus.WalletTransactionInfo': WalletTransactionInfo$json, '.pactus.SetDefaultFeeRequest': SetDefaultFeeRequest$json, '.pactus.SetDefaultFeeResponse': SetDefaultFeeResponse$json, '.pactus.GetMnemonicRequest': GetMnemonicRequest$json, '.pactus.GetMnemonicResponse': GetMnemonicResponse$json, '.pactus.GetPrivateKeyRequest': GetPrivateKeyRequest$json, '.pactus.GetPrivateKeyResponse': GetPrivateKeyResponse$json, }; /// Descriptor for `Wallet`. Decode as a `google.protobuf.ServiceDescriptorProto`. final $typed_data.Uint8List walletServiceDescriptor = $convert.base64Decode( 'CgZXYWxsZXQSSQoMQ3JlYXRlV2FsbGV0EhsucGFjdHVzLkNyZWF0ZVdhbGxldFJlcXVlc3QaHC' '5wYWN0dXMuQ3JlYXRlV2FsbGV0UmVzcG9uc2USTAoNUmVzdG9yZVdhbGxldBIcLnBhY3R1cy5S' 'ZXN0b3JlV2FsbGV0UmVxdWVzdBodLnBhY3R1cy5SZXN0b3JlV2FsbGV0UmVzcG9uc2USQwoKTG' '9hZFdhbGxldBIZLnBhY3R1cy5Mb2FkV2FsbGV0UmVxdWVzdBoaLnBhY3R1cy5Mb2FkV2FsbGV0' 'UmVzcG9uc2USSQoMVW5sb2FkV2FsbGV0EhsucGFjdHVzLlVubG9hZFdhbGxldFJlcXVlc3QaHC' '5wYWN0dXMuVW5sb2FkV2FsbGV0UmVzcG9uc2USRgoLTGlzdFdhbGxldHMSGi5wYWN0dXMuTGlz' 'dFdhbGxldHNSZXF1ZXN0GhsucGFjdHVzLkxpc3RXYWxsZXRzUmVzcG9uc2USTAoNR2V0V2FsbG' 'V0SW5mbxIcLnBhY3R1cy5HZXRXYWxsZXRJbmZvUmVxdWVzdBodLnBhY3R1cy5HZXRXYWxsZXRJ' 'bmZvUmVzcG9uc2USTwoOVXBkYXRlUGFzc3dvcmQSHS5wYWN0dXMuVXBkYXRlUGFzc3dvcmRSZX' 'F1ZXN0Gh4ucGFjdHVzLlVwZGF0ZVBhc3N3b3JkUmVzcG9uc2USUgoPR2V0VG90YWxCYWxhbmNl' 'Eh4ucGFjdHVzLkdldFRvdGFsQmFsYW5jZVJlcXVlc3QaHy5wYWN0dXMuR2V0VG90YWxCYWxhbm' 'NlUmVzcG9uc2USTAoNR2V0VG90YWxTdGFrZRIcLnBhY3R1cy5HZXRUb3RhbFN0YWtlUmVxdWVz' 'dBodLnBhY3R1cy5HZXRUb3RhbFN0YWtlUmVzcG9uc2USXgoTR2V0VmFsaWRhdG9yQWRkcmVzcx' 'IiLnBhY3R1cy5HZXRWYWxpZGF0b3JBZGRyZXNzUmVxdWVzdBojLnBhY3R1cy5HZXRWYWxpZGF0' 'b3JBZGRyZXNzUmVzcG9uc2USTwoOR2V0QWRkcmVzc0luZm8SHS5wYWN0dXMuR2V0QWRkcmVzc0' 'luZm9SZXF1ZXN0Gh4ucGFjdHVzLkdldEFkZHJlc3NJbmZvUmVzcG9uc2USUgoPU2V0QWRkcmVz' 'c0xhYmVsEh4ucGFjdHVzLlNldEFkZHJlc3NMYWJlbFJlcXVlc3QaHy5wYWN0dXMuU2V0QWRkcm' 'Vzc0xhYmVsUmVzcG9uc2USTAoNR2V0TmV3QWRkcmVzcxIcLnBhY3R1cy5HZXROZXdBZGRyZXNz' 'UmVxdWVzdBodLnBhY3R1cy5HZXROZXdBZGRyZXNzUmVzcG9uc2USTAoNTGlzdEFkZHJlc3Nlcx' 'IcLnBhY3R1cy5MaXN0QWRkcmVzc2VzUmVxdWVzdBodLnBhY3R1cy5MaXN0QWRkcmVzc2VzUmVz' 'cG9uc2USRgoLU2lnbk1lc3NhZ2USGi5wYWN0dXMuU2lnbk1lc3NhZ2VSZXF1ZXN0GhsucGFjdH' 'VzLlNpZ25NZXNzYWdlUmVzcG9uc2USWwoSU2lnblJhd1RyYW5zYWN0aW9uEiEucGFjdHVzLlNp' 'Z25SYXdUcmFuc2FjdGlvblJlcXVlc3QaIi5wYWN0dXMuU2lnblJhd1RyYW5zYWN0aW9uUmVzcG' '9uc2USVQoQTGlzdFRyYW5zYWN0aW9ucxIfLnBhY3R1cy5MaXN0VHJhbnNhY3Rpb25zUmVxdWVz' 'dBogLnBhY3R1cy5MaXN0VHJhbnNhY3Rpb25zUmVzcG9uc2USTAoNU2V0RGVmYXVsdEZlZRIcLn' 'BhY3R1cy5TZXREZWZhdWx0RmVlUmVxdWVzdBodLnBhY3R1cy5TZXREZWZhdWx0RmVlUmVzcG9u' 'c2USRgoLR2V0TW5lbW9uaWMSGi5wYWN0dXMuR2V0TW5lbW9uaWNSZXF1ZXN0GhsucGFjdHVzLk' 'dldE1uZW1vbmljUmVzcG9uc2USTAoNR2V0UHJpdmF0ZUtleRIcLnBhY3R1cy5HZXRQcml2YXRl' 'S2V5UmVxdWVzdBodLnBhY3R1cy5HZXRQcml2YXRlS2V5UmVzcG9uc2U='); ================================================ FILE: www/grpc/gen/dart/wallet.pbserver.dart ================================================ // This is a generated file - do not edit. // // Generated from wallet.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:async' as $async; import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'wallet.pb.dart' as $1; import 'wallet.pbjson.dart'; export 'wallet.pb.dart'; abstract class WalletServiceBase extends $pb.GeneratedService { $async.Future<$1.CreateWalletResponse> createWallet( $pb.ServerContext ctx, $1.CreateWalletRequest request); $async.Future<$1.RestoreWalletResponse> restoreWallet( $pb.ServerContext ctx, $1.RestoreWalletRequest request); $async.Future<$1.LoadWalletResponse> loadWallet( $pb.ServerContext ctx, $1.LoadWalletRequest request); $async.Future<$1.UnloadWalletResponse> unloadWallet( $pb.ServerContext ctx, $1.UnloadWalletRequest request); $async.Future<$1.ListWalletsResponse> listWallets( $pb.ServerContext ctx, $1.ListWalletsRequest request); $async.Future<$1.GetWalletInfoResponse> getWalletInfo( $pb.ServerContext ctx, $1.GetWalletInfoRequest request); $async.Future<$1.UpdatePasswordResponse> updatePassword( $pb.ServerContext ctx, $1.UpdatePasswordRequest request); $async.Future<$1.GetTotalBalanceResponse> getTotalBalance( $pb.ServerContext ctx, $1.GetTotalBalanceRequest request); $async.Future<$1.GetTotalStakeResponse> getTotalStake( $pb.ServerContext ctx, $1.GetTotalStakeRequest request); $async.Future<$1.GetValidatorAddressResponse> getValidatorAddress( $pb.ServerContext ctx, $1.GetValidatorAddressRequest request); $async.Future<$1.GetAddressInfoResponse> getAddressInfo( $pb.ServerContext ctx, $1.GetAddressInfoRequest request); $async.Future<$1.SetAddressLabelResponse> setAddressLabel( $pb.ServerContext ctx, $1.SetAddressLabelRequest request); $async.Future<$1.GetNewAddressResponse> getNewAddress( $pb.ServerContext ctx, $1.GetNewAddressRequest request); $async.Future<$1.ListAddressesResponse> listAddresses( $pb.ServerContext ctx, $1.ListAddressesRequest request); $async.Future<$1.SignMessageResponse> signMessage( $pb.ServerContext ctx, $1.SignMessageRequest request); $async.Future<$1.SignRawTransactionResponse> signRawTransaction( $pb.ServerContext ctx, $1.SignRawTransactionRequest request); $async.Future<$1.ListTransactionsResponse> listTransactions( $pb.ServerContext ctx, $1.ListTransactionsRequest request); $async.Future<$1.SetDefaultFeeResponse> setDefaultFee( $pb.ServerContext ctx, $1.SetDefaultFeeRequest request); $async.Future<$1.GetMnemonicResponse> getMnemonic( $pb.ServerContext ctx, $1.GetMnemonicRequest request); $async.Future<$1.GetPrivateKeyResponse> getPrivateKey( $pb.ServerContext ctx, $1.GetPrivateKeyRequest request); $pb.GeneratedMessage createRequest($core.String methodName) { switch (methodName) { case 'CreateWallet': return $1.CreateWalletRequest(); case 'RestoreWallet': return $1.RestoreWalletRequest(); case 'LoadWallet': return $1.LoadWalletRequest(); case 'UnloadWallet': return $1.UnloadWalletRequest(); case 'ListWallets': return $1.ListWalletsRequest(); case 'GetWalletInfo': return $1.GetWalletInfoRequest(); case 'UpdatePassword': return $1.UpdatePasswordRequest(); case 'GetTotalBalance': return $1.GetTotalBalanceRequest(); case 'GetTotalStake': return $1.GetTotalStakeRequest(); case 'GetValidatorAddress': return $1.GetValidatorAddressRequest(); case 'GetAddressInfo': return $1.GetAddressInfoRequest(); case 'SetAddressLabel': return $1.SetAddressLabelRequest(); case 'GetNewAddress': return $1.GetNewAddressRequest(); case 'ListAddresses': return $1.ListAddressesRequest(); case 'SignMessage': return $1.SignMessageRequest(); case 'SignRawTransaction': return $1.SignRawTransactionRequest(); case 'ListTransactions': return $1.ListTransactionsRequest(); case 'SetDefaultFee': return $1.SetDefaultFeeRequest(); case 'GetMnemonic': return $1.GetMnemonicRequest(); case 'GetPrivateKey': return $1.GetPrivateKeyRequest(); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $async.Future<$pb.GeneratedMessage> handleCall($pb.ServerContext ctx, $core.String methodName, $pb.GeneratedMessage request) { switch (methodName) { case 'CreateWallet': return createWallet(ctx, request as $1.CreateWalletRequest); case 'RestoreWallet': return restoreWallet(ctx, request as $1.RestoreWalletRequest); case 'LoadWallet': return loadWallet(ctx, request as $1.LoadWalletRequest); case 'UnloadWallet': return unloadWallet(ctx, request as $1.UnloadWalletRequest); case 'ListWallets': return listWallets(ctx, request as $1.ListWalletsRequest); case 'GetWalletInfo': return getWalletInfo(ctx, request as $1.GetWalletInfoRequest); case 'UpdatePassword': return updatePassword(ctx, request as $1.UpdatePasswordRequest); case 'GetTotalBalance': return getTotalBalance(ctx, request as $1.GetTotalBalanceRequest); case 'GetTotalStake': return getTotalStake(ctx, request as $1.GetTotalStakeRequest); case 'GetValidatorAddress': return getValidatorAddress( ctx, request as $1.GetValidatorAddressRequest); case 'GetAddressInfo': return getAddressInfo(ctx, request as $1.GetAddressInfoRequest); case 'SetAddressLabel': return setAddressLabel(ctx, request as $1.SetAddressLabelRequest); case 'GetNewAddress': return getNewAddress(ctx, request as $1.GetNewAddressRequest); case 'ListAddresses': return listAddresses(ctx, request as $1.ListAddressesRequest); case 'SignMessage': return signMessage(ctx, request as $1.SignMessageRequest); case 'SignRawTransaction': return signRawTransaction(ctx, request as $1.SignRawTransactionRequest); case 'ListTransactions': return listTransactions(ctx, request as $1.ListTransactionsRequest); case 'SetDefaultFee': return setDefaultFee(ctx, request as $1.SetDefaultFeeRequest); case 'GetMnemonic': return getMnemonic(ctx, request as $1.GetMnemonicRequest); case 'GetPrivateKey': return getPrivateKey(ctx, request as $1.GetPrivateKeyRequest); default: throw $core.ArgumentError('Unknown method: $methodName'); } } $core.Map<$core.String, $core.dynamic> get $json => WalletServiceBase$json; $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> get $messageJson => WalletServiceBase$messageJson; } ================================================ FILE: www/grpc/gen/docs/grpc.md ================================================ --- title: GRPC API Reference weight: 1 --- Every node in the Pactus network can be configured to use the [gRPC](https://grpc.io/) protocol for communication. Here you can find the list of all gRPC methods and messages. ## Units All the amounts are in NanoPAC units, which are atomic and the smallest unit in the Pactus blockchain. Each PAC is equivalent to 1,000,000,000 or 109 NanoPACs. ## Packages For seamless integration with Pactus, you can use these client libraries: - [pactus-grpc](https://www.npmjs.com/package/pactus-grpc/) package for Javascript - [pactus-grpc](https://pypi.org/project/pactus-grpc/) package for Python - [pactus-grpc](https://crates.io/crates/pactus-grpc) package for Rust ## gRPC Services
### Transaction Service

Transaction service defines various RPC methods for interacting with transactions.

#### GetTransaction

GetTransaction retrieves transaction details based on the provided request parameters.

GetTransactionRequest Request

FieldTypeDescription
id string The unique ID of the transaction to retrieve.
verbosity TransactionVerbosity (Enum)The verbosity level for transaction details.
Available values:
  • TRANSACTION_VERBOSITY_DATA = 0 (Request transaction data only.)
  • TRANSACTION_VERBOSITY_INFO = 1 (Request detailed transaction information.)

GetTransactionResponse Response

FieldTypeDescription
block_height uint32 The height of the block containing the transaction.
block_time uint32 The UNIX timestamp of the block containing the transaction.
transaction TransactionInfo Detailed information about the transaction.
transaction.id string The unique ID of the transaction.
transaction.data string The raw transaction data in hexadecimal format.
transaction.version int32 The version of the transaction.
transaction.lock_time uint32 The lock time for the transaction.
transaction.value int64 The value of the transaction in NanoPAC.
transaction.fee int64 The fee for the transaction in NanoPAC.
transaction.payload_type PayloadType (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
transaction.transfer PayloadTransfer (OneOf)Transfer transaction payload.
transaction.transfer.sender string The sender's address.
transaction.transfer.receiver string The receiver's address.
transaction.transfer.amount int64 The amount to be transferred in NanoPAC.
transaction.bond PayloadBond (OneOf)Bond transaction payload.
transaction.bond.sender string The sender's address.
transaction.bond.receiver string The receiver's address.
transaction.bond.stake int64 The stake amount in NanoPAC.
transaction.bond.public_key string The public key of the validator.
transaction.bond.is_delegated bool Indicates whether the bond transaction is a delegation.
transaction.bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
transaction.bond.delegate_share int64 The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
transaction.bond.delegate_expiry uint32 The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
transaction.sortition PayloadSortition (OneOf)Sortition transaction payload.
transaction.sortition.address string The validator address associated with the sortition proof.
transaction.sortition.proof string The proof for the sortition.
transaction.unbond PayloadUnbond (OneOf)Unbond transaction payload.
transaction.unbond.validator string The address of the validator to unbond from.
transaction.unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
transaction.withdraw PayloadWithdraw (OneOf)Withdraw transaction payload.
transaction.withdraw.validator_address string The address of the validator to withdraw from.
transaction.withdraw.account_address string The address of the account to withdraw to.
transaction.withdraw.amount int64 The withdrawal amount in NanoPAC.
transaction.batch_transfer PayloadBatchTransfer (OneOf)Batch Transfer transaction payload.
transaction.batch_transfer.sender string The sender's address.
transaction.batch_transfer.recipients repeated Recipient The list of recipients with their amounts.
transaction.memo string A memo string for the transaction.
transaction.public_key string The public key associated with the transaction.
transaction.signature string The signature for the transaction.
transaction.block_height uint32 The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
transaction.confirmed bool Indicates whether the transaction is confirmed.
transaction.confirmations int32 The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
#### CalculateFee

CalculateFee calculates the transaction fee based on the specified amount and payload type.

CalculateFeeRequest Request

FieldTypeDescription
amount int64 The amount involved in the transaction, specified in NanoPAC.
payload_type PayloadType (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
fixed_amount bool Indicates if the amount should be fixed and include the fee.

CalculateFeeResponse Response

FieldTypeDescription
amount int64 The calculated amount in NanoPAC.
fee int64 The calculated transaction fee in NanoPAC.
#### BroadcastTransaction

BroadcastTransaction broadcasts a signed transaction to the network.

BroadcastTransactionRequest Request

FieldTypeDescription
signed_raw_transaction string The signed raw transaction data to be broadcasted.

BroadcastTransactionResponse Response

FieldTypeDescription
id string The unique ID of the broadcasted transaction.
#### GetRawTransferTransaction

GetRawTransferTransaction retrieves raw details of a transfer transaction.

GetRawTransferTransactionRequest Request

FieldTypeDescription
lock_time uint32 The lock time for the transaction. If not set, defaults to the last block height.
sender string The sender's account address.
receiver string The receiver's account address.
amount int64 The amount to be transferred, specified in NanoPAC. Must be greater than 0.
fee int64 The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.

GetRawTransactionResponse Response

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### GetRawBondTransaction

GetRawBondTransaction retrieves raw details of a bond transaction.

GetRawBondTransactionRequest Request

FieldTypeDescription
lock_time uint32 The lock time for the transaction. If not set, defaults to the last block height.
sender string The sender's account address.
receiver string The receiver's validator address.
stake int64 The stake amount in NanoPAC. Must be greater than 0.
public_key string The public key of the validator. Optional, but required when registering a new validator.;
fee int64 The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.
delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
delegate_share int64 The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
delegate_expiry uint32 The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;

GetRawTransactionResponse Response

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### GetRawUnbondTransaction

GetRawUnbondTransaction retrieves raw details of an unbond transaction.

GetRawUnbondTransactionRequest Request

FieldTypeDescription
lock_time uint32 The lock time for the transaction. If not set, defaults to the last block height.
validator_address string The address of the validator to unbond from.
memo string A memo string for the transaction.
delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;

GetRawTransactionResponse Response

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### GetRawWithdrawTransaction

GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.

GetRawWithdrawTransactionRequest Request

FieldTypeDescription
lock_time uint32 The lock time for the transaction. If not set, defaults to the last block height.
validator_address string The address of the validator to withdraw from.
account_address string The address of the account to withdraw to.
amount int64 The withdrawal amount in NanoPAC. Must be greater than 0.
fee int64 The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.

GetRawTransactionResponse Response

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### GetRawBatchTransferTransaction

GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.

GetRawBatchTransferTransactionRequest Request

FieldTypeDescription
lock_time uint32 The lock time for the transaction. If not set, defaults to the last block height.
sender string The sender's account address.
recipients repeated Recipient The list of recipients with their amounts. Minimum 2 recipients required.
fee int64 The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.

GetRawTransactionResponse Response

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### DecodeRawTransaction

DecodeRawTransaction accepts raw transaction and returns decoded transaction.

DecodeRawTransactionRequest Request

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.

DecodeRawTransactionResponse Response

FieldTypeDescription
transaction TransactionInfo The decoded transaction information.
transaction.id string The unique ID of the transaction.
transaction.data string The raw transaction data in hexadecimal format.
transaction.version int32 The version of the transaction.
transaction.lock_time uint32 The lock time for the transaction.
transaction.value int64 The value of the transaction in NanoPAC.
transaction.fee int64 The fee for the transaction in NanoPAC.
transaction.payload_type PayloadType (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
transaction.transfer PayloadTransfer (OneOf)Transfer transaction payload.
transaction.transfer.sender string The sender's address.
transaction.transfer.receiver string The receiver's address.
transaction.transfer.amount int64 The amount to be transferred in NanoPAC.
transaction.bond PayloadBond (OneOf)Bond transaction payload.
transaction.bond.sender string The sender's address.
transaction.bond.receiver string The receiver's address.
transaction.bond.stake int64 The stake amount in NanoPAC.
transaction.bond.public_key string The public key of the validator.
transaction.bond.is_delegated bool Indicates whether the bond transaction is a delegation.
transaction.bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
transaction.bond.delegate_share int64 The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
transaction.bond.delegate_expiry uint32 The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
transaction.sortition PayloadSortition (OneOf)Sortition transaction payload.
transaction.sortition.address string The validator address associated with the sortition proof.
transaction.sortition.proof string The proof for the sortition.
transaction.unbond PayloadUnbond (OneOf)Unbond transaction payload.
transaction.unbond.validator string The address of the validator to unbond from.
transaction.unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
transaction.withdraw PayloadWithdraw (OneOf)Withdraw transaction payload.
transaction.withdraw.validator_address string The address of the validator to withdraw from.
transaction.withdraw.account_address string The address of the account to withdraw to.
transaction.withdraw.amount int64 The withdrawal amount in NanoPAC.
transaction.batch_transfer PayloadBatchTransfer (OneOf)Batch Transfer transaction payload.
transaction.batch_transfer.sender string The sender's address.
transaction.batch_transfer.recipients repeated Recipient The list of recipients with their amounts.
transaction.memo string A memo string for the transaction.
transaction.public_key string The public key associated with the transaction.
transaction.signature string The signature for the transaction.
transaction.block_height uint32 The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
transaction.confirmed bool Indicates whether the transaction is confirmed.
transaction.confirmations int32 The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
#### CheckTransaction

CheckTransaction checks if the transaction is valid and can be included in the blockchain.

CheckTransactionRequest Request

FieldTypeDescription
raw_transaction string The raw transaction data to be checked.

CheckTransactionResponse Response

FieldTypeDescription
is_valid bool Indicates whether the transaction is valid.
error_message string An error message if the transaction is invalid. Empty if the transaction is valid.
### Blockchain Service

Blockchain service defines RPC methods for interacting with the blockchain.

#### GetBlock

GetBlock retrieves information about a block based on the provided request parameters.

GetBlockRequest Request

FieldTypeDescription
height uint32 The height of the block to retrieve.
verbosity BlockVerbosity (Enum)The verbosity level for block information.
Available values:
  • BLOCK_VERBOSITY_DATA = 0 (Request only block data.)
  • BLOCK_VERBOSITY_INFO = 1 (Request block information and transaction IDs.)
  • BLOCK_VERBOSITY_TRANSACTIONS = 2 (Request block information and detailed transaction data.)

GetBlockResponse Response

FieldTypeDescription
height uint32 The height of the block.
hash string The hash of the block.
data string Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
block_time uint32 The timestamp of the block.
header BlockHeaderInfo Header information of the block.
header.version int32 The version of the block.
header.prev_block_hash string The hash of the previous block.
header.state_root string The state root hash of the blockchain.
header.sortition_seed string The sortition seed of the block.
header.proposer_address string The address of the proposer of the block.
prev_cert CertificateInfo Certificate information of the previous block.
prev_cert.hash string The hash of the certificate.
prev_cert.round int32 The round of the certificate.
prev_cert.committers repeated int32 List of committers in the certificate.
prev_cert.absentees repeated int32 List of absentees in the certificate.
prev_cert.signature string The signature of the certificate.
txs repeated TransactionInfo List of transactions in the block, available when verbosity level is set to BLOCK_VERBOSITY_TRANSACTIONS.
txs[].id string The unique ID of the transaction.
txs[].data string The raw transaction data in hexadecimal format.
txs[].version int32 The version of the transaction.
txs[].lock_time uint32 The lock time for the transaction.
txs[].value int64 The value of the transaction in NanoPAC.
txs[].fee int64 The fee for the transaction in NanoPAC.
txs[].payload_type PayloadType (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
txs[].transfer PayloadTransfer (OneOf)Transfer transaction payload.
txs[].transfer.sender string The sender's address.
txs[].transfer.receiver string The receiver's address.
txs[].transfer.amount int64 The amount to be transferred in NanoPAC.
txs[].bond PayloadBond (OneOf)Bond transaction payload.
txs[].bond.sender string The sender's address.
txs[].bond.receiver string The receiver's address.
txs[].bond.stake int64 The stake amount in NanoPAC.
txs[].bond.public_key string The public key of the validator.
txs[].bond.is_delegated bool Indicates whether the bond transaction is a delegation.
txs[].bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
txs[].bond.delegate_share int64 The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
txs[].bond.delegate_expiry uint32 The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
txs[].sortition PayloadSortition (OneOf)Sortition transaction payload.
txs[].sortition.address string The validator address associated with the sortition proof.
txs[].sortition.proof string The proof for the sortition.
txs[].unbond PayloadUnbond (OneOf)Unbond transaction payload.
txs[].unbond.validator string The address of the validator to unbond from.
txs[].unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
txs[].withdraw PayloadWithdraw (OneOf)Withdraw transaction payload.
txs[].withdraw.validator_address string The address of the validator to withdraw from.
txs[].withdraw.account_address string The address of the account to withdraw to.
txs[].withdraw.amount int64 The withdrawal amount in NanoPAC.
txs[].batch_transfer PayloadBatchTransfer (OneOf)Batch Transfer transaction payload.
txs[].batch_transfer.sender string The sender's address.
txs[].batch_transfer.recipients repeated Recipient The list of recipients with their amounts.
txs[].memo string A memo string for the transaction.
txs[].public_key string The public key associated with the transaction.
txs[].signature string The signature for the transaction.
txs[].block_height uint32 The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
txs[].confirmed bool Indicates whether the transaction is confirmed.
txs[].confirmations int32 The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
#### GetBlockHash

GetBlockHash retrieves the hash of a block at the specified height.

GetBlockHashRequest Request

FieldTypeDescription
height uint32 The height of the block to retrieve the hash for.

GetBlockHashResponse Response

FieldTypeDescription
hash string The hash of the block.
#### GetBlockHeight

GetBlockHeight retrieves the height of a block with the specified hash.

GetBlockHeightRequest Request

FieldTypeDescription
hash string The hash of the block to retrieve the height for.

GetBlockHeightResponse Response

FieldTypeDescription
height uint32 The height of the block.
#### GetBlockchainInfo

GetBlockchainInfo retrieves general information about the blockchain.

GetBlockchainInfoRequest Request

Request Message has no fields.

GetBlockchainInfoResponse Response

FieldTypeDescription
last_block_height uint32 The height of the last block in the blockchain.
last_block_hash string The hash of the last block in the blockchain.
last_block_time int64 The timestamp of the last block in Unix format.
total_accounts int32 The total number of accounts in the blockchain.
total_validators int32 The total number of validators in the blockchain.
active_validators int32 The number of active (not unbonded) validators in the blockchain.
total_power int64 The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
committee_power int64 The power of the committee.
is_pruned bool If the blocks are subject to pruning.
pruning_height uint32 Lowest-height block stored (only present if pruning is enabled)
in_committee bool Indicates whether this node participates in consensus: true if at least one of its running validators is a member of the current committee.
committee_size int32 The number of validators in the current committee.
average_score double Average availability score of validators with stake, in percentage (0-100).
#### GetCommitteeInfo

GetCommitteeInfo retrieves information about the current committee.

GetCommitteeInfoRequest Request

Request Message has no fields.

GetCommitteeInfoResponse Response

FieldTypeDescription
committee_size int32 The number of validators in the committee.
committee_power int64 The power of the committee.
total_power int64 The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
validators repeated ValidatorInfo List of committee validators.
validators[].hash string The hash of the validator.
validators[].data string The serialized data of the validator.
validators[].public_key string The public key of the validator.
validators[].number int32 The unique number assigned to the validator.
validators[].stake int64 The stake of the validator in NanoPAC.
validators[].last_bonding_height uint32 The height at which the validator last bonded.
validators[].last_sortition_height uint32 The height at which the validator last participated in sortition.
validators[].unbonding_height uint32 The height at which the validator will unbond.
validators[].address string The address of the validator.
validators[].availability_score double The availability score of the validator.
validators[].protocol_version int32 The protocol version of the validator.
validators[].is_delegated bool Whether the validator is delegated.
validators[].delegate_owner string The address of the stake owner of the validator.
validators[].delegate_share int64 The share of the stake owner of the validator.
validators[].delegate_expiry uint32 The expiry of the stake owner of the validator.
protocol_versions map<int32, double> Map of protocol versions and their percentages in the committee.
#### GetConsensusInfo

GetConsensusInfo retrieves information about the consensus instances.

GetConsensusInfoRequest Request

Request Message has no fields.

GetConsensusInfoResponse Response

FieldTypeDescription
proposal ProposalInfo The proposal of the consensus info.
proposal.height uint32 The height of the proposal.
proposal.round int32 The round of the proposal.
proposal.block_data string The block data of the proposal.
proposal.signature string The signature of the proposal, signed by the proposer.
instances repeated ConsensusInfo List of consensus instances.
instances[].address string The address of the consensus instance.
instances[].active bool Indicates whether the consensus instance is active and part of the committee.
instances[].height uint32 The height of the consensus instance.
instances[].round int32 The round of the consensus instance.
instances[].votes repeated VoteInfo List of votes in the consensus instance.
instances[].votes[].type VoteType (Enum)The type of the vote.
Available values:
  • VOTE_TYPE_UNSPECIFIED = 0 (Unspecified vote type.)
  • VOTE_TYPE_PREPARE = 1 (Prepare vote type.)
  • VOTE_TYPE_PRECOMMIT = 2 (Precommit vote type.)
  • VOTE_TYPE_CP_PRE_VOTE = 3 (Change-proposer:pre-vote vote type.)
  • VOTE_TYPE_CP_MAIN_VOTE = 4 (Change-proposer:main-vote vote type.)
  • VOTE_TYPE_CP_DECIDED = 5 (Change-proposer:decided vote type.)
instances[].votes[].voter string The address of the voter.
instances[].votes[].block_hash string The hash of the block being voted on.
instances[].votes[].round int32 The consensus round of the vote.
instances[].votes[].cp_round int32 The change-proposer round of the vote.
instances[].votes[].cp_value int32 The change-proposer value of the vote.
#### GetAccount

GetAccount retrieves information about an account based on the provided address.

GetAccountRequest Request

FieldTypeDescription
address string The address of the account to retrieve information for.

GetAccountResponse Response

FieldTypeDescription
account AccountInfo Detailed information about the account.
account.hash string The hash of the account.
account.data string The serialized data of the account.
account.number int32 The unique number assigned to the account.
account.balance int64 The balance of the account in NanoPAC.
account.address string The address of the account.
#### GetValidator

GetValidator retrieves information about a validator based on the provided address.

GetValidatorRequest Request

FieldTypeDescription
address string The address of the validator to retrieve information for.

GetValidatorResponse Response

FieldTypeDescription
validator ValidatorInfo Detailed information about the validator.
validator.hash string The hash of the validator.
validator.data string The serialized data of the validator.
validator.public_key string The public key of the validator.
validator.number int32 The unique number assigned to the validator.
validator.stake int64 The stake of the validator in NanoPAC.
validator.last_bonding_height uint32 The height at which the validator last bonded.
validator.last_sortition_height uint32 The height at which the validator last participated in sortition.
validator.unbonding_height uint32 The height at which the validator will unbond.
validator.address string The address of the validator.
validator.availability_score double The availability score of the validator.
validator.protocol_version int32 The protocol version of the validator.
validator.is_delegated bool Whether the validator is delegated.
validator.delegate_owner string The address of the stake owner of the validator.
validator.delegate_share int64 The share of the stake owner of the validator.
validator.delegate_expiry uint32 The expiry of the stake owner of the validator.
#### GetValidatorByNumber

GetValidatorByNumber retrieves information about a validator based on the provided number.

GetValidatorByNumberRequest Request

FieldTypeDescription
number int32 The unique number of the validator to retrieve information for.

GetValidatorResponse Response

FieldTypeDescription
validator ValidatorInfo Detailed information about the validator.
validator.hash string The hash of the validator.
validator.data string The serialized data of the validator.
validator.public_key string The public key of the validator.
validator.number int32 The unique number assigned to the validator.
validator.stake int64 The stake of the validator in NanoPAC.
validator.last_bonding_height uint32 The height at which the validator last bonded.
validator.last_sortition_height uint32 The height at which the validator last participated in sortition.
validator.unbonding_height uint32 The height at which the validator will unbond.
validator.address string The address of the validator.
validator.availability_score double The availability score of the validator.
validator.protocol_version int32 The protocol version of the validator.
validator.is_delegated bool Whether the validator is delegated.
validator.delegate_owner string The address of the stake owner of the validator.
validator.delegate_share int64 The share of the stake owner of the validator.
validator.delegate_expiry uint32 The expiry of the stake owner of the validator.
#### GetValidatorAddresses

GetValidatorAddresses retrieves a list of all validator addresses.

GetValidatorAddressesRequest Request

Request Message has no fields.

GetValidatorAddressesResponse Response

FieldTypeDescription
addresses repeated string List of validator addresses.
#### GetPublicKey

GetPublicKey retrieves the public key of an account based on the provided address.

GetPublicKeyRequest Request

FieldTypeDescription
address string The address for which to retrieve the public key.

GetPublicKeyResponse Response

FieldTypeDescription
public_key string The public key associated with the provided address.
#### GetTxPoolContent

GetTxPoolContent retrieves current transactions in the transaction pool.

GetTxPoolContentRequest Request

FieldTypeDescription
payload_type PayloadType (Enum)The type of transactions to retrieve from the transaction pool. 0 means all types.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)

GetTxPoolContentResponse Response

FieldTypeDescription
txs repeated TransactionInfo List of transactions currently in the pool.
txs[].id string The unique ID of the transaction.
txs[].data string The raw transaction data in hexadecimal format.
txs[].version int32 The version of the transaction.
txs[].lock_time uint32 The lock time for the transaction.
txs[].value int64 The value of the transaction in NanoPAC.
txs[].fee int64 The fee for the transaction in NanoPAC.
txs[].payload_type PayloadType (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
txs[].transfer PayloadTransfer (OneOf)Transfer transaction payload.
txs[].transfer.sender string The sender's address.
txs[].transfer.receiver string The receiver's address.
txs[].transfer.amount int64 The amount to be transferred in NanoPAC.
txs[].bond PayloadBond (OneOf)Bond transaction payload.
txs[].bond.sender string The sender's address.
txs[].bond.receiver string The receiver's address.
txs[].bond.stake int64 The stake amount in NanoPAC.
txs[].bond.public_key string The public key of the validator.
txs[].bond.is_delegated bool Indicates whether the bond transaction is a delegation.
txs[].bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
txs[].bond.delegate_share int64 The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
txs[].bond.delegate_expiry uint32 The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
txs[].sortition PayloadSortition (OneOf)Sortition transaction payload.
txs[].sortition.address string The validator address associated with the sortition proof.
txs[].sortition.proof string The proof for the sortition.
txs[].unbond PayloadUnbond (OneOf)Unbond transaction payload.
txs[].unbond.validator string The address of the validator to unbond from.
txs[].unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
txs[].withdraw PayloadWithdraw (OneOf)Withdraw transaction payload.
txs[].withdraw.validator_address string The address of the validator to withdraw from.
txs[].withdraw.account_address string The address of the account to withdraw to.
txs[].withdraw.amount int64 The withdrawal amount in NanoPAC.
txs[].batch_transfer PayloadBatchTransfer (OneOf)Batch Transfer transaction payload.
txs[].batch_transfer.sender string The sender's address.
txs[].batch_transfer.recipients repeated Recipient The list of recipients with their amounts.
txs[].memo string A memo string for the transaction.
txs[].public_key string The public key associated with the transaction.
txs[].signature string The signature for the transaction.
txs[].block_height uint32 The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
txs[].confirmed bool Indicates whether the transaction is confirmed.
txs[].confirmations int32 The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
### Network Service

Network service provides RPCs for retrieving information about the network.

#### GetNetworkInfo

GetNetworkInfo retrieves information about the overall network.

GetNetworkInfoRequest Request

Request Message has no fields.

GetNetworkInfoResponse Response

FieldTypeDescription
network_name string Name of the P2P network.
connected_peers_count uint32 Number of connected peers.
metric_info MetricInfo Metrics related to node activity.
metric_info.total_invalid CounterInfo Total number of invalid bundles.
metric_info.total_invalid.bytes uint64 Total number of bytes.
metric_info.total_invalid.bundles uint64 Total number of bundles.
metric_info.total_sent CounterInfo Total number of bundles sent.
metric_info.total_sent.bytes uint64 Total number of bytes.
metric_info.total_sent.bundles uint64 Total number of bundles.
metric_info.total_received CounterInfo Total number of bundles received.
metric_info.total_received.bytes uint64 Total number of bytes.
metric_info.total_received.bundles uint64 Total number of bundles.
metric_info.message_sent map<int32, CounterInfo> Number of sent bundles categorized by message type.
metric_info.message_received map<int32, CounterInfo> Number of received bundles categorized by message type.
#### ListPeers

ListPeers lists all peers in the network.

ListPeersRequest Request

FieldTypeDescription
include_disconnected bool If true, includes disconnected peers (default: connected peers only).

ListPeersResponse Response

FieldTypeDescription
peers repeated PeerInfo List of peers.
peers[].status int32 Current status of the peer (e.g., connected, disconnected).
peers[].moniker string Moniker or Human-Readable name of the peer.
peers[].agent string Version and agent details of the peer.
peers[].peer_id string Peer ID of the peer in P2P network.
peers[].consensus_keys repeated string List of consensus keys used by the peer.
peers[].consensus_addresses repeated string List of consensus addresses used by the peer.
peers[].services uint32 Bitfield representing the services provided by the peer.
peers[].last_block_hash string Hash of the last block the peer knows.
peers[].height uint32 Blockchain height of the peer.
peers[].last_sent int64 Unix timestamp of the last bundle sent to the peer (UTC).
peers[].last_received int64 Unix timestamp of the last bundle received from the peer (UTC).
peers[].address string Network address of the peer.
peers[].direction Direction (Enum)Connection direction (e.g., inbound, outbound).
Available values:
  • DIRECTION_UNKNOWN = 0 (Unknown direction (default value).)
  • DIRECTION_INBOUND = 1 (Inbound connection - peer connected to us.)
  • DIRECTION_OUTBOUND = 2 (Outbound connection - we connected to peer.)
peers[].protocols repeated string List of protocols supported by the peer.
peers[].total_sessions int32 Total download sessions with the peer.
peers[].completed_sessions int32 Completed download sessions with the peer.
peers[].metric_info MetricInfo Metrics related to peer activity.
peers[].metric_info.total_invalid CounterInfo Total number of invalid bundles.
peers[].metric_info.total_sent CounterInfo Total number of bundles sent.
peers[].metric_info.total_received CounterInfo Total number of bundles received.
peers[].metric_info.message_sent map<int32, CounterInfo> Number of sent bundles categorized by message type.
peers[].metric_info.message_received map<int32, CounterInfo> Number of received bundles categorized by message type.
peers[].outbound_hello_sent bool Whether the hello message was sent from the outbound connection.
#### GetNodeInfo

GetNodeInfo retrieves information about a specific node in the network.

GetNodeInfoRequest Request

Request Message has no fields.

GetNodeInfoResponse Response

FieldTypeDescription
moniker string Moniker or Human-readable name identifying this node in the network.
agent string Version and agent details of the node.
peer_id string Peer ID of the node.
started_at uint64 Unix timestamp when the node was started (UTC).
reachability string Reachability status of the node.
services int32 Bitfield representing the services provided by the node.
services_names string Names of services provided by the node.
local_addrs repeated string List of addresses associated with the node.
protocols repeated string List of protocols supported by the node.
clock_offset double Offset between the node's clock and the network's clock (in seconds).
connection_info ConnectionInfo Information about the node's connections.
connection_info.connections uint64 Total number of connections.
connection_info.inbound_connections uint64 Number of inbound connections.
connection_info.outbound_connections uint64 Number of outbound connections.
zmq_publishers repeated ZMQPublisherInfo List of active ZeroMQ publishers.
zmq_publishers[].topic string The topic associated with the publisher.
zmq_publishers[].address string The address of the publisher.
zmq_publishers[].hwm int32 The high-water mark (HWM) for the publisher, indicating the maximum number of messages to queue before dropping older ones.
current_time uint64 Current Unix timestamp of the node (UTC).
network_name string Name of the P2P network.
#### Ping

Ping provides a simple connectivity test and latency measurement.

PingRequest Request

Request Message has no fields.

PingResponse Response

Response Message has no fields. ### Utils Service

Utils service defines RPC methods for utility functions such as message signing, verification, and other cryptographic operations.

#### SignMessageWithPrivateKey

SignMessageWithPrivateKey signs a message with the provided private key.

SignMessageWithPrivateKeyRequest Request

FieldTypeDescription
private_key string The private key to sign the message.
message string The message content to be signed.

SignMessageWithPrivateKeyResponse Response

FieldTypeDescription
signature string The resulting signature in hexadecimal format.
#### VerifyMessage

VerifyMessage verifies a signature against the public key and message.

VerifyMessageRequest Request

FieldTypeDescription
message string The original message content that was signed.
signature string The signature to verify in hexadecimal format.
public_key string The public key of the signer.

VerifyMessageResponse Response

FieldTypeDescription
is_valid bool Boolean indicating whether the signature is valid for the given message and public key.
#### PublicKeyAggregation

PublicKeyAggregation aggregates multiple BLS public keys into a single key.

PublicKeyAggregationRequest Request

FieldTypeDescription
public_keys repeated string List of BLS public keys to be aggregated.

PublicKeyAggregationResponse Response

FieldTypeDescription
public_key string The aggregated BLS public key.
address string The blockchain address derived from the aggregated public key.
#### SignatureAggregation

SignatureAggregation aggregates multiple BLS signatures into a single signature.

SignatureAggregationRequest Request

FieldTypeDescription
signatures repeated string List of BLS signatures to be aggregated.

SignatureAggregationResponse Response

FieldTypeDescription
signature string The aggregated BLS signature in hexadecimal format.
### Wallet Service

Wallet service provides RPC methods for wallet management operations.

#### CreateWallet

CreateWallet creates a new wallet with the specified parameters.

CreateWalletRequest Request

FieldTypeDescription
wallet_name string The name for the new wallet.
password string Password to secure the new wallet.

CreateWalletResponse Response

FieldTypeDescription
wallet_name string The name for the new wallet.
mnemonic string The mnemonic (seed phrase) for wallet recovery.
#### RestoreWallet

RestoreWallet restores an existing wallet with the given mnemonic.

RestoreWalletRequest Request

FieldTypeDescription
wallet_name string The name for the restored wallet.
mnemonic string The mnemonic (seed phrase) for wallet recovery.
password string Password to secure the restored wallet.

RestoreWalletResponse Response

FieldTypeDescription
wallet_name string The name of the restored wallet.
#### LoadWallet

LoadWallet loads an existing wallet with the given name. deprecated: It will be removed in a future version.

LoadWalletRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to load.

LoadWalletResponse Response

FieldTypeDescription
wallet_name string The name of the loaded wallet.
#### UnloadWallet

UnloadWallet unloads a currently loaded wallet with the specified name. deprecated: It will be removed in a future version.

UnloadWalletRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to unload.

UnloadWalletResponse Response

FieldTypeDescription
wallet_name string The name of the unloaded wallet.
#### ListWallets

ListWallets returns a list of all available wallets.

ListWalletsRequest Request

Request Message has no fields.

ListWalletsResponse Response

FieldTypeDescription
wallets repeated string Array of wallet names.
#### GetWalletInfo

GetWalletInfo returns detailed information about a specific wallet.

GetWalletInfoRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to query.

GetWalletInfoResponse Response

FieldTypeDescription
wallet_name string The name of the wallet.
version int32 The wallet format version.
network string The network the wallet is connected to (e.g., mainnet, testnet).
encrypted bool Indicates if the wallet is encrypted.
uuid string A unique identifier of the wallet.
created_at int64 Unix timestamp of wallet creation.
default_fee int64 The default fee of the wallet.
driver string The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
path string Path to the wallet file or storage location.
#### UpdatePassword

UpdatePassword updates the password of an existing wallet.

UpdatePasswordRequest Request

FieldTypeDescription
wallet_name string The name of the wallet whose password will be updated.
old_password string The current wallet password.
new_password string The new wallet password.

UpdatePasswordResponse Response

FieldTypeDescription
wallet_name string The name of the wallet whose password was updated.
#### GetTotalBalance

GetTotalBalance returns the total available balance of the wallet.

GetTotalBalanceRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to get the total balance.

GetTotalBalanceResponse Response

FieldTypeDescription
wallet_name string The name of the queried wallet.
total_balance int64 The total balance of the wallet in NanoPAC.
#### GetTotalStake

GetTotalStake returns the total stake amount in the wallet.

GetTotalStakeRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to get the total stake.

GetTotalStakeResponse Response

FieldTypeDescription
wallet_name string The name of the queried wallet.
total_stake int64 The total stake amount in NanoPAC.
#### GetValidatorAddress

GetValidatorAddress retrieves the validator address associated with a public key. Deprecated: Will move into utils.

GetValidatorAddressRequest Request

FieldTypeDescription
public_key string The public key of the validator.

GetValidatorAddressResponse Response

FieldTypeDescription
address string The validator address associated with the public key.
#### GetAddressInfo

GetAddressInfo returns detailed information about a specific address.

GetAddressInfoRequest Request

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
address string The address to query.

GetAddressInfoResponse Response

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
addr AddressInfo Detailed information about the address.
addr.address string The address string.
addr.public_key string The public key associated with the address.
addr.label string A human-readable label associated with the address.
addr.path string The Hierarchical Deterministic (HD) path of the address within the wallet.
#### SetAddressLabel

SetAddressLabel sets or updates the label for a given address.

SetAddressLabelRequest Request

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
password string Wallet password required for modification.
address string The address to label.
label string The new label for the address.

SetAddressLabelResponse Response

FieldTypeDescription
wallet_name string The name of the wallet where the address label was updated.
address string The address where the label was updated.
label string The new label for the address.
#### GetNewAddress

GetNewAddress generates a new address for the specified wallet.

GetNewAddressRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to generate a new address.
address_type AddressType (Enum)The type of address to generate.
Available values:
  • ADDRESS_TYPE_TREASURY = 0 (Treasury address type. Should not be used to generate new addresses.)
  • ADDRESS_TYPE_VALIDATOR = 1 (Validator address type used for validator nodes.)
  • ADDRESS_TYPE_BLS_ACCOUNT = 2 (Account address type with BLS signature scheme.)
  • ADDRESS_TYPE_ED25519_ACCOUNT = 3 (Account address type with Ed25519 signature scheme. Note: Generating a new Ed25519 address requires the wallet password.)
label string A label for the new address.
password string Password for the new address. It's required when address_type is Ed25519 type.

GetNewAddressResponse Response

FieldTypeDescription
wallet_name string The name of the wallet where address was generated.
addr AddressInfo Detailed information about the new address.
addr.address string The address string.
addr.public_key string The public key associated with the address.
addr.label string A human-readable label associated with the address.
addr.path string The Hierarchical Deterministic (HD) path of the address within the wallet.
#### ListAddresses

ListAddresses returns all addresses in the specified wallet.

ListAddressesRequest Request

FieldTypeDescription
wallet_name string The name of the queried wallet.
address_types repeated AddressType (Enum)Filter addresses by their types. If empty, all address types are included.
Available values:
  • ADDRESS_TYPE_TREASURY = 0 (Treasury address type. Should not be used to generate new addresses.)
  • ADDRESS_TYPE_VALIDATOR = 1 (Validator address type used for validator nodes.)
  • ADDRESS_TYPE_BLS_ACCOUNT = 2 (Account address type with BLS signature scheme.)
  • ADDRESS_TYPE_ED25519_ACCOUNT = 3 (Account address type with Ed25519 signature scheme. Note: Generating a new Ed25519 address requires the wallet password.)

ListAddressesResponse Response

FieldTypeDescription
wallet_name string The name of the queried wallet.
addrs repeated AddressInfo List of all addresses in the wallet with their details.
addrs[].address string The address string.
addrs[].public_key string The public key associated with the address.
addrs[].label string A human-readable label associated with the address.
addrs[].path string The Hierarchical Deterministic (HD) path of the address within the wallet.
#### SignMessage

SignMessage signs an arbitrary message using a wallet's private key.

SignMessageRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to sign with.
password string Wallet password required for signing.
address string The address whose private key should be used for signing the message.
message string The arbitrary message to be signed.

SignMessageResponse Response

FieldTypeDescription
signature string The signature in hexadecimal format.
#### SignRawTransaction

SignRawTransaction signs a raw transaction for a specified wallet.

SignRawTransactionRequest Request

FieldTypeDescription
wallet_name string The name of the wallet used for signing.
raw_transaction string The raw transaction data to be signed.
password string Wallet password required for signing.

SignRawTransactionResponse Response

FieldTypeDescription
transaction_id string The ID of the signed transaction.
signed_raw_transaction string The signed raw transaction data.
#### ListTransactions

ListTransactions returns a list of transactions for a wallet, optionally filtered by a specific address, with pagination support.

ListTransactionsRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to query transactions for.
address string Optional: The address to filter transactions. If empty or set to '*', transactions for all addresses in the wallet are included.
direction TxDirection (Enum)Filter transactions by direction relative to the wallet. Defaults to any direction if not set.
Available values:
  • TX_DIRECTION_ANY = 0 (include both incoming and outgoing transactions.)
  • TX_DIRECTION_INCOMING = 1 (Include only incoming transactions where the wallet receives funds.)
  • TX_DIRECTION_OUTGOING = 2 (Include only outgoing transactions where the wallet sends funds.)
count int32 Optional: The maximum number of transactions to return. Defaults to 10 if not set.
skip int32 Optional: The number of transactions to skip (for pagination). Defaults to 0 if not set.

ListTransactionsResponse Response

FieldTypeDescription
wallet_name string The name of the wallet queried.
txs repeated WalletTransactionInfo List of transactions for the wallet, filtered by the specified address if provided.
txs[].no int64 A sequence number for the transaction in the wallet.
txs[].tx_id string The unique ID of the transaction.
txs[].sender string The sender's address.
txs[].receiver string The receiver's address.
txs[].direction TxDirection (Enum)The direction of the transaction relative to the wallet.
Available values:
  • TX_DIRECTION_ANY = 0 (include both incoming and outgoing transactions.)
  • TX_DIRECTION_INCOMING = 1 (Include only incoming transactions where the wallet receives funds.)
  • TX_DIRECTION_OUTGOING = 2 (Include only outgoing transactions where the wallet sends funds.)
txs[].amount int64 The amount involved in the transaction in NanoPAC.
txs[].fee int64 The transaction fee in NanoPAC.
txs[].memo string A memo string for the transaction.
txs[].status TransactionStatus (Enum)The current status of the transaction.
Available values:
  • TRANSACTION_STATUS_PENDING = 0 (Pending status for transactions in the mempool.)
  • TRANSACTION_STATUS_CONFIRMED = 1 (Confirmed status for transactions included in a block.)
  • TRANSACTION_STATUS_FAILED = -1 (Failed status for transactions that were not successful.)
txs[].block_height uint32 The block height containing the transaction.
txs[].payload_type PayloadType (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
txs[].data bytes The raw transaction data.
txs[].comment string A comment associated with the transaction in the wallet.
txs[].created_at int64 Unix timestamp of when the transaction was created.
txs[].updated_at int64 Unix timestamp of when the transaction was last updated.
#### SetDefaultFee

SetDefaultFee sets the default fee for the wallet.

SetDefaultFeeRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to set the default fee.
amount int64 The default fee amount in NanoPAC.

SetDefaultFeeResponse Response

FieldTypeDescription
wallet_name string The name of the wallet where the default fee was updated.
#### GetMnemonic

GetMnemonic returns the mnemonic (seed phrase) for the wallet.

GetMnemonicRequest Request

FieldTypeDescription
wallet_name string The name of the wallet to get the mnemonic.
password string Wallet password.

GetMnemonicResponse Response

FieldTypeDescription
mnemonic string The mnemonic (seed phrase).
#### GetPrivateKey

GetPrivateKey returns the private key for a given address.

GetPrivateKeyRequest Request

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
password string Wallet password.
address string The address to get the private key.

GetPrivateKeyResponse Response

FieldTypeDescription
private_key string The private key in hexadecimal format.
## Scalar Value Types
.proto TypeGoC++RustJavaPython
double float64 double f64 double float
float float32 float f32 float float
int32 int32 int32 i32 int int
int64 int64 int64 i64 long int/long
uint32 uint32 uint32 u32 int int/long
uint64 uint64 uint64 u64 long int/long
sint32 int32 int32 i32 int int
sint64 int64 int64 i64 long int/long
fixed32 uint32 uint32 u64 int int
fixed64 uint64 uint64 u64 long int/long
sfixed32 int32 int32 i32 int int
sfixed64 int64 int64 i64 long int/long
bool bool bool bool boolean boolean
string string string String String str/unicode
bytes []byte string Vec<u8> ByteString str
================================================ FILE: www/grpc/gen/docs/json-rpc.md ================================================ --- title: JSON-RPC API Reference weight: 2 --- Every node in the Pactus network can be configured to use the [JSON-RPC](https://www.jsonrpc.org/specification) protocol for communication. Here, you can find the list of all JSON-RPC methods, params and result. ## Units All the amounts are in NanoPAC units, which are atomic and the smallest unit in the Pactus blockchain. Each PAC is equivalent to 1,000,000,000 or 109 NanoPACs. ## Packages For seamless integration with Pactus, you can use these client libraries: - [pactus-jsonrpc](https://www.npmjs.com/package/pactus-jsonrpc/) package for Javascript - [pactus-jsonrpc](https://pypi.org/project/pactus-jsonrpc/) package for Python - [pactus-jsonrpc](https://crates.io/crates/pactus-jsonrpc) package for Rust ## Example To call JSON-RPC methods, you need to create the JSON-RPC request: ```json { "jsonrpc": "2.0", "id": 1, "method": "pactus.network.get_node_info", "params": {} } ``` > Make sure you always add the `params` field, even if no parameters are needed, and ensure you use curly braces. Then you use the `curl` command to send the request to the node: ```bash curl --location 'http://localhost:8545/' \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "pactus.network.get_node_info", "params": {} }' ``` > Before sending the request, you need to enable the JSON-RPC service inside the > [configuration](/get-started/configuration/). ### Using Basic Auth If you have enabled the [gRPC Basic Authentication](/tutorials/grpc-sign-transactions/), then you need to set the `Authorization` header. ```bash curl --location 'http://localhost:8545/' \ --header 'Content-Type: application/json' \ --header 'Authorization: Basic ' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "pactus.blockchain.get_account", "params": { "address": "pc1z2r0fmu8sg2ffa0tgrr08gnefcxl2kq7wvquf8z" } }' ``` ## JSON-RPC Methods
### Transaction Service

Transaction service defines various RPC methods for interacting with transactions.

#### pactus.transaction.get_transaction

GetTransaction retrieves transaction details based on the provided request parameters.

Parameters

FieldTypeDescription
id string The unique ID of the transaction to retrieve.
verbosity numeric (Enum)The verbosity level for transaction details.
Available values:
  • TRANSACTION_VERBOSITY_DATA = 0 (Request transaction data only.)
  • TRANSACTION_VERBOSITY_INFO = 1 (Request detailed transaction information.)

Result

FieldTypeDescription
block_height numeric The height of the block containing the transaction.
block_time numeric The UNIX timestamp of the block containing the transaction.
transaction object (TransactionInfo) Detailed information about the transaction.
transaction.id string The unique ID of the transaction.
transaction.data string The raw transaction data in hexadecimal format.
transaction.version numeric The version of the transaction.
transaction.lock_time numeric The lock time for the transaction.
transaction.value numeric The value of the transaction in NanoPAC.
transaction.fee numeric The fee for the transaction in NanoPAC.
transaction.payload_type numeric (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
transaction.transfer object (PayloadTransfer) (OneOf)Transfer transaction payload.
transaction.transfer.sender string The sender's address.
transaction.transfer.receiver string The receiver's address.
transaction.transfer.amount numeric The amount to be transferred in NanoPAC.
transaction.bond object (PayloadBond) (OneOf)Bond transaction payload.
transaction.bond.sender string The sender's address.
transaction.bond.receiver string The receiver's address.
transaction.bond.stake numeric The stake amount in NanoPAC.
transaction.bond.public_key string The public key of the validator.
transaction.bond.is_delegated boolean Indicates whether the bond transaction is a delegation.
transaction.bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
transaction.bond.delegate_share numeric The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
transaction.bond.delegate_expiry numeric The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
transaction.sortition object (PayloadSortition) (OneOf)Sortition transaction payload.
transaction.sortition.address string The validator address associated with the sortition proof.
transaction.sortition.proof string The proof for the sortition.
transaction.unbond object (PayloadUnbond) (OneOf)Unbond transaction payload.
transaction.unbond.validator string The address of the validator to unbond from.
transaction.unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
transaction.withdraw object (PayloadWithdraw) (OneOf)Withdraw transaction payload.
transaction.withdraw.validator_address string The address of the validator to withdraw from.
transaction.withdraw.account_address string The address of the account to withdraw to.
transaction.withdraw.amount numeric The withdrawal amount in NanoPAC.
transaction.batch_transfer object (PayloadBatchTransfer) (OneOf)Batch Transfer transaction payload.
transaction.batch_transfer.sender string The sender's address.
transaction.batch_transfer.recipients repeated object (Recipient) The list of recipients with their amounts.
transaction.memo string A memo string for the transaction.
transaction.public_key string The public key associated with the transaction.
transaction.signature string The signature for the transaction.
transaction.block_height numeric The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
transaction.confirmed boolean Indicates whether the transaction is confirmed.
transaction.confirmations numeric The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
#### pactus.transaction.calculate_fee

CalculateFee calculates the transaction fee based on the specified amount and payload type.

Parameters

FieldTypeDescription
amount numeric The amount involved in the transaction, specified in NanoPAC.
payload_type numeric (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
fixed_amount boolean Indicates if the amount should be fixed and include the fee.

Result

FieldTypeDescription
amount numeric The calculated amount in NanoPAC.
fee numeric The calculated transaction fee in NanoPAC.
#### pactus.transaction.broadcast_transaction

BroadcastTransaction broadcasts a signed transaction to the network.

Parameters

FieldTypeDescription
signed_raw_transaction string The signed raw transaction data to be broadcasted.

Result

FieldTypeDescription
id string The unique ID of the broadcasted transaction.
#### pactus.transaction.get_raw_transfer_transaction

GetRawTransferTransaction retrieves raw details of a transfer transaction.

Parameters

FieldTypeDescription
lock_time numeric The lock time for the transaction. If not set, defaults to the last block height.
sender string The sender's account address.
receiver string The receiver's account address.
amount numeric The amount to be transferred, specified in NanoPAC. Must be greater than 0.
fee numeric The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.

Result

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### pactus.transaction.get_raw_bond_transaction

GetRawBondTransaction retrieves raw details of a bond transaction.

Parameters

FieldTypeDescription
lock_time numeric The lock time for the transaction. If not set, defaults to the last block height.
sender string The sender's account address.
receiver string The receiver's validator address.
stake numeric The stake amount in NanoPAC. Must be greater than 0.
public_key string The public key of the validator. Optional, but required when registering a new validator.;
fee numeric The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.
delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
delegate_share numeric The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
delegate_expiry numeric The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;

Result

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### pactus.transaction.get_raw_unbond_transaction

GetRawUnbondTransaction retrieves raw details of an unbond transaction.

Parameters

FieldTypeDescription
lock_time numeric The lock time for the transaction. If not set, defaults to the last block height.
validator_address string The address of the validator to unbond from.
memo string A memo string for the transaction.
delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;

Result

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### pactus.transaction.get_raw_withdraw_transaction

GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.

Parameters

FieldTypeDescription
lock_time numeric The lock time for the transaction. If not set, defaults to the last block height.
validator_address string The address of the validator to withdraw from.
account_address string The address of the account to withdraw to.
amount numeric The withdrawal amount in NanoPAC. Must be greater than 0.
fee numeric The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.

Result

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### pactus.transaction.get_raw_batch_transfer_transaction

GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.

Parameters

FieldTypeDescription
lock_time numeric The lock time for the transaction. If not set, defaults to the last block height.
sender string The sender's account address.
recipients repeated object (Recipient) The list of recipients with their amounts. Minimum 2 recipients required.
fee numeric The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
memo string A memo string for the transaction.

Result

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.
id string The unique ID of the transaction.
#### pactus.transaction.decode_raw_transaction

DecodeRawTransaction accepts raw transaction and returns decoded transaction.

Parameters

FieldTypeDescription
raw_transaction string The raw transaction data in hexadecimal format.

Result

FieldTypeDescription
transaction object (TransactionInfo) The decoded transaction information.
transaction.id string The unique ID of the transaction.
transaction.data string The raw transaction data in hexadecimal format.
transaction.version numeric The version of the transaction.
transaction.lock_time numeric The lock time for the transaction.
transaction.value numeric The value of the transaction in NanoPAC.
transaction.fee numeric The fee for the transaction in NanoPAC.
transaction.payload_type numeric (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
transaction.transfer object (PayloadTransfer) (OneOf)Transfer transaction payload.
transaction.transfer.sender string The sender's address.
transaction.transfer.receiver string The receiver's address.
transaction.transfer.amount numeric The amount to be transferred in NanoPAC.
transaction.bond object (PayloadBond) (OneOf)Bond transaction payload.
transaction.bond.sender string The sender's address.
transaction.bond.receiver string The receiver's address.
transaction.bond.stake numeric The stake amount in NanoPAC.
transaction.bond.public_key string The public key of the validator.
transaction.bond.is_delegated boolean Indicates whether the bond transaction is a delegation.
transaction.bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
transaction.bond.delegate_share numeric The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
transaction.bond.delegate_expiry numeric The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
transaction.sortition object (PayloadSortition) (OneOf)Sortition transaction payload.
transaction.sortition.address string The validator address associated with the sortition proof.
transaction.sortition.proof string The proof for the sortition.
transaction.unbond object (PayloadUnbond) (OneOf)Unbond transaction payload.
transaction.unbond.validator string The address of the validator to unbond from.
transaction.unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
transaction.withdraw object (PayloadWithdraw) (OneOf)Withdraw transaction payload.
transaction.withdraw.validator_address string The address of the validator to withdraw from.
transaction.withdraw.account_address string The address of the account to withdraw to.
transaction.withdraw.amount numeric The withdrawal amount in NanoPAC.
transaction.batch_transfer object (PayloadBatchTransfer) (OneOf)Batch Transfer transaction payload.
transaction.batch_transfer.sender string The sender's address.
transaction.batch_transfer.recipients repeated object (Recipient) The list of recipients with their amounts.
transaction.memo string A memo string for the transaction.
transaction.public_key string The public key associated with the transaction.
transaction.signature string The signature for the transaction.
transaction.block_height numeric The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
transaction.confirmed boolean Indicates whether the transaction is confirmed.
transaction.confirmations numeric The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
#### pactus.transaction.check_transaction

CheckTransaction checks if the transaction is valid and can be included in the blockchain.

Parameters

FieldTypeDescription
raw_transaction string The raw transaction data to be checked.

Result

FieldTypeDescription
is_valid boolean Indicates whether the transaction is valid.
error_message string An error message if the transaction is invalid. Empty if the transaction is valid.
### Blockchain Service

Blockchain service defines RPC methods for interacting with the blockchain.

#### pactus.blockchain.get_block

GetBlock retrieves information about a block based on the provided request parameters.

Parameters

FieldTypeDescription
height numeric The height of the block to retrieve.
verbosity numeric (Enum)The verbosity level for block information.
Available values:
  • BLOCK_VERBOSITY_DATA = 0 (Request only block data.)
  • BLOCK_VERBOSITY_INFO = 1 (Request block information and transaction IDs.)
  • BLOCK_VERBOSITY_TRANSACTIONS = 2 (Request block information and detailed transaction data.)

Result

FieldTypeDescription
height numeric The height of the block.
hash string The hash of the block.
data string Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
block_time numeric The timestamp of the block.
header object (BlockHeaderInfo) Header information of the block.
header.version numeric The version of the block.
header.prev_block_hash string The hash of the previous block.
header.state_root string The state root hash of the blockchain.
header.sortition_seed string The sortition seed of the block.
header.proposer_address string The address of the proposer of the block.
prev_cert object (CertificateInfo) Certificate information of the previous block.
prev_cert.hash string The hash of the certificate.
prev_cert.round numeric The round of the certificate.
prev_cert.committers repeated numeric List of committers in the certificate.
prev_cert.absentees repeated numeric List of absentees in the certificate.
prev_cert.signature string The signature of the certificate.
txs repeated object (TransactionInfo) List of transactions in the block, available when verbosity level is set to BLOCK_VERBOSITY_TRANSACTIONS.
txs[].id string The unique ID of the transaction.
txs[].data string The raw transaction data in hexadecimal format.
txs[].version numeric The version of the transaction.
txs[].lock_time numeric The lock time for the transaction.
txs[].value numeric The value of the transaction in NanoPAC.
txs[].fee numeric The fee for the transaction in NanoPAC.
txs[].payload_type numeric (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
txs[].transfer object (PayloadTransfer) (OneOf)Transfer transaction payload.
txs[].transfer.sender string The sender's address.
txs[].transfer.receiver string The receiver's address.
txs[].transfer.amount numeric The amount to be transferred in NanoPAC.
txs[].bond object (PayloadBond) (OneOf)Bond transaction payload.
txs[].bond.sender string The sender's address.
txs[].bond.receiver string The receiver's address.
txs[].bond.stake numeric The stake amount in NanoPAC.
txs[].bond.public_key string The public key of the validator.
txs[].bond.is_delegated boolean Indicates whether the bond transaction is a delegation.
txs[].bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
txs[].bond.delegate_share numeric The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
txs[].bond.delegate_expiry numeric The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
txs[].sortition object (PayloadSortition) (OneOf)Sortition transaction payload.
txs[].sortition.address string The validator address associated with the sortition proof.
txs[].sortition.proof string The proof for the sortition.
txs[].unbond object (PayloadUnbond) (OneOf)Unbond transaction payload.
txs[].unbond.validator string The address of the validator to unbond from.
txs[].unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
txs[].withdraw object (PayloadWithdraw) (OneOf)Withdraw transaction payload.
txs[].withdraw.validator_address string The address of the validator to withdraw from.
txs[].withdraw.account_address string The address of the account to withdraw to.
txs[].withdraw.amount numeric The withdrawal amount in NanoPAC.
txs[].batch_transfer object (PayloadBatchTransfer) (OneOf)Batch Transfer transaction payload.
txs[].batch_transfer.sender string The sender's address.
txs[].batch_transfer.recipients repeated object (Recipient) The list of recipients with their amounts.
txs[].memo string A memo string for the transaction.
txs[].public_key string The public key associated with the transaction.
txs[].signature string The signature for the transaction.
txs[].block_height numeric The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
txs[].confirmed boolean Indicates whether the transaction is confirmed.
txs[].confirmations numeric The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
#### pactus.blockchain.get_block_hash

GetBlockHash retrieves the hash of a block at the specified height.

Parameters

FieldTypeDescription
height numeric The height of the block to retrieve the hash for.

Result

FieldTypeDescription
hash string The hash of the block.
#### pactus.blockchain.get_block_height

GetBlockHeight retrieves the height of a block with the specified hash.

Parameters

FieldTypeDescription
hash string The hash of the block to retrieve the height for.

Result

FieldTypeDescription
height numeric The height of the block.
#### pactus.blockchain.get_blockchain_info

GetBlockchainInfo retrieves general information about the blockchain.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
last_block_height numeric The height of the last block in the blockchain.
last_block_hash string The hash of the last block in the blockchain.
last_block_time numeric The timestamp of the last block in Unix format.
total_accounts numeric The total number of accounts in the blockchain.
total_validators numeric The total number of validators in the blockchain.
active_validators numeric The number of active (not unbonded) validators in the blockchain.
total_power numeric The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
committee_power numeric The power of the committee.
is_pruned boolean If the blocks are subject to pruning.
pruning_height numeric Lowest-height block stored (only present if pruning is enabled)
in_committee boolean Indicates whether this node participates in consensus: true if at least one of its running validators is a member of the current committee.
committee_size numeric The number of validators in the current committee.
average_score numeric Average availability score of validators with stake, in percentage (0-100).
#### pactus.blockchain.get_committee_info

GetCommitteeInfo retrieves information about the current committee.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
committee_size numeric The number of validators in the committee.
committee_power numeric The power of the committee.
total_power numeric The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
validators repeated object (ValidatorInfo) List of committee validators.
validators[].hash string The hash of the validator.
validators[].data string The serialized data of the validator.
validators[].public_key string The public key of the validator.
validators[].number numeric The unique number assigned to the validator.
validators[].stake numeric The stake of the validator in NanoPAC.
validators[].last_bonding_height numeric The height at which the validator last bonded.
validators[].last_sortition_height numeric The height at which the validator last participated in sortition.
validators[].unbonding_height numeric The height at which the validator will unbond.
validators[].address string The address of the validator.
validators[].availability_score numeric The availability score of the validator.
validators[].protocol_version numeric The protocol version of the validator.
validators[].is_delegated boolean Whether the validator is delegated.
validators[].delegate_owner string The address of the stake owner of the validator.
validators[].delegate_share numeric The share of the stake owner of the validator.
validators[].delegate_expiry numeric The expiry of the stake owner of the validator.
protocol_versions map<int32, double> Map of protocol versions and their percentages in the committee.
#### pactus.blockchain.get_consensus_info

GetConsensusInfo retrieves information about the consensus instances.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
proposal object (ProposalInfo) The proposal of the consensus info.
proposal.height numeric The height of the proposal.
proposal.round numeric The round of the proposal.
proposal.block_data string The block data of the proposal.
proposal.signature string The signature of the proposal, signed by the proposer.
instances repeated object (ConsensusInfo) List of consensus instances.
instances[].address string The address of the consensus instance.
instances[].active boolean Indicates whether the consensus instance is active and part of the committee.
instances[].height numeric The height of the consensus instance.
instances[].round numeric The round of the consensus instance.
instances[].votes repeated object (VoteInfo) List of votes in the consensus instance.
instances[].votes[].type numeric (Enum)The type of the vote.
Available values:
  • VOTE_TYPE_UNSPECIFIED = 0 (Unspecified vote type.)
  • VOTE_TYPE_PREPARE = 1 (Prepare vote type.)
  • VOTE_TYPE_PRECOMMIT = 2 (Precommit vote type.)
  • VOTE_TYPE_CP_PRE_VOTE = 3 (Change-proposer:pre-vote vote type.)
  • VOTE_TYPE_CP_MAIN_VOTE = 4 (Change-proposer:main-vote vote type.)
  • VOTE_TYPE_CP_DECIDED = 5 (Change-proposer:decided vote type.)
instances[].votes[].voter string The address of the voter.
instances[].votes[].block_hash string The hash of the block being voted on.
instances[].votes[].round numeric The consensus round of the vote.
instances[].votes[].cp_round numeric The change-proposer round of the vote.
instances[].votes[].cp_value numeric The change-proposer value of the vote.
#### pactus.blockchain.get_account

GetAccount retrieves information about an account based on the provided address.

Parameters

FieldTypeDescription
address string The address of the account to retrieve information for.

Result

FieldTypeDescription
account object (AccountInfo) Detailed information about the account.
account.hash string The hash of the account.
account.data string The serialized data of the account.
account.number numeric The unique number assigned to the account.
account.balance numeric The balance of the account in NanoPAC.
account.address string The address of the account.
#### pactus.blockchain.get_validator

GetValidator retrieves information about a validator based on the provided address.

Parameters

FieldTypeDescription
address string The address of the validator to retrieve information for.

Result

FieldTypeDescription
validator object (ValidatorInfo) Detailed information about the validator.
validator.hash string The hash of the validator.
validator.data string The serialized data of the validator.
validator.public_key string The public key of the validator.
validator.number numeric The unique number assigned to the validator.
validator.stake numeric The stake of the validator in NanoPAC.
validator.last_bonding_height numeric The height at which the validator last bonded.
validator.last_sortition_height numeric The height at which the validator last participated in sortition.
validator.unbonding_height numeric The height at which the validator will unbond.
validator.address string The address of the validator.
validator.availability_score numeric The availability score of the validator.
validator.protocol_version numeric The protocol version of the validator.
validator.is_delegated boolean Whether the validator is delegated.
validator.delegate_owner string The address of the stake owner of the validator.
validator.delegate_share numeric The share of the stake owner of the validator.
validator.delegate_expiry numeric The expiry of the stake owner of the validator.
#### pactus.blockchain.get_validator_by_number

GetValidatorByNumber retrieves information about a validator based on the provided number.

Parameters

FieldTypeDescription
number numeric The unique number of the validator to retrieve information for.

Result

FieldTypeDescription
validator object (ValidatorInfo) Detailed information about the validator.
validator.hash string The hash of the validator.
validator.data string The serialized data of the validator.
validator.public_key string The public key of the validator.
validator.number numeric The unique number assigned to the validator.
validator.stake numeric The stake of the validator in NanoPAC.
validator.last_bonding_height numeric The height at which the validator last bonded.
validator.last_sortition_height numeric The height at which the validator last participated in sortition.
validator.unbonding_height numeric The height at which the validator will unbond.
validator.address string The address of the validator.
validator.availability_score numeric The availability score of the validator.
validator.protocol_version numeric The protocol version of the validator.
validator.is_delegated boolean Whether the validator is delegated.
validator.delegate_owner string The address of the stake owner of the validator.
validator.delegate_share numeric The share of the stake owner of the validator.
validator.delegate_expiry numeric The expiry of the stake owner of the validator.
#### pactus.blockchain.get_validator_addresses

GetValidatorAddresses retrieves a list of all validator addresses.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
addresses repeated string List of validator addresses.
#### pactus.blockchain.get_public_key

GetPublicKey retrieves the public key of an account based on the provided address.

Parameters

FieldTypeDescription
address string The address for which to retrieve the public key.

Result

FieldTypeDescription
public_key string The public key associated with the provided address.
#### pactus.blockchain.get_tx_pool_content

GetTxPoolContent retrieves current transactions in the transaction pool.

Parameters

FieldTypeDescription
payload_type numeric (Enum)The type of transactions to retrieve from the transaction pool. 0 means all types.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)

Result

FieldTypeDescription
txs repeated object (TransactionInfo) List of transactions currently in the pool.
txs[].id string The unique ID of the transaction.
txs[].data string The raw transaction data in hexadecimal format.
txs[].version numeric The version of the transaction.
txs[].lock_time numeric The lock time for the transaction.
txs[].value numeric The value of the transaction in NanoPAC.
txs[].fee numeric The fee for the transaction in NanoPAC.
txs[].payload_type numeric (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
txs[].transfer object (PayloadTransfer) (OneOf)Transfer transaction payload.
txs[].transfer.sender string The sender's address.
txs[].transfer.receiver string The receiver's address.
txs[].transfer.amount numeric The amount to be transferred in NanoPAC.
txs[].bond object (PayloadBond) (OneOf)Bond transaction payload.
txs[].bond.sender string The sender's address.
txs[].bond.receiver string The receiver's address.
txs[].bond.stake numeric The stake amount in NanoPAC.
txs[].bond.public_key string The public key of the validator.
txs[].bond.is_delegated boolean Indicates whether the bond transaction is a delegation.
txs[].bond.delegate_owner string The address of the delegate owner. Optional, but required when registering a new validator with delegation.;
txs[].bond.delegate_share numeric The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.
txs[].bond.delegate_expiry numeric The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;
txs[].sortition object (PayloadSortition) (OneOf)Sortition transaction payload.
txs[].sortition.address string The validator address associated with the sortition proof.
txs[].sortition.proof string The proof for the sortition.
txs[].unbond object (PayloadUnbond) (OneOf)Unbond transaction payload.
txs[].unbond.validator string The address of the validator to unbond from.
txs[].unbond.delegate_owner string The address of the delegate owner. Optional, but required when the validator is a delegated validator.;
txs[].withdraw object (PayloadWithdraw) (OneOf)Withdraw transaction payload.
txs[].withdraw.validator_address string The address of the validator to withdraw from.
txs[].withdraw.account_address string The address of the account to withdraw to.
txs[].withdraw.amount numeric The withdrawal amount in NanoPAC.
txs[].batch_transfer object (PayloadBatchTransfer) (OneOf)Batch Transfer transaction payload.
txs[].batch_transfer.sender string The sender's address.
txs[].batch_transfer.recipients repeated object (Recipient) The list of recipients with their amounts.
txs[].memo string A memo string for the transaction.
txs[].public_key string The public key associated with the transaction.
txs[].signature string The signature for the transaction.
txs[].block_height numeric The block height containing the transaction. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
txs[].confirmed boolean Indicates whether the transaction is confirmed.
txs[].confirmations numeric The number of blocks that have been added to the chain after this transaction was included in a block. A value of zero means the transaction is unconfirmed and may still in the transaction pool.
### Network Service

Network service provides RPCs for retrieving information about the network.

#### pactus.network.get_network_info

GetNetworkInfo retrieves information about the overall network.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
network_name string Name of the P2P network.
connected_peers_count numeric Number of connected peers.
metric_info object (MetricInfo) Metrics related to node activity.
metric_info.total_invalid object (CounterInfo) Total number of invalid bundles.
metric_info.total_invalid.bytes numeric Total number of bytes.
metric_info.total_invalid.bundles numeric Total number of bundles.
metric_info.total_sent object (CounterInfo) Total number of bundles sent.
metric_info.total_sent.bytes numeric Total number of bytes.
metric_info.total_sent.bundles numeric Total number of bundles.
metric_info.total_received object (CounterInfo) Total number of bundles received.
metric_info.total_received.bytes numeric Total number of bytes.
metric_info.total_received.bundles numeric Total number of bundles.
metric_info.message_sent map<int32, CounterInfo> Number of sent bundles categorized by message type.
metric_info.message_received map<int32, CounterInfo> Number of received bundles categorized by message type.
#### pactus.network.list_peers

ListPeers lists all peers in the network.

Parameters

FieldTypeDescription
include_disconnected boolean If true, includes disconnected peers (default: connected peers only).

Result

FieldTypeDescription
peers repeated object (PeerInfo) List of peers.
peers[].status numeric Current status of the peer (e.g., connected, disconnected).
peers[].moniker string Moniker or Human-Readable name of the peer.
peers[].agent string Version and agent details of the peer.
peers[].peer_id string Peer ID of the peer in P2P network.
peers[].consensus_keys repeated string List of consensus keys used by the peer.
peers[].consensus_addresses repeated string List of consensus addresses used by the peer.
peers[].services numeric Bitfield representing the services provided by the peer.
peers[].last_block_hash string Hash of the last block the peer knows.
peers[].height numeric Blockchain height of the peer.
peers[].last_sent numeric Unix timestamp of the last bundle sent to the peer (UTC).
peers[].last_received numeric Unix timestamp of the last bundle received from the peer (UTC).
peers[].address string Network address of the peer.
peers[].direction numeric (Enum)Connection direction (e.g., inbound, outbound).
Available values:
  • DIRECTION_UNKNOWN = 0 (Unknown direction (default value).)
  • DIRECTION_INBOUND = 1 (Inbound connection - peer connected to us.)
  • DIRECTION_OUTBOUND = 2 (Outbound connection - we connected to peer.)
peers[].protocols repeated string List of protocols supported by the peer.
peers[].total_sessions numeric Total download sessions with the peer.
peers[].completed_sessions numeric Completed download sessions with the peer.
peers[].metric_info object (MetricInfo) Metrics related to peer activity.
peers[].metric_info.total_invalid object (CounterInfo) Total number of invalid bundles.
peers[].metric_info.total_sent object (CounterInfo) Total number of bundles sent.
peers[].metric_info.total_received object (CounterInfo) Total number of bundles received.
peers[].metric_info.message_sent map<int32, CounterInfo> Number of sent bundles categorized by message type.
peers[].metric_info.message_received map<int32, CounterInfo> Number of received bundles categorized by message type.
peers[].outbound_hello_sent boolean Whether the hello message was sent from the outbound connection.
#### pactus.network.get_node_info

GetNodeInfo retrieves information about a specific node in the network.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
moniker string Moniker or Human-readable name identifying this node in the network.
agent string Version and agent details of the node.
peer_id string Peer ID of the node.
started_at numeric Unix timestamp when the node was started (UTC).
reachability string Reachability status of the node.
services numeric Bitfield representing the services provided by the node.
services_names string Names of services provided by the node.
local_addrs repeated string List of addresses associated with the node.
protocols repeated string List of protocols supported by the node.
clock_offset numeric Offset between the node's clock and the network's clock (in seconds).
connection_info object (ConnectionInfo) Information about the node's connections.
connection_info.connections numeric Total number of connections.
connection_info.inbound_connections numeric Number of inbound connections.
connection_info.outbound_connections numeric Number of outbound connections.
zmq_publishers repeated object (ZMQPublisherInfo) List of active ZeroMQ publishers.
zmq_publishers[].topic string The topic associated with the publisher.
zmq_publishers[].address string The address of the publisher.
zmq_publishers[].hwm numeric The high-water mark (HWM) for the publisher, indicating the maximum number of messages to queue before dropping older ones.
current_time numeric Current Unix timestamp of the node (UTC).
network_name string Name of the P2P network.
#### pactus.network.ping

Ping provides a simple connectivity test and latency measurement.

Parameters

Parameters has no fields.

Result

Result has no fields. ### Utils Service

Utils service defines RPC methods for utility functions such as message signing, verification, and other cryptographic operations.

#### pactus.utils.sign_message_with_private_key

SignMessageWithPrivateKey signs a message with the provided private key.

Parameters

FieldTypeDescription
private_key string The private key to sign the message.
message string The message content to be signed.

Result

FieldTypeDescription
signature string The resulting signature in hexadecimal format.
#### pactus.utils.verify_message

VerifyMessage verifies a signature against the public key and message.

Parameters

FieldTypeDescription
message string The original message content that was signed.
signature string The signature to verify in hexadecimal format.
public_key string The public key of the signer.

Result

FieldTypeDescription
is_valid boolean Boolean indicating whether the signature is valid for the given message and public key.
#### pactus.utils.public_key_aggregation

PublicKeyAggregation aggregates multiple BLS public keys into a single key.

Parameters

FieldTypeDescription
public_keys repeated string List of BLS public keys to be aggregated.

Result

FieldTypeDescription
public_key string The aggregated BLS public key.
address string The blockchain address derived from the aggregated public key.
#### pactus.utils.signature_aggregation

SignatureAggregation aggregates multiple BLS signatures into a single signature.

Parameters

FieldTypeDescription
signatures repeated string List of BLS signatures to be aggregated.

Result

FieldTypeDescription
signature string The aggregated BLS signature in hexadecimal format.
### Wallet Service

Wallet service provides RPC methods for wallet management operations.

#### pactus.wallet.create_wallet

CreateWallet creates a new wallet with the specified parameters.

Parameters

FieldTypeDescription
wallet_name string The name for the new wallet.
password string Password to secure the new wallet.

Result

FieldTypeDescription
wallet_name string The name for the new wallet.
mnemonic string The mnemonic (seed phrase) for wallet recovery.
#### pactus.wallet.restore_wallet

RestoreWallet restores an existing wallet with the given mnemonic.

Parameters

FieldTypeDescription
wallet_name string The name for the restored wallet.
mnemonic string The mnemonic (seed phrase) for wallet recovery.
password string Password to secure the restored wallet.

Result

FieldTypeDescription
wallet_name string The name of the restored wallet.
#### pactus.wallet.load_wallet

LoadWallet loads an existing wallet with the given name. deprecated: It will be removed in a future version.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to load.

Result

FieldTypeDescription
wallet_name string The name of the loaded wallet.
#### pactus.wallet.unload_wallet

UnloadWallet unloads a currently loaded wallet with the specified name. deprecated: It will be removed in a future version.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to unload.

Result

FieldTypeDescription
wallet_name string The name of the unloaded wallet.
#### pactus.wallet.list_wallets

ListWallets returns a list of all available wallets.

Parameters

Parameters has no fields.

Result

FieldTypeDescription
wallets repeated string Array of wallet names.
#### pactus.wallet.get_wallet_info

GetWalletInfo returns detailed information about a specific wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to query.

Result

FieldTypeDescription
wallet_name string The name of the wallet.
version numeric The wallet format version.
network string The network the wallet is connected to (e.g., mainnet, testnet).
encrypted boolean Indicates if the wallet is encrypted.
uuid string A unique identifier of the wallet.
created_at numeric Unix timestamp of wallet creation.
default_fee numeric The default fee of the wallet.
driver string The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
path string Path to the wallet file or storage location.
#### pactus.wallet.update_password

UpdatePassword updates the password of an existing wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet whose password will be updated.
old_password string The current wallet password.
new_password string The new wallet password.

Result

FieldTypeDescription
wallet_name string The name of the wallet whose password was updated.
#### pactus.wallet.get_total_balance

GetTotalBalance returns the total available balance of the wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to get the total balance.

Result

FieldTypeDescription
wallet_name string The name of the queried wallet.
total_balance numeric The total balance of the wallet in NanoPAC.
#### pactus.wallet.get_total_stake

GetTotalStake returns the total stake amount in the wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to get the total stake.

Result

FieldTypeDescription
wallet_name string The name of the queried wallet.
total_stake numeric The total stake amount in NanoPAC.
#### pactus.wallet.get_validator_address

GetValidatorAddress retrieves the validator address associated with a public key. Deprecated: Will move into utils.

Parameters

FieldTypeDescription
public_key string The public key of the validator.

Result

FieldTypeDescription
address string The validator address associated with the public key.
#### pactus.wallet.get_address_info

GetAddressInfo returns detailed information about a specific address.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
address string The address to query.

Result

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
addr object (AddressInfo) Detailed information about the address.
addr.address string The address string.
addr.public_key string The public key associated with the address.
addr.label string A human-readable label associated with the address.
addr.path string The Hierarchical Deterministic (HD) path of the address within the wallet.
#### pactus.wallet.set_address_label

SetAddressLabel sets or updates the label for a given address.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
password string Wallet password required for modification.
address string The address to label.
label string The new label for the address.

Result

FieldTypeDescription
wallet_name string The name of the wallet where the address label was updated.
address string The address where the label was updated.
label string The new label for the address.
#### pactus.wallet.get_new_address

GetNewAddress generates a new address for the specified wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to generate a new address.
address_type numeric (Enum)The type of address to generate.
Available values:
  • ADDRESS_TYPE_TREASURY = 0 (Treasury address type. Should not be used to generate new addresses.)
  • ADDRESS_TYPE_VALIDATOR = 1 (Validator address type used for validator nodes.)
  • ADDRESS_TYPE_BLS_ACCOUNT = 2 (Account address type with BLS signature scheme.)
  • ADDRESS_TYPE_ED25519_ACCOUNT = 3 (Account address type with Ed25519 signature scheme. Note: Generating a new Ed25519 address requires the wallet password.)
label string A label for the new address.
password string Password for the new address. It's required when address_type is Ed25519 type.

Result

FieldTypeDescription
wallet_name string The name of the wallet where address was generated.
addr object (AddressInfo) Detailed information about the new address.
addr.address string The address string.
addr.public_key string The public key associated with the address.
addr.label string A human-readable label associated with the address.
addr.path string The Hierarchical Deterministic (HD) path of the address within the wallet.
#### pactus.wallet.list_addresses

ListAddresses returns all addresses in the specified wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the queried wallet.
address_types repeated numeric (Enum)Filter addresses by their types. If empty, all address types are included.
Available values:
  • ADDRESS_TYPE_TREASURY = 0 (Treasury address type. Should not be used to generate new addresses.)
  • ADDRESS_TYPE_VALIDATOR = 1 (Validator address type used for validator nodes.)
  • ADDRESS_TYPE_BLS_ACCOUNT = 2 (Account address type with BLS signature scheme.)
  • ADDRESS_TYPE_ED25519_ACCOUNT = 3 (Account address type with Ed25519 signature scheme. Note: Generating a new Ed25519 address requires the wallet password.)

Result

FieldTypeDescription
wallet_name string The name of the queried wallet.
addrs repeated object (AddressInfo) List of all addresses in the wallet with their details.
addrs[].address string The address string.
addrs[].public_key string The public key associated with the address.
addrs[].label string A human-readable label associated with the address.
addrs[].path string The Hierarchical Deterministic (HD) path of the address within the wallet.
#### pactus.wallet.sign_message

SignMessage signs an arbitrary message using a wallet's private key.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to sign with.
password string Wallet password required for signing.
address string The address whose private key should be used for signing the message.
message string The arbitrary message to be signed.

Result

FieldTypeDescription
signature string The signature in hexadecimal format.
#### pactus.wallet.sign_raw_transaction

SignRawTransaction signs a raw transaction for a specified wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet used for signing.
raw_transaction string The raw transaction data to be signed.
password string Wallet password required for signing.

Result

FieldTypeDescription
transaction_id string The ID of the signed transaction.
signed_raw_transaction string The signed raw transaction data.
#### pactus.wallet.list_transactions

ListTransactions returns a list of transactions for a wallet, optionally filtered by a specific address, with pagination support.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to query transactions for.
address string Optional: The address to filter transactions. If empty or set to '*', transactions for all addresses in the wallet are included.
direction numeric (Enum)Filter transactions by direction relative to the wallet. Defaults to any direction if not set.
Available values:
  • TX_DIRECTION_ANY = 0 (include both incoming and outgoing transactions.)
  • TX_DIRECTION_INCOMING = 1 (Include only incoming transactions where the wallet receives funds.)
  • TX_DIRECTION_OUTGOING = 2 (Include only outgoing transactions where the wallet sends funds.)
count numeric Optional: The maximum number of transactions to return. Defaults to 10 if not set.
skip numeric Optional: The number of transactions to skip (for pagination). Defaults to 0 if not set.

Result

FieldTypeDescription
wallet_name string The name of the wallet queried.
txs repeated object (WalletTransactionInfo) List of transactions for the wallet, filtered by the specified address if provided.
txs[].no numeric A sequence number for the transaction in the wallet.
txs[].tx_id string The unique ID of the transaction.
txs[].sender string The sender's address.
txs[].receiver string The receiver's address.
txs[].direction numeric (Enum)The direction of the transaction relative to the wallet.
Available values:
  • TX_DIRECTION_ANY = 0 (include both incoming and outgoing transactions.)
  • TX_DIRECTION_INCOMING = 1 (Include only incoming transactions where the wallet receives funds.)
  • TX_DIRECTION_OUTGOING = 2 (Include only outgoing transactions where the wallet sends funds.)
txs[].amount numeric The amount involved in the transaction in NanoPAC.
txs[].fee numeric The transaction fee in NanoPAC.
txs[].memo string A memo string for the transaction.
txs[].status numeric (Enum)The current status of the transaction.
Available values:
  • TRANSACTION_STATUS_PENDING = 0 (Pending status for transactions in the mempool.)
  • TRANSACTION_STATUS_CONFIRMED = 1 (Confirmed status for transactions included in a block.)
  • TRANSACTION_STATUS_FAILED = -1 (Failed status for transactions that were not successful.)
txs[].block_height numeric The block height containing the transaction.
txs[].payload_type numeric (Enum)The type of transaction payload.
Available values:
  • PAYLOAD_TYPE_UNSPECIFIED = 0 (Unspecified payload type.)
  • PAYLOAD_TYPE_TRANSFER = 1 (Transfer payload type.)
  • PAYLOAD_TYPE_BOND = 2 (Bond payload type.)
  • PAYLOAD_TYPE_SORTITION = 3 (Sortition payload type.)
  • PAYLOAD_TYPE_UNBOND = 4 (Unbond payload type.)
  • PAYLOAD_TYPE_WITHDRAW = 5 (Withdraw payload type.)
  • PAYLOAD_TYPE_BATCH_TRANSFER = 6 (Batch transfer payload type.)
txs[].data string The raw transaction data.
txs[].comment string A comment associated with the transaction in the wallet.
txs[].created_at numeric Unix timestamp of when the transaction was created.
txs[].updated_at numeric Unix timestamp of when the transaction was last updated.
#### pactus.wallet.set_default_fee

SetDefaultFee sets the default fee for the wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to set the default fee.
amount numeric The default fee amount in NanoPAC.

Result

FieldTypeDescription
wallet_name string The name of the wallet where the default fee was updated.
#### pactus.wallet.get_mnemonic

GetMnemonic returns the mnemonic (seed phrase) for the wallet.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet to get the mnemonic.
password string Wallet password.

Result

FieldTypeDescription
mnemonic string The mnemonic (seed phrase).
#### pactus.wallet.get_private_key

GetPrivateKey returns the private key for a given address.

Parameters

FieldTypeDescription
wallet_name string The name of the wallet containing the address.
password string Wallet password.
address string The address to get the private key.

Result

FieldTypeDescription
private_key string The private key in hexadecimal format.
================================================ FILE: www/grpc/gen/go/blockchain.cobra.pb.go ================================================ // Code generated by protoc-gen-cobra. DO NOT EDIT. package pactus import ( client "github.com/NathanBaulch/protoc-gen-cobra/client" flag "github.com/NathanBaulch/protoc-gen-cobra/flag" iocodec "github.com/NathanBaulch/protoc-gen-cobra/iocodec" cobra "github.com/spf13/cobra" grpc "google.golang.org/grpc" proto "google.golang.org/protobuf/proto" ) func BlockchainClientCommand(options ...client.Option) *cobra.Command { cfg := client.NewConfig(options...) cmd := &cobra.Command{ Use: cfg.CommandNamer("Blockchain"), Short: "Blockchain service client", Long: "Blockchain service defines RPC methods for interacting with the blockchain.", } cfg.BindFlags(cmd.PersistentFlags()) cmd.AddCommand( _BlockchainGetBlockCommand(cfg), _BlockchainGetBlockHashCommand(cfg), _BlockchainGetBlockHeightCommand(cfg), _BlockchainGetBlockchainInfoCommand(cfg), _BlockchainGetCommitteeInfoCommand(cfg), _BlockchainGetConsensusInfoCommand(cfg), _BlockchainGetAccountCommand(cfg), _BlockchainGetValidatorCommand(cfg), _BlockchainGetValidatorByNumberCommand(cfg), _BlockchainGetValidatorAddressesCommand(cfg), _BlockchainGetPublicKeyCommand(cfg), _BlockchainGetTxPoolContentCommand(cfg), ) return cmd } func _BlockchainGetBlockCommand(cfg *client.Config) *cobra.Command { req := &GetBlockRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetBlock"), Short: "GetBlock RPC client", Long: "GetBlock retrieves information about a block based on the provided request parameters.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetBlock"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetBlockRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetBlock(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.Height, cfg.FlagNamer("Height"), 0, "The height of the block to retrieve.") flag.EnumVar(cmd.PersistentFlags(), &req.Verbosity, cfg.FlagNamer("Verbosity"), "The verbosity level for block information.") return cmd } func _BlockchainGetBlockHashCommand(cfg *client.Config) *cobra.Command { req := &GetBlockHashRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetBlockHash"), Short: "GetBlockHash RPC client", Long: "GetBlockHash retrieves the hash of a block at the specified height.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetBlockHash"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetBlockHashRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetBlockHash(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.Height, cfg.FlagNamer("Height"), 0, "The height of the block to retrieve the hash for.") return cmd } func _BlockchainGetBlockHeightCommand(cfg *client.Config) *cobra.Command { req := &GetBlockHeightRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetBlockHeight"), Short: "GetBlockHeight RPC client", Long: "GetBlockHeight retrieves the height of a block with the specified hash.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetBlockHeight"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetBlockHeightRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetBlockHeight(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.Hash, cfg.FlagNamer("Hash"), "", "The hash of the block to retrieve the height for.") return cmd } func _BlockchainGetBlockchainInfoCommand(cfg *client.Config) *cobra.Command { req := &GetBlockchainInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetBlockchainInfo"), Short: "GetBlockchainInfo RPC client", Long: "GetBlockchainInfo retrieves general information about the blockchain.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetBlockchainInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetBlockchainInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetBlockchainInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _BlockchainGetCommitteeInfoCommand(cfg *client.Config) *cobra.Command { req := &GetCommitteeInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetCommitteeInfo"), Short: "GetCommitteeInfo RPC client", Long: "GetCommitteeInfo retrieves information about the current committee.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetCommitteeInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetCommitteeInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetCommitteeInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _BlockchainGetConsensusInfoCommand(cfg *client.Config) *cobra.Command { req := &GetConsensusInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetConsensusInfo"), Short: "GetConsensusInfo RPC client", Long: "GetConsensusInfo retrieves information about the consensus instances.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetConsensusInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetConsensusInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetConsensusInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _BlockchainGetAccountCommand(cfg *client.Config) *cobra.Command { req := &GetAccountRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetAccount"), Short: "GetAccount RPC client", Long: "GetAccount retrieves information about an account based on the provided address.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetAccount"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetAccountRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetAccount(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address of the account to retrieve information for.") return cmd } func _BlockchainGetValidatorCommand(cfg *client.Config) *cobra.Command { req := &GetValidatorRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetValidator"), Short: "GetValidator RPC client", Long: "GetValidator retrieves information about a validator based on the provided address.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetValidator"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetValidatorRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetValidator(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address of the validator to retrieve information for.") return cmd } func _BlockchainGetValidatorByNumberCommand(cfg *client.Config) *cobra.Command { req := &GetValidatorByNumberRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetValidatorByNumber"), Short: "GetValidatorByNumber RPC client", Long: "GetValidatorByNumber retrieves information about a validator based on the provided number.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetValidatorByNumber"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetValidatorByNumberRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetValidatorByNumber(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Int32Var(&req.Number, cfg.FlagNamer("Number"), 0, "The unique number of the validator to retrieve information for.") return cmd } func _BlockchainGetValidatorAddressesCommand(cfg *client.Config) *cobra.Command { req := &GetValidatorAddressesRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetValidatorAddresses"), Short: "GetValidatorAddresses RPC client", Long: "GetValidatorAddresses retrieves a list of all validator addresses.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetValidatorAddresses"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetValidatorAddressesRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetValidatorAddresses(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _BlockchainGetPublicKeyCommand(cfg *client.Config) *cobra.Command { req := &GetPublicKeyRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetPublicKey"), Short: "GetPublicKey RPC client", Long: "GetPublicKey retrieves the public key of an account based on the provided address.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetPublicKey"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetPublicKeyRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetPublicKey(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address for which to retrieve the public key.") return cmd } func _BlockchainGetTxPoolContentCommand(cfg *client.Config) *cobra.Command { req := &GetTxPoolContentRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetTxPoolContent"), Short: "GetTxPoolContent RPC client", Long: "GetTxPoolContent retrieves current transactions in the transaction pool.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Blockchain", "GetTxPoolContent"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewBlockchainClient(cc) v := &GetTxPoolContentRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetTxPoolContent(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } flag.EnumVar(cmd.PersistentFlags(), &req.PayloadType, cfg.FlagNamer("PayloadType"), "The type of transactions to retrieve from the transaction pool. 0 means all types.") return cmd } ================================================ FILE: www/grpc/gen/go/blockchain.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: blockchain.proto package pactus import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Enumeration for verbosity levels when requesting block information. type BlockVerbosity int32 const ( // Request only block data. BlockVerbosity_BLOCK_VERBOSITY_DATA BlockVerbosity = 0 // Request block information and transaction IDs. BlockVerbosity_BLOCK_VERBOSITY_INFO BlockVerbosity = 1 // Request block information and detailed transaction data. BlockVerbosity_BLOCK_VERBOSITY_TRANSACTIONS BlockVerbosity = 2 ) // Enum value maps for BlockVerbosity. var ( BlockVerbosity_name = map[int32]string{ 0: "BLOCK_VERBOSITY_DATA", 1: "BLOCK_VERBOSITY_INFO", 2: "BLOCK_VERBOSITY_TRANSACTIONS", } BlockVerbosity_value = map[string]int32{ "BLOCK_VERBOSITY_DATA": 0, "BLOCK_VERBOSITY_INFO": 1, "BLOCK_VERBOSITY_TRANSACTIONS": 2, } ) func (x BlockVerbosity) Enum() *BlockVerbosity { p := new(BlockVerbosity) *p = x return p } func (x BlockVerbosity) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (BlockVerbosity) Descriptor() protoreflect.EnumDescriptor { return file_blockchain_proto_enumTypes[0].Descriptor() } func (BlockVerbosity) Type() protoreflect.EnumType { return &file_blockchain_proto_enumTypes[0] } func (x BlockVerbosity) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use BlockVerbosity.Descriptor instead. func (BlockVerbosity) EnumDescriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{0} } // Enumeration for types of votes. type VoteType int32 const ( // Unspecified vote type. VoteType_VOTE_TYPE_UNSPECIFIED VoteType = 0 // Prepare vote type. VoteType_VOTE_TYPE_PREPARE VoteType = 1 // Precommit vote type. VoteType_VOTE_TYPE_PRECOMMIT VoteType = 2 // Change-proposer:pre-vote vote type. VoteType_VOTE_TYPE_CP_PRE_VOTE VoteType = 3 // Change-proposer:main-vote vote type. VoteType_VOTE_TYPE_CP_MAIN_VOTE VoteType = 4 // Change-proposer:decided vote type. VoteType_VOTE_TYPE_CP_DECIDED VoteType = 5 ) // Enum value maps for VoteType. var ( VoteType_name = map[int32]string{ 0: "VOTE_TYPE_UNSPECIFIED", 1: "VOTE_TYPE_PREPARE", 2: "VOTE_TYPE_PRECOMMIT", 3: "VOTE_TYPE_CP_PRE_VOTE", 4: "VOTE_TYPE_CP_MAIN_VOTE", 5: "VOTE_TYPE_CP_DECIDED", } VoteType_value = map[string]int32{ "VOTE_TYPE_UNSPECIFIED": 0, "VOTE_TYPE_PREPARE": 1, "VOTE_TYPE_PRECOMMIT": 2, "VOTE_TYPE_CP_PRE_VOTE": 3, "VOTE_TYPE_CP_MAIN_VOTE": 4, "VOTE_TYPE_CP_DECIDED": 5, } ) func (x VoteType) Enum() *VoteType { p := new(VoteType) *p = x return p } func (x VoteType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (VoteType) Descriptor() protoreflect.EnumDescriptor { return file_blockchain_proto_enumTypes[1].Descriptor() } func (VoteType) Type() protoreflect.EnumType { return &file_blockchain_proto_enumTypes[1] } func (x VoteType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use VoteType.Descriptor instead. func (VoteType) EnumDescriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{1} } // Request message for retrieving account information. type GetAccountRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The address of the account to retrieve information for. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetAccountRequest) Reset() { *x = GetAccountRequest{} mi := &file_blockchain_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetAccountRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetAccountRequest) ProtoMessage() {} func (x *GetAccountRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetAccountRequest.ProtoReflect.Descriptor instead. func (*GetAccountRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{0} } func (x *GetAccountRequest) GetAddress() string { if x != nil { return x.Address } return "" } // Response message contains account information. type GetAccountResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Detailed information about the account. Account *AccountInfo `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetAccountResponse) Reset() { *x = GetAccountResponse{} mi := &file_blockchain_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetAccountResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetAccountResponse) ProtoMessage() {} func (x *GetAccountResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetAccountResponse.ProtoReflect.Descriptor instead. func (*GetAccountResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{1} } func (x *GetAccountResponse) GetAccount() *AccountInfo { if x != nil { return x.Account } return nil } // Request message for retrieving validator addresses. type GetValidatorAddressesRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorAddressesRequest) Reset() { *x = GetValidatorAddressesRequest{} mi := &file_blockchain_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorAddressesRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorAddressesRequest) ProtoMessage() {} func (x *GetValidatorAddressesRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorAddressesRequest.ProtoReflect.Descriptor instead. func (*GetValidatorAddressesRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{2} } // Response message contains list of validator addresses. type GetValidatorAddressesResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // List of validator addresses. Addresses []string `protobuf:"bytes,1,rep,name=addresses,proto3" json:"addresses,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorAddressesResponse) Reset() { *x = GetValidatorAddressesResponse{} mi := &file_blockchain_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorAddressesResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorAddressesResponse) ProtoMessage() {} func (x *GetValidatorAddressesResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorAddressesResponse.ProtoReflect.Descriptor instead. func (*GetValidatorAddressesResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{3} } func (x *GetValidatorAddressesResponse) GetAddresses() []string { if x != nil { return x.Addresses } return nil } // Request message for retrieving validator information by address. type GetValidatorRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The address of the validator to retrieve information for. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorRequest) Reset() { *x = GetValidatorRequest{} mi := &file_blockchain_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorRequest) ProtoMessage() {} func (x *GetValidatorRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorRequest.ProtoReflect.Descriptor instead. func (*GetValidatorRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{4} } func (x *GetValidatorRequest) GetAddress() string { if x != nil { return x.Address } return "" } // Request message for retrieving validator information by number. type GetValidatorByNumberRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The unique number of the validator to retrieve information for. Number int32 `protobuf:"varint,1,opt,name=number,proto3" json:"number,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorByNumberRequest) Reset() { *x = GetValidatorByNumberRequest{} mi := &file_blockchain_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorByNumberRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorByNumberRequest) ProtoMessage() {} func (x *GetValidatorByNumberRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorByNumberRequest.ProtoReflect.Descriptor instead. func (*GetValidatorByNumberRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{5} } func (x *GetValidatorByNumberRequest) GetNumber() int32 { if x != nil { return x.Number } return 0 } // Response message contains validator information. type GetValidatorResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Detailed information about the validator. Validator *ValidatorInfo `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorResponse) Reset() { *x = GetValidatorResponse{} mi := &file_blockchain_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorResponse) ProtoMessage() {} func (x *GetValidatorResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorResponse.ProtoReflect.Descriptor instead. func (*GetValidatorResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{6} } func (x *GetValidatorResponse) GetValidator() *ValidatorInfo { if x != nil { return x.Validator } return nil } // Request message for retrieving public key by address. type GetPublicKeyRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The address for which to retrieve the public key. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetPublicKeyRequest) Reset() { *x = GetPublicKeyRequest{} mi := &file_blockchain_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetPublicKeyRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetPublicKeyRequest) ProtoMessage() {} func (x *GetPublicKeyRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetPublicKeyRequest.ProtoReflect.Descriptor instead. func (*GetPublicKeyRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{7} } func (x *GetPublicKeyRequest) GetAddress() string { if x != nil { return x.Address } return "" } // Response message contains public key information. type GetPublicKeyResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The public key associated with the provided address. PublicKey string `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetPublicKeyResponse) Reset() { *x = GetPublicKeyResponse{} mi := &file_blockchain_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetPublicKeyResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetPublicKeyResponse) ProtoMessage() {} func (x *GetPublicKeyResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetPublicKeyResponse.ProtoReflect.Descriptor instead. func (*GetPublicKeyResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{8} } func (x *GetPublicKeyResponse) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } // Request message for retrieving block information based on height and verbosity level. type GetBlockRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the block to retrieve. Height uint32 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` // The verbosity level for block information. Verbosity BlockVerbosity `protobuf:"varint,2,opt,name=verbosity,proto3,enum=pactus.BlockVerbosity" json:"verbosity,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockRequest) Reset() { *x = GetBlockRequest{} mi := &file_blockchain_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockRequest) ProtoMessage() {} func (x *GetBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockRequest.ProtoReflect.Descriptor instead. func (*GetBlockRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{9} } func (x *GetBlockRequest) GetHeight() uint32 { if x != nil { return x.Height } return 0 } func (x *GetBlockRequest) GetVerbosity() BlockVerbosity { if x != nil { return x.Verbosity } return BlockVerbosity_BLOCK_VERBOSITY_DATA } // Response message contains block information. type GetBlockResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the block. Height uint32 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` // The hash of the block. Hash string `protobuf:"bytes,2,opt,name=hash,proto3" json:"hash,omitempty"` // Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA. Data string `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` // The timestamp of the block. BlockTime uint32 `protobuf:"varint,4,opt,name=block_time,json=blockTime,proto3" json:"block_time,omitempty"` // Header information of the block. Header *BlockHeaderInfo `protobuf:"bytes,5,opt,name=header,proto3" json:"header,omitempty"` // Certificate information of the previous block. PrevCert *CertificateInfo `protobuf:"bytes,6,opt,name=prev_cert,json=prevCert,proto3" json:"prev_cert,omitempty"` // List of transactions in the block, available when verbosity level is set to // BLOCK_VERBOSITY_TRANSACTIONS. Txs []*TransactionInfo `protobuf:"bytes,7,rep,name=txs,proto3" json:"txs,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockResponse) Reset() { *x = GetBlockResponse{} mi := &file_blockchain_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockResponse) ProtoMessage() {} func (x *GetBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockResponse.ProtoReflect.Descriptor instead. func (*GetBlockResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{10} } func (x *GetBlockResponse) GetHeight() uint32 { if x != nil { return x.Height } return 0 } func (x *GetBlockResponse) GetHash() string { if x != nil { return x.Hash } return "" } func (x *GetBlockResponse) GetData() string { if x != nil { return x.Data } return "" } func (x *GetBlockResponse) GetBlockTime() uint32 { if x != nil { return x.BlockTime } return 0 } func (x *GetBlockResponse) GetHeader() *BlockHeaderInfo { if x != nil { return x.Header } return nil } func (x *GetBlockResponse) GetPrevCert() *CertificateInfo { if x != nil { return x.PrevCert } return nil } func (x *GetBlockResponse) GetTxs() []*TransactionInfo { if x != nil { return x.Txs } return nil } // Request message for retrieving block hash by height. type GetBlockHashRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the block to retrieve the hash for. Height uint32 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockHashRequest) Reset() { *x = GetBlockHashRequest{} mi := &file_blockchain_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockHashRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockHashRequest) ProtoMessage() {} func (x *GetBlockHashRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockHashRequest.ProtoReflect.Descriptor instead. func (*GetBlockHashRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{11} } func (x *GetBlockHashRequest) GetHeight() uint32 { if x != nil { return x.Height } return 0 } // Response message contains block hash. type GetBlockHashResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The hash of the block. Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockHashResponse) Reset() { *x = GetBlockHashResponse{} mi := &file_blockchain_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockHashResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockHashResponse) ProtoMessage() {} func (x *GetBlockHashResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockHashResponse.ProtoReflect.Descriptor instead. func (*GetBlockHashResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{12} } func (x *GetBlockHashResponse) GetHash() string { if x != nil { return x.Hash } return "" } // Request message for retrieving block height by hash. type GetBlockHeightRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The hash of the block to retrieve the height for. Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockHeightRequest) Reset() { *x = GetBlockHeightRequest{} mi := &file_blockchain_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockHeightRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockHeightRequest) ProtoMessage() {} func (x *GetBlockHeightRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockHeightRequest.ProtoReflect.Descriptor instead. func (*GetBlockHeightRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{13} } func (x *GetBlockHeightRequest) GetHash() string { if x != nil { return x.Hash } return "" } // Response message contains block height. type GetBlockHeightResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the block. Height uint32 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockHeightResponse) Reset() { *x = GetBlockHeightResponse{} mi := &file_blockchain_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockHeightResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockHeightResponse) ProtoMessage() {} func (x *GetBlockHeightResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockHeightResponse.ProtoReflect.Descriptor instead. func (*GetBlockHeightResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{14} } func (x *GetBlockHeightResponse) GetHeight() uint32 { if x != nil { return x.Height } return 0 } // Request message for retrieving blockchain information. type GetBlockchainInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockchainInfoRequest) Reset() { *x = GetBlockchainInfoRequest{} mi := &file_blockchain_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockchainInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockchainInfoRequest) ProtoMessage() {} func (x *GetBlockchainInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockchainInfoRequest.ProtoReflect.Descriptor instead. func (*GetBlockchainInfoRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{15} } // Response message contains general blockchain information. type GetBlockchainInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the last block in the blockchain. LastBlockHeight uint32 `protobuf:"varint,1,opt,name=last_block_height,json=lastBlockHeight,proto3" json:"last_block_height,omitempty"` // The hash of the last block in the blockchain. LastBlockHash string `protobuf:"bytes,2,opt,name=last_block_hash,json=lastBlockHash,proto3" json:"last_block_hash,omitempty"` // The timestamp of the last block in Unix format. LastBlockTime int64 `protobuf:"varint,10,opt,name=last_block_time,json=lastBlockTime,proto3" json:"last_block_time,omitempty"` // The total number of accounts in the blockchain. TotalAccounts int32 `protobuf:"varint,3,opt,name=total_accounts,json=totalAccounts,proto3" json:"total_accounts,omitempty"` // The total number of validators in the blockchain. TotalValidators int32 `protobuf:"varint,4,opt,name=total_validators,json=totalValidators,proto3" json:"total_validators,omitempty"` // The number of active (not unbonded) validators in the blockchain. ActiveValidators int32 `protobuf:"varint,12,opt,name=active_validators,json=activeValidators,proto3" json:"active_validators,omitempty"` // The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. TotalPower int64 `protobuf:"varint,5,opt,name=total_power,json=totalPower,proto3" json:"total_power,omitempty"` // The power of the committee. CommitteePower int64 `protobuf:"varint,6,opt,name=committee_power,json=committeePower,proto3" json:"committee_power,omitempty"` // If the blocks are subject to pruning. IsPruned bool `protobuf:"varint,8,opt,name=is_pruned,json=isPruned,proto3" json:"is_pruned,omitempty"` // Lowest-height block stored (only present if pruning is enabled) PruningHeight uint32 `protobuf:"varint,9,opt,name=pruning_height,json=pruningHeight,proto3" json:"pruning_height,omitempty"` // Indicates whether this node participates in consensus: true if at least one // of its running validators is a member of the current committee. InCommittee bool `protobuf:"varint,13,opt,name=in_committee,json=inCommittee,proto3" json:"in_committee,omitempty"` // The number of validators in the current committee. CommitteeSize int32 `protobuf:"varint,14,opt,name=committee_size,json=committeeSize,proto3" json:"committee_size,omitempty"` // Average availability score of validators with stake, in percentage (0-100). AverageScore float64 `protobuf:"fixed64,15,opt,name=average_score,json=averageScore,proto3" json:"average_score,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBlockchainInfoResponse) Reset() { *x = GetBlockchainInfoResponse{} mi := &file_blockchain_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBlockchainInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBlockchainInfoResponse) ProtoMessage() {} func (x *GetBlockchainInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBlockchainInfoResponse.ProtoReflect.Descriptor instead. func (*GetBlockchainInfoResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{16} } func (x *GetBlockchainInfoResponse) GetLastBlockHeight() uint32 { if x != nil { return x.LastBlockHeight } return 0 } func (x *GetBlockchainInfoResponse) GetLastBlockHash() string { if x != nil { return x.LastBlockHash } return "" } func (x *GetBlockchainInfoResponse) GetLastBlockTime() int64 { if x != nil { return x.LastBlockTime } return 0 } func (x *GetBlockchainInfoResponse) GetTotalAccounts() int32 { if x != nil { return x.TotalAccounts } return 0 } func (x *GetBlockchainInfoResponse) GetTotalValidators() int32 { if x != nil { return x.TotalValidators } return 0 } func (x *GetBlockchainInfoResponse) GetActiveValidators() int32 { if x != nil { return x.ActiveValidators } return 0 } func (x *GetBlockchainInfoResponse) GetTotalPower() int64 { if x != nil { return x.TotalPower } return 0 } func (x *GetBlockchainInfoResponse) GetCommitteePower() int64 { if x != nil { return x.CommitteePower } return 0 } func (x *GetBlockchainInfoResponse) GetIsPruned() bool { if x != nil { return x.IsPruned } return false } func (x *GetBlockchainInfoResponse) GetPruningHeight() uint32 { if x != nil { return x.PruningHeight } return 0 } func (x *GetBlockchainInfoResponse) GetInCommittee() bool { if x != nil { return x.InCommittee } return false } func (x *GetBlockchainInfoResponse) GetCommitteeSize() int32 { if x != nil { return x.CommitteeSize } return 0 } func (x *GetBlockchainInfoResponse) GetAverageScore() float64 { if x != nil { return x.AverageScore } return 0 } // Request message for retrieving committee information. type GetCommitteeInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetCommitteeInfoRequest) Reset() { *x = GetCommitteeInfoRequest{} mi := &file_blockchain_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetCommitteeInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetCommitteeInfoRequest) ProtoMessage() {} func (x *GetCommitteeInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetCommitteeInfoRequest.ProtoReflect.Descriptor instead. func (*GetCommitteeInfoRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{17} } // Response message contains committee information. type GetCommitteeInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The number of validators in the committee. CommitteeSize int32 `protobuf:"varint,1,opt,name=committee_size,json=committeeSize,proto3" json:"committee_size,omitempty"` // The power of the committee. CommitteePower int64 `protobuf:"varint,2,opt,name=committee_power,json=committeePower,proto3" json:"committee_power,omitempty"` // The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. TotalPower int64 `protobuf:"varint,3,opt,name=total_power,json=totalPower,proto3" json:"total_power,omitempty"` // List of committee validators. Validators []*ValidatorInfo `protobuf:"bytes,4,rep,name=validators,proto3" json:"validators,omitempty"` // Map of protocol versions and their percentages in the committee. ProtocolVersions map[int32]float64 `protobuf:"bytes,5,rep,name=protocol_versions,json=protocolVersions,proto3" json:"protocol_versions,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetCommitteeInfoResponse) Reset() { *x = GetCommitteeInfoResponse{} mi := &file_blockchain_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetCommitteeInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetCommitteeInfoResponse) ProtoMessage() {} func (x *GetCommitteeInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetCommitteeInfoResponse.ProtoReflect.Descriptor instead. func (*GetCommitteeInfoResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{18} } func (x *GetCommitteeInfoResponse) GetCommitteeSize() int32 { if x != nil { return x.CommitteeSize } return 0 } func (x *GetCommitteeInfoResponse) GetCommitteePower() int64 { if x != nil { return x.CommitteePower } return 0 } func (x *GetCommitteeInfoResponse) GetTotalPower() int64 { if x != nil { return x.TotalPower } return 0 } func (x *GetCommitteeInfoResponse) GetValidators() []*ValidatorInfo { if x != nil { return x.Validators } return nil } func (x *GetCommitteeInfoResponse) GetProtocolVersions() map[int32]float64 { if x != nil { return x.ProtocolVersions } return nil } // Request message for retrieving consensus information. type GetConsensusInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetConsensusInfoRequest) Reset() { *x = GetConsensusInfoRequest{} mi := &file_blockchain_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetConsensusInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetConsensusInfoRequest) ProtoMessage() {} func (x *GetConsensusInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetConsensusInfoRequest.ProtoReflect.Descriptor instead. func (*GetConsensusInfoRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{19} } // Response message contains consensus information. type GetConsensusInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The proposal of the consensus info. Proposal *ProposalInfo `protobuf:"bytes,1,opt,name=proposal,proto3" json:"proposal,omitempty"` // List of consensus instances. Instances []*ConsensusInfo `protobuf:"bytes,2,rep,name=instances,proto3" json:"instances,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetConsensusInfoResponse) Reset() { *x = GetConsensusInfoResponse{} mi := &file_blockchain_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetConsensusInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetConsensusInfoResponse) ProtoMessage() {} func (x *GetConsensusInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetConsensusInfoResponse.ProtoReflect.Descriptor instead. func (*GetConsensusInfoResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{20} } func (x *GetConsensusInfoResponse) GetProposal() *ProposalInfo { if x != nil { return x.Proposal } return nil } func (x *GetConsensusInfoResponse) GetInstances() []*ConsensusInfo { if x != nil { return x.Instances } return nil } // Request message for retrieving transactions in the transaction pool. type GetTxPoolContentRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The type of transactions to retrieve from the transaction pool. 0 means all types. PayloadType PayloadType `protobuf:"varint,1,opt,name=payload_type,json=payloadType,proto3,enum=pactus.PayloadType" json:"payload_type,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTxPoolContentRequest) Reset() { *x = GetTxPoolContentRequest{} mi := &file_blockchain_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTxPoolContentRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTxPoolContentRequest) ProtoMessage() {} func (x *GetTxPoolContentRequest) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTxPoolContentRequest.ProtoReflect.Descriptor instead. func (*GetTxPoolContentRequest) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{21} } func (x *GetTxPoolContentRequest) GetPayloadType() PayloadType { if x != nil { return x.PayloadType } return PayloadType_PAYLOAD_TYPE_UNSPECIFIED } // Response message contains transactions in the transaction pool. type GetTxPoolContentResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // List of transactions currently in the pool. Txs []*TransactionInfo `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTxPoolContentResponse) Reset() { *x = GetTxPoolContentResponse{} mi := &file_blockchain_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTxPoolContentResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTxPoolContentResponse) ProtoMessage() {} func (x *GetTxPoolContentResponse) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTxPoolContentResponse.ProtoReflect.Descriptor instead. func (*GetTxPoolContentResponse) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{22} } func (x *GetTxPoolContentResponse) GetTxs() []*TransactionInfo { if x != nil { return x.Txs } return nil } // Message contains information about a validator. type ValidatorInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The hash of the validator. Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` // The serialized data of the validator. Data string `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` // The public key of the validator. PublicKey string `protobuf:"bytes,3,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // The unique number assigned to the validator. Number int32 `protobuf:"varint,4,opt,name=number,proto3" json:"number,omitempty"` // The stake of the validator in NanoPAC. Stake int64 `protobuf:"varint,5,opt,name=stake,proto3" json:"stake,omitempty"` // The height at which the validator last bonded. LastBondingHeight uint32 `protobuf:"varint,6,opt,name=last_bonding_height,json=lastBondingHeight,proto3" json:"last_bonding_height,omitempty"` // The height at which the validator last participated in sortition. LastSortitionHeight uint32 `protobuf:"varint,7,opt,name=last_sortition_height,json=lastSortitionHeight,proto3" json:"last_sortition_height,omitempty"` // The height at which the validator will unbond. UnbondingHeight uint32 `protobuf:"varint,8,opt,name=unbonding_height,json=unbondingHeight,proto3" json:"unbonding_height,omitempty"` // The address of the validator. Address string `protobuf:"bytes,9,opt,name=address,proto3" json:"address,omitempty"` // The availability score of the validator. AvailabilityScore float64 `protobuf:"fixed64,10,opt,name=availability_score,json=availabilityScore,proto3" json:"availability_score,omitempty"` // The protocol version of the validator. ProtocolVersion int32 `protobuf:"varint,11,opt,name=protocol_version,json=protocolVersion,proto3" json:"protocol_version,omitempty"` // Whether the validator is delegated. IsDelegated bool `protobuf:"varint,12,opt,name=is_delegated,json=isDelegated,proto3" json:"is_delegated,omitempty"` // The address of the stake owner of the validator. DelegateOwner string `protobuf:"bytes,13,opt,name=delegate_owner,json=delegateOwner,proto3" json:"delegate_owner,omitempty"` // The share of the stake owner of the validator. DelegateShare int64 `protobuf:"varint,14,opt,name=delegate_share,json=delegateShare,proto3" json:"delegate_share,omitempty"` // The expiry of the stake owner of the validator. DelegateExpiry uint32 `protobuf:"varint,15,opt,name=delegate_expiry,json=delegateExpiry,proto3" json:"delegate_expiry,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ValidatorInfo) Reset() { *x = ValidatorInfo{} mi := &file_blockchain_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ValidatorInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*ValidatorInfo) ProtoMessage() {} func (x *ValidatorInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ValidatorInfo.ProtoReflect.Descriptor instead. func (*ValidatorInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{23} } func (x *ValidatorInfo) GetHash() string { if x != nil { return x.Hash } return "" } func (x *ValidatorInfo) GetData() string { if x != nil { return x.Data } return "" } func (x *ValidatorInfo) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *ValidatorInfo) GetNumber() int32 { if x != nil { return x.Number } return 0 } func (x *ValidatorInfo) GetStake() int64 { if x != nil { return x.Stake } return 0 } func (x *ValidatorInfo) GetLastBondingHeight() uint32 { if x != nil { return x.LastBondingHeight } return 0 } func (x *ValidatorInfo) GetLastSortitionHeight() uint32 { if x != nil { return x.LastSortitionHeight } return 0 } func (x *ValidatorInfo) GetUnbondingHeight() uint32 { if x != nil { return x.UnbondingHeight } return 0 } func (x *ValidatorInfo) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ValidatorInfo) GetAvailabilityScore() float64 { if x != nil { return x.AvailabilityScore } return 0 } func (x *ValidatorInfo) GetProtocolVersion() int32 { if x != nil { return x.ProtocolVersion } return 0 } func (x *ValidatorInfo) GetIsDelegated() bool { if x != nil { return x.IsDelegated } return false } func (x *ValidatorInfo) GetDelegateOwner() string { if x != nil { return x.DelegateOwner } return "" } func (x *ValidatorInfo) GetDelegateShare() int64 { if x != nil { return x.DelegateShare } return 0 } func (x *ValidatorInfo) GetDelegateExpiry() uint32 { if x != nil { return x.DelegateExpiry } return 0 } // Message contains information about an account. type AccountInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The hash of the account. Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` // The serialized data of the account. Data string `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` // The unique number assigned to the account. Number int32 `protobuf:"varint,3,opt,name=number,proto3" json:"number,omitempty"` // The balance of the account in NanoPAC. Balance int64 `protobuf:"varint,4,opt,name=balance,proto3" json:"balance,omitempty"` // The address of the account. Address string `protobuf:"bytes,5,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AccountInfo) Reset() { *x = AccountInfo{} mi := &file_blockchain_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AccountInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*AccountInfo) ProtoMessage() {} func (x *AccountInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AccountInfo.ProtoReflect.Descriptor instead. func (*AccountInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{24} } func (x *AccountInfo) GetHash() string { if x != nil { return x.Hash } return "" } func (x *AccountInfo) GetData() string { if x != nil { return x.Data } return "" } func (x *AccountInfo) GetNumber() int32 { if x != nil { return x.Number } return 0 } func (x *AccountInfo) GetBalance() int64 { if x != nil { return x.Balance } return 0 } func (x *AccountInfo) GetAddress() string { if x != nil { return x.Address } return "" } // Message contains information about the header of a block. type BlockHeaderInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The version of the block. Version int32 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` // The hash of the previous block. PrevBlockHash string `protobuf:"bytes,2,opt,name=prev_block_hash,json=prevBlockHash,proto3" json:"prev_block_hash,omitempty"` // The state root hash of the blockchain. StateRoot string `protobuf:"bytes,3,opt,name=state_root,json=stateRoot,proto3" json:"state_root,omitempty"` // The sortition seed of the block. SortitionSeed string `protobuf:"bytes,4,opt,name=sortition_seed,json=sortitionSeed,proto3" json:"sortition_seed,omitempty"` // The address of the proposer of the block. ProposerAddress string `protobuf:"bytes,5,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *BlockHeaderInfo) Reset() { *x = BlockHeaderInfo{} mi := &file_blockchain_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *BlockHeaderInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*BlockHeaderInfo) ProtoMessage() {} func (x *BlockHeaderInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BlockHeaderInfo.ProtoReflect.Descriptor instead. func (*BlockHeaderInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{25} } func (x *BlockHeaderInfo) GetVersion() int32 { if x != nil { return x.Version } return 0 } func (x *BlockHeaderInfo) GetPrevBlockHash() string { if x != nil { return x.PrevBlockHash } return "" } func (x *BlockHeaderInfo) GetStateRoot() string { if x != nil { return x.StateRoot } return "" } func (x *BlockHeaderInfo) GetSortitionSeed() string { if x != nil { return x.SortitionSeed } return "" } func (x *BlockHeaderInfo) GetProposerAddress() string { if x != nil { return x.ProposerAddress } return "" } // Message contains information about a certificate. type CertificateInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The hash of the certificate. Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` // The round of the certificate. Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` // List of committers in the certificate. Committers []int32 `protobuf:"varint,3,rep,packed,name=committers,proto3" json:"committers,omitempty"` // List of absentees in the certificate. Absentees []int32 `protobuf:"varint,4,rep,packed,name=absentees,proto3" json:"absentees,omitempty"` // The signature of the certificate. Signature string `protobuf:"bytes,5,opt,name=signature,proto3" json:"signature,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CertificateInfo) Reset() { *x = CertificateInfo{} mi := &file_blockchain_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CertificateInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*CertificateInfo) ProtoMessage() {} func (x *CertificateInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CertificateInfo.ProtoReflect.Descriptor instead. func (*CertificateInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{26} } func (x *CertificateInfo) GetHash() string { if x != nil { return x.Hash } return "" } func (x *CertificateInfo) GetRound() int32 { if x != nil { return x.Round } return 0 } func (x *CertificateInfo) GetCommitters() []int32 { if x != nil { return x.Committers } return nil } func (x *CertificateInfo) GetAbsentees() []int32 { if x != nil { return x.Absentees } return nil } func (x *CertificateInfo) GetSignature() string { if x != nil { return x.Signature } return "" } // Message contains information about a vote. type VoteInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The type of the vote. Type VoteType `protobuf:"varint,1,opt,name=type,proto3,enum=pactus.VoteType" json:"type,omitempty"` // The address of the voter. Voter string `protobuf:"bytes,2,opt,name=voter,proto3" json:"voter,omitempty"` // The hash of the block being voted on. BlockHash string `protobuf:"bytes,3,opt,name=block_hash,json=blockHash,proto3" json:"block_hash,omitempty"` // The consensus round of the vote. Round int32 `protobuf:"varint,4,opt,name=round,proto3" json:"round,omitempty"` // The change-proposer round of the vote. CpRound int32 `protobuf:"varint,5,opt,name=cp_round,json=cpRound,proto3" json:"cp_round,omitempty"` // The change-proposer value of the vote. CpValue int32 `protobuf:"varint,6,opt,name=cp_value,json=cpValue,proto3" json:"cp_value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *VoteInfo) Reset() { *x = VoteInfo{} mi := &file_blockchain_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *VoteInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*VoteInfo) ProtoMessage() {} func (x *VoteInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use VoteInfo.ProtoReflect.Descriptor instead. func (*VoteInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{27} } func (x *VoteInfo) GetType() VoteType { if x != nil { return x.Type } return VoteType_VOTE_TYPE_UNSPECIFIED } func (x *VoteInfo) GetVoter() string { if x != nil { return x.Voter } return "" } func (x *VoteInfo) GetBlockHash() string { if x != nil { return x.BlockHash } return "" } func (x *VoteInfo) GetRound() int32 { if x != nil { return x.Round } return 0 } func (x *VoteInfo) GetCpRound() int32 { if x != nil { return x.CpRound } return 0 } func (x *VoteInfo) GetCpValue() int32 { if x != nil { return x.CpValue } return 0 } // Message contains information about a consensus instance. type ConsensusInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The address of the consensus instance. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` // Indicates whether the consensus instance is active and part of the committee. Active bool `protobuf:"varint,2,opt,name=active,proto3" json:"active,omitempty"` // The height of the consensus instance. Height uint32 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` // The round of the consensus instance. Round int32 `protobuf:"varint,4,opt,name=round,proto3" json:"round,omitempty"` // List of votes in the consensus instance. Votes []*VoteInfo `protobuf:"bytes,5,rep,name=votes,proto3" json:"votes,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ConsensusInfo) Reset() { *x = ConsensusInfo{} mi := &file_blockchain_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ConsensusInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusInfo) ProtoMessage() {} func (x *ConsensusInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusInfo.ProtoReflect.Descriptor instead. func (*ConsensusInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{28} } func (x *ConsensusInfo) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ConsensusInfo) GetActive() bool { if x != nil { return x.Active } return false } func (x *ConsensusInfo) GetHeight() uint32 { if x != nil { return x.Height } return 0 } func (x *ConsensusInfo) GetRound() int32 { if x != nil { return x.Round } return 0 } func (x *ConsensusInfo) GetVotes() []*VoteInfo { if x != nil { return x.Votes } return nil } // Message contains information about a proposal. type ProposalInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the proposal. Height uint32 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` // The round of the proposal. Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"` // The block data of the proposal. BlockData string `protobuf:"bytes,3,opt,name=block_data,json=blockData,proto3" json:"block_data,omitempty"` // The signature of the proposal, signed by the proposer. Signature string `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ProposalInfo) Reset() { *x = ProposalInfo{} mi := &file_blockchain_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ProposalInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*ProposalInfo) ProtoMessage() {} func (x *ProposalInfo) ProtoReflect() protoreflect.Message { mi := &file_blockchain_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ProposalInfo.ProtoReflect.Descriptor instead. func (*ProposalInfo) Descriptor() ([]byte, []int) { return file_blockchain_proto_rawDescGZIP(), []int{29} } func (x *ProposalInfo) GetHeight() uint32 { if x != nil { return x.Height } return 0 } func (x *ProposalInfo) GetRound() int32 { if x != nil { return x.Round } return 0 } func (x *ProposalInfo) GetBlockData() string { if x != nil { return x.BlockData } return "" } func (x *ProposalInfo) GetSignature() string { if x != nil { return x.Signature } return "" } var File_blockchain_proto protoreflect.FileDescriptor const file_blockchain_proto_rawDesc = "" + "\n" + "\x10blockchain.proto\x12\x06pactus\x1a\x11transaction.proto\"-\n" + "\x11GetAccountRequest\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\"C\n" + "\x12GetAccountResponse\x12-\n" + "\aaccount\x18\x01 \x01(\v2\x13.pactus.AccountInfoR\aaccount\"\x1e\n" + "\x1cGetValidatorAddressesRequest\"=\n" + "\x1dGetValidatorAddressesResponse\x12\x1c\n" + "\taddresses\x18\x01 \x03(\tR\taddresses\"/\n" + "\x13GetValidatorRequest\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\"5\n" + "\x1bGetValidatorByNumberRequest\x12\x16\n" + "\x06number\x18\x01 \x01(\x05R\x06number\"K\n" + "\x14GetValidatorResponse\x123\n" + "\tvalidator\x18\x01 \x01(\v2\x15.pactus.ValidatorInfoR\tvalidator\"/\n" + "\x13GetPublicKeyRequest\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\"5\n" + "\x14GetPublicKeyResponse\x12\x1d\n" + "\n" + "public_key\x18\x01 \x01(\tR\tpublicKey\"_\n" + "\x0fGetBlockRequest\x12\x16\n" + "\x06height\x18\x01 \x01(\rR\x06height\x124\n" + "\tverbosity\x18\x02 \x01(\x0e2\x16.pactus.BlockVerbosityR\tverbosity\"\x83\x02\n" + "\x10GetBlockResponse\x12\x16\n" + "\x06height\x18\x01 \x01(\rR\x06height\x12\x12\n" + "\x04hash\x18\x02 \x01(\tR\x04hash\x12\x12\n" + "\x04data\x18\x03 \x01(\tR\x04data\x12\x1d\n" + "\n" + "block_time\x18\x04 \x01(\rR\tblockTime\x12/\n" + "\x06header\x18\x05 \x01(\v2\x17.pactus.BlockHeaderInfoR\x06header\x124\n" + "\tprev_cert\x18\x06 \x01(\v2\x17.pactus.CertificateInfoR\bprevCert\x12)\n" + "\x03txs\x18\a \x03(\v2\x17.pactus.TransactionInfoR\x03txs\"-\n" + "\x13GetBlockHashRequest\x12\x16\n" + "\x06height\x18\x01 \x01(\rR\x06height\"*\n" + "\x14GetBlockHashResponse\x12\x12\n" + "\x04hash\x18\x01 \x01(\tR\x04hash\"+\n" + "\x15GetBlockHeightRequest\x12\x12\n" + "\x04hash\x18\x01 \x01(\tR\x04hash\"0\n" + "\x16GetBlockHeightResponse\x12\x16\n" + "\x06height\x18\x01 \x01(\rR\x06height\"\x1a\n" + "\x18GetBlockchainInfoRequest\"\x93\x04\n" + "\x19GetBlockchainInfoResponse\x12*\n" + "\x11last_block_height\x18\x01 \x01(\rR\x0flastBlockHeight\x12&\n" + "\x0flast_block_hash\x18\x02 \x01(\tR\rlastBlockHash\x12&\n" + "\x0flast_block_time\x18\n" + " \x01(\x03R\rlastBlockTime\x12%\n" + "\x0etotal_accounts\x18\x03 \x01(\x05R\rtotalAccounts\x12)\n" + "\x10total_validators\x18\x04 \x01(\x05R\x0ftotalValidators\x12+\n" + "\x11active_validators\x18\f \x01(\x05R\x10activeValidators\x12\x1f\n" + "\vtotal_power\x18\x05 \x01(\x03R\n" + "totalPower\x12'\n" + "\x0fcommittee_power\x18\x06 \x01(\x03R\x0ecommitteePower\x12\x1b\n" + "\tis_pruned\x18\b \x01(\bR\bisPruned\x12%\n" + "\x0epruning_height\x18\t \x01(\rR\rpruningHeight\x12!\n" + "\fin_committee\x18\r \x01(\bR\vinCommittee\x12%\n" + "\x0ecommittee_size\x18\x0e \x01(\x05R\rcommitteeSize\x12#\n" + "\raverage_score\x18\x0f \x01(\x01R\faverageScore\"\x19\n" + "\x17GetCommitteeInfoRequest\"\xec\x02\n" + "\x18GetCommitteeInfoResponse\x12%\n" + "\x0ecommittee_size\x18\x01 \x01(\x05R\rcommitteeSize\x12'\n" + "\x0fcommittee_power\x18\x02 \x01(\x03R\x0ecommitteePower\x12\x1f\n" + "\vtotal_power\x18\x03 \x01(\x03R\n" + "totalPower\x125\n" + "\n" + "validators\x18\x04 \x03(\v2\x15.pactus.ValidatorInfoR\n" + "validators\x12c\n" + "\x11protocol_versions\x18\x05 \x03(\v26.pactus.GetCommitteeInfoResponse.ProtocolVersionsEntryR\x10protocolVersions\x1aC\n" + "\x15ProtocolVersionsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\x01R\x05value:\x028\x01\"\x19\n" + "\x17GetConsensusInfoRequest\"\x81\x01\n" + "\x18GetConsensusInfoResponse\x120\n" + "\bproposal\x18\x01 \x01(\v2\x14.pactus.ProposalInfoR\bproposal\x123\n" + "\tinstances\x18\x02 \x03(\v2\x15.pactus.ConsensusInfoR\tinstances\"Q\n" + "\x17GetTxPoolContentRequest\x126\n" + "\fpayload_type\x18\x01 \x01(\x0e2\x13.pactus.PayloadTypeR\vpayloadType\"E\n" + "\x18GetTxPoolContentResponse\x12)\n" + "\x03txs\x18\x01 \x03(\v2\x17.pactus.TransactionInfoR\x03txs\"\xa1\x04\n" + "\rValidatorInfo\x12\x12\n" + "\x04hash\x18\x01 \x01(\tR\x04hash\x12\x12\n" + "\x04data\x18\x02 \x01(\tR\x04data\x12\x1d\n" + "\n" + "public_key\x18\x03 \x01(\tR\tpublicKey\x12\x16\n" + "\x06number\x18\x04 \x01(\x05R\x06number\x12\x14\n" + "\x05stake\x18\x05 \x01(\x03R\x05stake\x12.\n" + "\x13last_bonding_height\x18\x06 \x01(\rR\x11lastBondingHeight\x122\n" + "\x15last_sortition_height\x18\a \x01(\rR\x13lastSortitionHeight\x12)\n" + "\x10unbonding_height\x18\b \x01(\rR\x0funbondingHeight\x12\x18\n" + "\aaddress\x18\t \x01(\tR\aaddress\x12-\n" + "\x12availability_score\x18\n" + " \x01(\x01R\x11availabilityScore\x12)\n" + "\x10protocol_version\x18\v \x01(\x05R\x0fprotocolVersion\x12!\n" + "\fis_delegated\x18\f \x01(\bR\visDelegated\x12%\n" + "\x0edelegate_owner\x18\r \x01(\tR\rdelegateOwner\x12%\n" + "\x0edelegate_share\x18\x0e \x01(\x03R\rdelegateShare\x12'\n" + "\x0fdelegate_expiry\x18\x0f \x01(\rR\x0edelegateExpiry\"\x81\x01\n" + "\vAccountInfo\x12\x12\n" + "\x04hash\x18\x01 \x01(\tR\x04hash\x12\x12\n" + "\x04data\x18\x02 \x01(\tR\x04data\x12\x16\n" + "\x06number\x18\x03 \x01(\x05R\x06number\x12\x18\n" + "\abalance\x18\x04 \x01(\x03R\abalance\x12\x18\n" + "\aaddress\x18\x05 \x01(\tR\aaddress\"\xc4\x01\n" + "\x0fBlockHeaderInfo\x12\x18\n" + "\aversion\x18\x01 \x01(\x05R\aversion\x12&\n" + "\x0fprev_block_hash\x18\x02 \x01(\tR\rprevBlockHash\x12\x1d\n" + "\n" + "state_root\x18\x03 \x01(\tR\tstateRoot\x12%\n" + "\x0esortition_seed\x18\x04 \x01(\tR\rsortitionSeed\x12)\n" + "\x10proposer_address\x18\x05 \x01(\tR\x0fproposerAddress\"\x97\x01\n" + "\x0fCertificateInfo\x12\x12\n" + "\x04hash\x18\x01 \x01(\tR\x04hash\x12\x14\n" + "\x05round\x18\x02 \x01(\x05R\x05round\x12\x1e\n" + "\n" + "committers\x18\x03 \x03(\x05R\n" + "committers\x12\x1c\n" + "\tabsentees\x18\x04 \x03(\x05R\tabsentees\x12\x1c\n" + "\tsignature\x18\x05 \x01(\tR\tsignature\"\xb1\x01\n" + "\bVoteInfo\x12$\n" + "\x04type\x18\x01 \x01(\x0e2\x10.pactus.VoteTypeR\x04type\x12\x14\n" + "\x05voter\x18\x02 \x01(\tR\x05voter\x12\x1d\n" + "\n" + "block_hash\x18\x03 \x01(\tR\tblockHash\x12\x14\n" + "\x05round\x18\x04 \x01(\x05R\x05round\x12\x19\n" + "\bcp_round\x18\x05 \x01(\x05R\acpRound\x12\x19\n" + "\bcp_value\x18\x06 \x01(\x05R\acpValue\"\x97\x01\n" + "\rConsensusInfo\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\x12\x16\n" + "\x06active\x18\x02 \x01(\bR\x06active\x12\x16\n" + "\x06height\x18\x03 \x01(\rR\x06height\x12\x14\n" + "\x05round\x18\x04 \x01(\x05R\x05round\x12&\n" + "\x05votes\x18\x05 \x03(\v2\x10.pactus.VoteInfoR\x05votes\"y\n" + "\fProposalInfo\x12\x16\n" + "\x06height\x18\x01 \x01(\rR\x06height\x12\x14\n" + "\x05round\x18\x02 \x01(\x05R\x05round\x12\x1d\n" + "\n" + "block_data\x18\x03 \x01(\tR\tblockData\x12\x1c\n" + "\tsignature\x18\x04 \x01(\tR\tsignature*f\n" + "\x0eBlockVerbosity\x12\x18\n" + "\x14BLOCK_VERBOSITY_DATA\x10\x00\x12\x18\n" + "\x14BLOCK_VERBOSITY_INFO\x10\x01\x12 \n" + "\x1cBLOCK_VERBOSITY_TRANSACTIONS\x10\x02*\xa6\x01\n" + "\bVoteType\x12\x19\n" + "\x15VOTE_TYPE_UNSPECIFIED\x10\x00\x12\x15\n" + "\x11VOTE_TYPE_PREPARE\x10\x01\x12\x17\n" + "\x13VOTE_TYPE_PRECOMMIT\x10\x02\x12\x19\n" + "\x15VOTE_TYPE_CP_PRE_VOTE\x10\x03\x12\x1a\n" + "\x16VOTE_TYPE_CP_MAIN_VOTE\x10\x04\x12\x18\n" + "\x14VOTE_TYPE_CP_DECIDED\x10\x052\xe2\a\n" + "\n" + "Blockchain\x12=\n" + "\bGetBlock\x12\x17.pactus.GetBlockRequest\x1a\x18.pactus.GetBlockResponse\x12I\n" + "\fGetBlockHash\x12\x1b.pactus.GetBlockHashRequest\x1a\x1c.pactus.GetBlockHashResponse\x12O\n" + "\x0eGetBlockHeight\x12\x1d.pactus.GetBlockHeightRequest\x1a\x1e.pactus.GetBlockHeightResponse\x12X\n" + "\x11GetBlockchainInfo\x12 .pactus.GetBlockchainInfoRequest\x1a!.pactus.GetBlockchainInfoResponse\x12U\n" + "\x10GetCommitteeInfo\x12\x1f.pactus.GetCommitteeInfoRequest\x1a .pactus.GetCommitteeInfoResponse\x12U\n" + "\x10GetConsensusInfo\x12\x1f.pactus.GetConsensusInfoRequest\x1a .pactus.GetConsensusInfoResponse\x12C\n" + "\n" + "GetAccount\x12\x19.pactus.GetAccountRequest\x1a\x1a.pactus.GetAccountResponse\x12I\n" + "\fGetValidator\x12\x1b.pactus.GetValidatorRequest\x1a\x1c.pactus.GetValidatorResponse\x12Y\n" + "\x14GetValidatorByNumber\x12#.pactus.GetValidatorByNumberRequest\x1a\x1c.pactus.GetValidatorResponse\x12d\n" + "\x15GetValidatorAddresses\x12$.pactus.GetValidatorAddressesRequest\x1a%.pactus.GetValidatorAddressesResponse\x12I\n" + "\fGetPublicKey\x12\x1b.pactus.GetPublicKeyRequest\x1a\x1c.pactus.GetPublicKeyResponse\x12U\n" + "\x10GetTxPoolContent\x12\x1f.pactus.GetTxPoolContentRequest\x1a .pactus.GetTxPoolContentResponseB:\n" + "\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3" var ( file_blockchain_proto_rawDescOnce sync.Once file_blockchain_proto_rawDescData []byte ) func file_blockchain_proto_rawDescGZIP() []byte { file_blockchain_proto_rawDescOnce.Do(func() { file_blockchain_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_blockchain_proto_rawDesc), len(file_blockchain_proto_rawDesc))) }) return file_blockchain_proto_rawDescData } var file_blockchain_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_blockchain_proto_msgTypes = make([]protoimpl.MessageInfo, 31) var file_blockchain_proto_goTypes = []any{ (BlockVerbosity)(0), // 0: pactus.BlockVerbosity (VoteType)(0), // 1: pactus.VoteType (*GetAccountRequest)(nil), // 2: pactus.GetAccountRequest (*GetAccountResponse)(nil), // 3: pactus.GetAccountResponse (*GetValidatorAddressesRequest)(nil), // 4: pactus.GetValidatorAddressesRequest (*GetValidatorAddressesResponse)(nil), // 5: pactus.GetValidatorAddressesResponse (*GetValidatorRequest)(nil), // 6: pactus.GetValidatorRequest (*GetValidatorByNumberRequest)(nil), // 7: pactus.GetValidatorByNumberRequest (*GetValidatorResponse)(nil), // 8: pactus.GetValidatorResponse (*GetPublicKeyRequest)(nil), // 9: pactus.GetPublicKeyRequest (*GetPublicKeyResponse)(nil), // 10: pactus.GetPublicKeyResponse (*GetBlockRequest)(nil), // 11: pactus.GetBlockRequest (*GetBlockResponse)(nil), // 12: pactus.GetBlockResponse (*GetBlockHashRequest)(nil), // 13: pactus.GetBlockHashRequest (*GetBlockHashResponse)(nil), // 14: pactus.GetBlockHashResponse (*GetBlockHeightRequest)(nil), // 15: pactus.GetBlockHeightRequest (*GetBlockHeightResponse)(nil), // 16: pactus.GetBlockHeightResponse (*GetBlockchainInfoRequest)(nil), // 17: pactus.GetBlockchainInfoRequest (*GetBlockchainInfoResponse)(nil), // 18: pactus.GetBlockchainInfoResponse (*GetCommitteeInfoRequest)(nil), // 19: pactus.GetCommitteeInfoRequest (*GetCommitteeInfoResponse)(nil), // 20: pactus.GetCommitteeInfoResponse (*GetConsensusInfoRequest)(nil), // 21: pactus.GetConsensusInfoRequest (*GetConsensusInfoResponse)(nil), // 22: pactus.GetConsensusInfoResponse (*GetTxPoolContentRequest)(nil), // 23: pactus.GetTxPoolContentRequest (*GetTxPoolContentResponse)(nil), // 24: pactus.GetTxPoolContentResponse (*ValidatorInfo)(nil), // 25: pactus.ValidatorInfo (*AccountInfo)(nil), // 26: pactus.AccountInfo (*BlockHeaderInfo)(nil), // 27: pactus.BlockHeaderInfo (*CertificateInfo)(nil), // 28: pactus.CertificateInfo (*VoteInfo)(nil), // 29: pactus.VoteInfo (*ConsensusInfo)(nil), // 30: pactus.ConsensusInfo (*ProposalInfo)(nil), // 31: pactus.ProposalInfo nil, // 32: pactus.GetCommitteeInfoResponse.ProtocolVersionsEntry (*TransactionInfo)(nil), // 33: pactus.TransactionInfo (PayloadType)(0), // 34: pactus.PayloadType } var file_blockchain_proto_depIdxs = []int32{ 26, // 0: pactus.GetAccountResponse.account:type_name -> pactus.AccountInfo 25, // 1: pactus.GetValidatorResponse.validator:type_name -> pactus.ValidatorInfo 0, // 2: pactus.GetBlockRequest.verbosity:type_name -> pactus.BlockVerbosity 27, // 3: pactus.GetBlockResponse.header:type_name -> pactus.BlockHeaderInfo 28, // 4: pactus.GetBlockResponse.prev_cert:type_name -> pactus.CertificateInfo 33, // 5: pactus.GetBlockResponse.txs:type_name -> pactus.TransactionInfo 25, // 6: pactus.GetCommitteeInfoResponse.validators:type_name -> pactus.ValidatorInfo 32, // 7: pactus.GetCommitteeInfoResponse.protocol_versions:type_name -> pactus.GetCommitteeInfoResponse.ProtocolVersionsEntry 31, // 8: pactus.GetConsensusInfoResponse.proposal:type_name -> pactus.ProposalInfo 30, // 9: pactus.GetConsensusInfoResponse.instances:type_name -> pactus.ConsensusInfo 34, // 10: pactus.GetTxPoolContentRequest.payload_type:type_name -> pactus.PayloadType 33, // 11: pactus.GetTxPoolContentResponse.txs:type_name -> pactus.TransactionInfo 1, // 12: pactus.VoteInfo.type:type_name -> pactus.VoteType 29, // 13: pactus.ConsensusInfo.votes:type_name -> pactus.VoteInfo 11, // 14: pactus.Blockchain.GetBlock:input_type -> pactus.GetBlockRequest 13, // 15: pactus.Blockchain.GetBlockHash:input_type -> pactus.GetBlockHashRequest 15, // 16: pactus.Blockchain.GetBlockHeight:input_type -> pactus.GetBlockHeightRequest 17, // 17: pactus.Blockchain.GetBlockchainInfo:input_type -> pactus.GetBlockchainInfoRequest 19, // 18: pactus.Blockchain.GetCommitteeInfo:input_type -> pactus.GetCommitteeInfoRequest 21, // 19: pactus.Blockchain.GetConsensusInfo:input_type -> pactus.GetConsensusInfoRequest 2, // 20: pactus.Blockchain.GetAccount:input_type -> pactus.GetAccountRequest 6, // 21: pactus.Blockchain.GetValidator:input_type -> pactus.GetValidatorRequest 7, // 22: pactus.Blockchain.GetValidatorByNumber:input_type -> pactus.GetValidatorByNumberRequest 4, // 23: pactus.Blockchain.GetValidatorAddresses:input_type -> pactus.GetValidatorAddressesRequest 9, // 24: pactus.Blockchain.GetPublicKey:input_type -> pactus.GetPublicKeyRequest 23, // 25: pactus.Blockchain.GetTxPoolContent:input_type -> pactus.GetTxPoolContentRequest 12, // 26: pactus.Blockchain.GetBlock:output_type -> pactus.GetBlockResponse 14, // 27: pactus.Blockchain.GetBlockHash:output_type -> pactus.GetBlockHashResponse 16, // 28: pactus.Blockchain.GetBlockHeight:output_type -> pactus.GetBlockHeightResponse 18, // 29: pactus.Blockchain.GetBlockchainInfo:output_type -> pactus.GetBlockchainInfoResponse 20, // 30: pactus.Blockchain.GetCommitteeInfo:output_type -> pactus.GetCommitteeInfoResponse 22, // 31: pactus.Blockchain.GetConsensusInfo:output_type -> pactus.GetConsensusInfoResponse 3, // 32: pactus.Blockchain.GetAccount:output_type -> pactus.GetAccountResponse 8, // 33: pactus.Blockchain.GetValidator:output_type -> pactus.GetValidatorResponse 8, // 34: pactus.Blockchain.GetValidatorByNumber:output_type -> pactus.GetValidatorResponse 5, // 35: pactus.Blockchain.GetValidatorAddresses:output_type -> pactus.GetValidatorAddressesResponse 10, // 36: pactus.Blockchain.GetPublicKey:output_type -> pactus.GetPublicKeyResponse 24, // 37: pactus.Blockchain.GetTxPoolContent:output_type -> pactus.GetTxPoolContentResponse 26, // [26:38] is the sub-list for method output_type 14, // [14:26] is the sub-list for method input_type 14, // [14:14] is the sub-list for extension type_name 14, // [14:14] is the sub-list for extension extendee 0, // [0:14] is the sub-list for field type_name } func init() { file_blockchain_proto_init() } func file_blockchain_proto_init() { if File_blockchain_proto != nil { return } file_transaction_proto_init() type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_blockchain_proto_rawDesc), len(file_blockchain_proto_rawDesc)), NumEnums: 2, NumMessages: 31, NumExtensions: 0, NumServices: 1, }, GoTypes: file_blockchain_proto_goTypes, DependencyIndexes: file_blockchain_proto_depIdxs, EnumInfos: file_blockchain_proto_enumTypes, MessageInfos: file_blockchain_proto_msgTypes, }.Build() File_blockchain_proto = out.File file_blockchain_proto_goTypes = nil file_blockchain_proto_depIdxs = nil } ================================================ FILE: www/grpc/gen/go/blockchain.pb.gw.go ================================================ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: blockchain.proto /* Package pactus is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package pactus import ( "context" "errors" "io" "net/http" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors var ( _ codes.Code _ io.Reader _ status.Status _ = errors.New _ = runtime.String _ = utilities.NewDoubleArray _ = metadata.Join ) var filter_Blockchain_GetBlock_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetBlock_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetBlock_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetBlock(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetBlock_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetBlock_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetBlock(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetBlockHash_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetBlockHash_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockHashRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetBlockHash_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetBlockHash(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetBlockHash_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockHashRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetBlockHash_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetBlockHash(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetBlockHeight_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetBlockHeight_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockHeightRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetBlockHeight_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetBlockHeight(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetBlockHeight_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockHeightRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetBlockHeight_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetBlockHeight(ctx, &protoReq) return msg, metadata, err } func request_Blockchain_GetBlockchainInfo_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockchainInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetBlockchainInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetBlockchainInfo_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetBlockchainInfoRequest metadata runtime.ServerMetadata ) msg, err := server.GetBlockchainInfo(ctx, &protoReq) return msg, metadata, err } func request_Blockchain_GetCommitteeInfo_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetCommitteeInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetCommitteeInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetCommitteeInfo_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetCommitteeInfoRequest metadata runtime.ServerMetadata ) msg, err := server.GetCommitteeInfo(ctx, &protoReq) return msg, metadata, err } func request_Blockchain_GetConsensusInfo_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetConsensusInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetConsensusInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetConsensusInfo_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetConsensusInfoRequest metadata runtime.ServerMetadata ) msg, err := server.GetConsensusInfo(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetAccount_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetAccount_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetAccountRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetAccount_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetAccount(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetAccount_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetAccountRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetAccount_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetAccount(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetValidator_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetValidator_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetValidator_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetValidator(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetValidator_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetValidator_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetValidator(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetValidatorByNumber_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetValidatorByNumber_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorByNumberRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetValidatorByNumber_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetValidatorByNumber(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetValidatorByNumber_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorByNumberRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetValidatorByNumber_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetValidatorByNumber(ctx, &protoReq) return msg, metadata, err } func request_Blockchain_GetValidatorAddresses_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorAddressesRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetValidatorAddresses(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetValidatorAddresses_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorAddressesRequest metadata runtime.ServerMetadata ) msg, err := server.GetValidatorAddresses(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetPublicKey_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetPublicKey_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetPublicKeyRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetPublicKey_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetPublicKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetPublicKey_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetPublicKeyRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetPublicKey_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetPublicKey(ctx, &protoReq) return msg, metadata, err } var filter_Blockchain_GetTxPoolContent_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Blockchain_GetTxPoolContent_0(ctx context.Context, marshaler runtime.Marshaler, client BlockchainClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTxPoolContentRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetTxPoolContent_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetTxPoolContent(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Blockchain_GetTxPoolContent_0(ctx context.Context, marshaler runtime.Marshaler, server BlockchainServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTxPoolContentRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Blockchain_GetTxPoolContent_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetTxPoolContent(ctx, &protoReq) return msg, metadata, err } // RegisterBlockchainHandlerServer registers the http handlers for service Blockchain to "mux". // UnaryRPC :call BlockchainServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterBlockchainHandlerFromEndpoint instead. // GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterBlockchainHandlerServer(ctx context.Context, mux *runtime.ServeMux, server BlockchainServer) error { mux.Handle(http.MethodGet, pattern_Blockchain_GetBlock_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetBlock", runtime.WithHTTPPathPattern("/pactus/blockchain/get_block")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetBlock_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlock_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetBlockHash_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetBlockHash", runtime.WithHTTPPathPattern("/pactus/blockchain/get_block_hash")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetBlockHash_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlockHash_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetBlockHeight_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetBlockHeight", runtime.WithHTTPPathPattern("/pactus/blockchain/get_block_height")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetBlockHeight_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlockHeight_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetBlockchainInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetBlockchainInfo", runtime.WithHTTPPathPattern("/pactus/blockchain/get_blockchain_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetBlockchainInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlockchainInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetCommitteeInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetCommitteeInfo", runtime.WithHTTPPathPattern("/pactus/blockchain/get_committee_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetCommitteeInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetCommitteeInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetConsensusInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetConsensusInfo", runtime.WithHTTPPathPattern("/pactus/blockchain/get_consensus_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetConsensusInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetConsensusInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetAccount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetAccount", runtime.WithHTTPPathPattern("/pactus/blockchain/get_account")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetAccount_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetAccount_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetValidator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetValidator", runtime.WithHTTPPathPattern("/pactus/blockchain/get_validator")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetValidator_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetValidator_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetValidatorByNumber_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetValidatorByNumber", runtime.WithHTTPPathPattern("/pactus/blockchain/get_validator_by_number")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetValidatorByNumber_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetValidatorByNumber_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetValidatorAddresses_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetValidatorAddresses", runtime.WithHTTPPathPattern("/pactus/blockchain/get_validator_addresses")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetValidatorAddresses_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetValidatorAddresses_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetPublicKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetPublicKey", runtime.WithHTTPPathPattern("/pactus/blockchain/get_public_key")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetPublicKey_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetPublicKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetTxPoolContent_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Blockchain/GetTxPoolContent", runtime.WithHTTPPathPattern("/pactus/blockchain/get_txpool_content")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Blockchain_GetTxPoolContent_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetTxPoolContent_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterBlockchainHandlerFromEndpoint is same as RegisterBlockchainHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterBlockchainHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterBlockchainHandler(ctx, mux, conn) } // RegisterBlockchainHandler registers the http handlers for service Blockchain to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterBlockchainHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterBlockchainHandlerClient(ctx, mux, NewBlockchainClient(conn)) } // RegisterBlockchainHandlerClient registers the http handlers for service Blockchain // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "BlockchainClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "BlockchainClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "BlockchainClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterBlockchainHandlerClient(ctx context.Context, mux *runtime.ServeMux, client BlockchainClient) error { mux.Handle(http.MethodGet, pattern_Blockchain_GetBlock_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetBlock", runtime.WithHTTPPathPattern("/pactus/blockchain/get_block")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetBlock_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlock_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetBlockHash_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetBlockHash", runtime.WithHTTPPathPattern("/pactus/blockchain/get_block_hash")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetBlockHash_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlockHash_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetBlockHeight_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetBlockHeight", runtime.WithHTTPPathPattern("/pactus/blockchain/get_block_height")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetBlockHeight_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlockHeight_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetBlockchainInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetBlockchainInfo", runtime.WithHTTPPathPattern("/pactus/blockchain/get_blockchain_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetBlockchainInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetBlockchainInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetCommitteeInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetCommitteeInfo", runtime.WithHTTPPathPattern("/pactus/blockchain/get_committee_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetCommitteeInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetCommitteeInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetConsensusInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetConsensusInfo", runtime.WithHTTPPathPattern("/pactus/blockchain/get_consensus_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetConsensusInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetConsensusInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetAccount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetAccount", runtime.WithHTTPPathPattern("/pactus/blockchain/get_account")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetAccount_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetAccount_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetValidator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetValidator", runtime.WithHTTPPathPattern("/pactus/blockchain/get_validator")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetValidator_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetValidator_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetValidatorByNumber_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetValidatorByNumber", runtime.WithHTTPPathPattern("/pactus/blockchain/get_validator_by_number")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetValidatorByNumber_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetValidatorByNumber_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetValidatorAddresses_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetValidatorAddresses", runtime.WithHTTPPathPattern("/pactus/blockchain/get_validator_addresses")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetValidatorAddresses_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetValidatorAddresses_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetPublicKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetPublicKey", runtime.WithHTTPPathPattern("/pactus/blockchain/get_public_key")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetPublicKey_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetPublicKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Blockchain_GetTxPoolContent_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Blockchain/GetTxPoolContent", runtime.WithHTTPPathPattern("/pactus/blockchain/get_txpool_content")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Blockchain_GetTxPoolContent_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Blockchain_GetTxPoolContent_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_Blockchain_GetBlock_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_block"}, "")) pattern_Blockchain_GetBlockHash_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_block_hash"}, "")) pattern_Blockchain_GetBlockHeight_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_block_height"}, "")) pattern_Blockchain_GetBlockchainInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_blockchain_info"}, "")) pattern_Blockchain_GetCommitteeInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_committee_info"}, "")) pattern_Blockchain_GetConsensusInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_consensus_info"}, "")) pattern_Blockchain_GetAccount_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_account"}, "")) pattern_Blockchain_GetValidator_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_validator"}, "")) pattern_Blockchain_GetValidatorByNumber_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_validator_by_number"}, "")) pattern_Blockchain_GetValidatorAddresses_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_validator_addresses"}, "")) pattern_Blockchain_GetPublicKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_public_key"}, "")) pattern_Blockchain_GetTxPoolContent_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "blockchain", "get_txpool_content"}, "")) ) var ( forward_Blockchain_GetBlock_0 = runtime.ForwardResponseMessage forward_Blockchain_GetBlockHash_0 = runtime.ForwardResponseMessage forward_Blockchain_GetBlockHeight_0 = runtime.ForwardResponseMessage forward_Blockchain_GetBlockchainInfo_0 = runtime.ForwardResponseMessage forward_Blockchain_GetCommitteeInfo_0 = runtime.ForwardResponseMessage forward_Blockchain_GetConsensusInfo_0 = runtime.ForwardResponseMessage forward_Blockchain_GetAccount_0 = runtime.ForwardResponseMessage forward_Blockchain_GetValidator_0 = runtime.ForwardResponseMessage forward_Blockchain_GetValidatorByNumber_0 = runtime.ForwardResponseMessage forward_Blockchain_GetValidatorAddresses_0 = runtime.ForwardResponseMessage forward_Blockchain_GetPublicKey_0 = runtime.ForwardResponseMessage forward_Blockchain_GetTxPoolContent_0 = runtime.ForwardResponseMessage ) ================================================ FILE: www/grpc/gen/go/blockchain_grpc.pb.go ================================================ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.6.0 // - protoc (unknown) // source: blockchain.proto package pactus import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( Blockchain_GetBlock_FullMethodName = "/pactus.Blockchain/GetBlock" Blockchain_GetBlockHash_FullMethodName = "/pactus.Blockchain/GetBlockHash" Blockchain_GetBlockHeight_FullMethodName = "/pactus.Blockchain/GetBlockHeight" Blockchain_GetBlockchainInfo_FullMethodName = "/pactus.Blockchain/GetBlockchainInfo" Blockchain_GetCommitteeInfo_FullMethodName = "/pactus.Blockchain/GetCommitteeInfo" Blockchain_GetConsensusInfo_FullMethodName = "/pactus.Blockchain/GetConsensusInfo" Blockchain_GetAccount_FullMethodName = "/pactus.Blockchain/GetAccount" Blockchain_GetValidator_FullMethodName = "/pactus.Blockchain/GetValidator" Blockchain_GetValidatorByNumber_FullMethodName = "/pactus.Blockchain/GetValidatorByNumber" Blockchain_GetValidatorAddresses_FullMethodName = "/pactus.Blockchain/GetValidatorAddresses" Blockchain_GetPublicKey_FullMethodName = "/pactus.Blockchain/GetPublicKey" Blockchain_GetTxPoolContent_FullMethodName = "/pactus.Blockchain/GetTxPoolContent" ) // BlockchainClient is the client API for Blockchain service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. // // Blockchain service defines RPC methods for interacting with the blockchain. type BlockchainClient interface { // GetBlock retrieves information about a block based on the provided request parameters. GetBlock(ctx context.Context, in *GetBlockRequest, opts ...grpc.CallOption) (*GetBlockResponse, error) // GetBlockHash retrieves the hash of a block at the specified height. GetBlockHash(ctx context.Context, in *GetBlockHashRequest, opts ...grpc.CallOption) (*GetBlockHashResponse, error) // GetBlockHeight retrieves the height of a block with the specified hash. GetBlockHeight(ctx context.Context, in *GetBlockHeightRequest, opts ...grpc.CallOption) (*GetBlockHeightResponse, error) // GetBlockchainInfo retrieves general information about the blockchain. GetBlockchainInfo(ctx context.Context, in *GetBlockchainInfoRequest, opts ...grpc.CallOption) (*GetBlockchainInfoResponse, error) // GetCommitteeInfo retrieves information about the current committee. GetCommitteeInfo(ctx context.Context, in *GetCommitteeInfoRequest, opts ...grpc.CallOption) (*GetCommitteeInfoResponse, error) // GetConsensusInfo retrieves information about the consensus instances. GetConsensusInfo(ctx context.Context, in *GetConsensusInfoRequest, opts ...grpc.CallOption) (*GetConsensusInfoResponse, error) // GetAccount retrieves information about an account based on the provided address. GetAccount(ctx context.Context, in *GetAccountRequest, opts ...grpc.CallOption) (*GetAccountResponse, error) // GetValidator retrieves information about a validator based on the provided address. GetValidator(ctx context.Context, in *GetValidatorRequest, opts ...grpc.CallOption) (*GetValidatorResponse, error) // GetValidatorByNumber retrieves information about a validator based on the provided number. GetValidatorByNumber(ctx context.Context, in *GetValidatorByNumberRequest, opts ...grpc.CallOption) (*GetValidatorResponse, error) // GetValidatorAddresses retrieves a list of all validator addresses. GetValidatorAddresses(ctx context.Context, in *GetValidatorAddressesRequest, opts ...grpc.CallOption) (*GetValidatorAddressesResponse, error) // GetPublicKey retrieves the public key of an account based on the provided address. GetPublicKey(ctx context.Context, in *GetPublicKeyRequest, opts ...grpc.CallOption) (*GetPublicKeyResponse, error) // GetTxPoolContent retrieves current transactions in the transaction pool. GetTxPoolContent(ctx context.Context, in *GetTxPoolContentRequest, opts ...grpc.CallOption) (*GetTxPoolContentResponse, error) } type blockchainClient struct { cc grpc.ClientConnInterface } func NewBlockchainClient(cc grpc.ClientConnInterface) BlockchainClient { return &blockchainClient{cc} } func (c *blockchainClient) GetBlock(ctx context.Context, in *GetBlockRequest, opts ...grpc.CallOption) (*GetBlockResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetBlockResponse) err := c.cc.Invoke(ctx, Blockchain_GetBlock_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetBlockHash(ctx context.Context, in *GetBlockHashRequest, opts ...grpc.CallOption) (*GetBlockHashResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetBlockHashResponse) err := c.cc.Invoke(ctx, Blockchain_GetBlockHash_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetBlockHeight(ctx context.Context, in *GetBlockHeightRequest, opts ...grpc.CallOption) (*GetBlockHeightResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetBlockHeightResponse) err := c.cc.Invoke(ctx, Blockchain_GetBlockHeight_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetBlockchainInfo(ctx context.Context, in *GetBlockchainInfoRequest, opts ...grpc.CallOption) (*GetBlockchainInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetBlockchainInfoResponse) err := c.cc.Invoke(ctx, Blockchain_GetBlockchainInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetCommitteeInfo(ctx context.Context, in *GetCommitteeInfoRequest, opts ...grpc.CallOption) (*GetCommitteeInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetCommitteeInfoResponse) err := c.cc.Invoke(ctx, Blockchain_GetCommitteeInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetConsensusInfo(ctx context.Context, in *GetConsensusInfoRequest, opts ...grpc.CallOption) (*GetConsensusInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetConsensusInfoResponse) err := c.cc.Invoke(ctx, Blockchain_GetConsensusInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetAccount(ctx context.Context, in *GetAccountRequest, opts ...grpc.CallOption) (*GetAccountResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetAccountResponse) err := c.cc.Invoke(ctx, Blockchain_GetAccount_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetValidator(ctx context.Context, in *GetValidatorRequest, opts ...grpc.CallOption) (*GetValidatorResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetValidatorResponse) err := c.cc.Invoke(ctx, Blockchain_GetValidator_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetValidatorByNumber(ctx context.Context, in *GetValidatorByNumberRequest, opts ...grpc.CallOption) (*GetValidatorResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetValidatorResponse) err := c.cc.Invoke(ctx, Blockchain_GetValidatorByNumber_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetValidatorAddresses(ctx context.Context, in *GetValidatorAddressesRequest, opts ...grpc.CallOption) (*GetValidatorAddressesResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetValidatorAddressesResponse) err := c.cc.Invoke(ctx, Blockchain_GetValidatorAddresses_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetPublicKey(ctx context.Context, in *GetPublicKeyRequest, opts ...grpc.CallOption) (*GetPublicKeyResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetPublicKeyResponse) err := c.cc.Invoke(ctx, Blockchain_GetPublicKey_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *blockchainClient) GetTxPoolContent(ctx context.Context, in *GetTxPoolContentRequest, opts ...grpc.CallOption) (*GetTxPoolContentResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetTxPoolContentResponse) err := c.cc.Invoke(ctx, Blockchain_GetTxPoolContent_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // BlockchainServer is the server API for Blockchain service. // All implementations should embed UnimplementedBlockchainServer // for forward compatibility. // // Blockchain service defines RPC methods for interacting with the blockchain. type BlockchainServer interface { // GetBlock retrieves information about a block based on the provided request parameters. GetBlock(context.Context, *GetBlockRequest) (*GetBlockResponse, error) // GetBlockHash retrieves the hash of a block at the specified height. GetBlockHash(context.Context, *GetBlockHashRequest) (*GetBlockHashResponse, error) // GetBlockHeight retrieves the height of a block with the specified hash. GetBlockHeight(context.Context, *GetBlockHeightRequest) (*GetBlockHeightResponse, error) // GetBlockchainInfo retrieves general information about the blockchain. GetBlockchainInfo(context.Context, *GetBlockchainInfoRequest) (*GetBlockchainInfoResponse, error) // GetCommitteeInfo retrieves information about the current committee. GetCommitteeInfo(context.Context, *GetCommitteeInfoRequest) (*GetCommitteeInfoResponse, error) // GetConsensusInfo retrieves information about the consensus instances. GetConsensusInfo(context.Context, *GetConsensusInfoRequest) (*GetConsensusInfoResponse, error) // GetAccount retrieves information about an account based on the provided address. GetAccount(context.Context, *GetAccountRequest) (*GetAccountResponse, error) // GetValidator retrieves information about a validator based on the provided address. GetValidator(context.Context, *GetValidatorRequest) (*GetValidatorResponse, error) // GetValidatorByNumber retrieves information about a validator based on the provided number. GetValidatorByNumber(context.Context, *GetValidatorByNumberRequest) (*GetValidatorResponse, error) // GetValidatorAddresses retrieves a list of all validator addresses. GetValidatorAddresses(context.Context, *GetValidatorAddressesRequest) (*GetValidatorAddressesResponse, error) // GetPublicKey retrieves the public key of an account based on the provided address. GetPublicKey(context.Context, *GetPublicKeyRequest) (*GetPublicKeyResponse, error) // GetTxPoolContent retrieves current transactions in the transaction pool. GetTxPoolContent(context.Context, *GetTxPoolContentRequest) (*GetTxPoolContentResponse, error) } // UnimplementedBlockchainServer should be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedBlockchainServer struct{} func (UnimplementedBlockchainServer) GetBlock(context.Context, *GetBlockRequest) (*GetBlockResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetBlock not implemented") } func (UnimplementedBlockchainServer) GetBlockHash(context.Context, *GetBlockHashRequest) (*GetBlockHashResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetBlockHash not implemented") } func (UnimplementedBlockchainServer) GetBlockHeight(context.Context, *GetBlockHeightRequest) (*GetBlockHeightResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetBlockHeight not implemented") } func (UnimplementedBlockchainServer) GetBlockchainInfo(context.Context, *GetBlockchainInfoRequest) (*GetBlockchainInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetBlockchainInfo not implemented") } func (UnimplementedBlockchainServer) GetCommitteeInfo(context.Context, *GetCommitteeInfoRequest) (*GetCommitteeInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetCommitteeInfo not implemented") } func (UnimplementedBlockchainServer) GetConsensusInfo(context.Context, *GetConsensusInfoRequest) (*GetConsensusInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetConsensusInfo not implemented") } func (UnimplementedBlockchainServer) GetAccount(context.Context, *GetAccountRequest) (*GetAccountResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetAccount not implemented") } func (UnimplementedBlockchainServer) GetValidator(context.Context, *GetValidatorRequest) (*GetValidatorResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetValidator not implemented") } func (UnimplementedBlockchainServer) GetValidatorByNumber(context.Context, *GetValidatorByNumberRequest) (*GetValidatorResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetValidatorByNumber not implemented") } func (UnimplementedBlockchainServer) GetValidatorAddresses(context.Context, *GetValidatorAddressesRequest) (*GetValidatorAddressesResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetValidatorAddresses not implemented") } func (UnimplementedBlockchainServer) GetPublicKey(context.Context, *GetPublicKeyRequest) (*GetPublicKeyResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetPublicKey not implemented") } func (UnimplementedBlockchainServer) GetTxPoolContent(context.Context, *GetTxPoolContentRequest) (*GetTxPoolContentResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetTxPoolContent not implemented") } func (UnimplementedBlockchainServer) testEmbeddedByValue() {} // UnsafeBlockchainServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to BlockchainServer will // result in compilation errors. type UnsafeBlockchainServer interface { mustEmbedUnimplementedBlockchainServer() } func RegisterBlockchainServer(s grpc.ServiceRegistrar, srv BlockchainServer) { // If the following call panics, it indicates UnimplementedBlockchainServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&Blockchain_ServiceDesc, srv) } func _Blockchain_GetBlock_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetBlockRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetBlock(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetBlock_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetBlock(ctx, req.(*GetBlockRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetBlockHash_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetBlockHashRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetBlockHash(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetBlockHash_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetBlockHash(ctx, req.(*GetBlockHashRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetBlockHeight_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetBlockHeightRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetBlockHeight(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetBlockHeight_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetBlockHeight(ctx, req.(*GetBlockHeightRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetBlockchainInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetBlockchainInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetBlockchainInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetBlockchainInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetBlockchainInfo(ctx, req.(*GetBlockchainInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetCommitteeInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetCommitteeInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetCommitteeInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetCommitteeInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetCommitteeInfo(ctx, req.(*GetCommitteeInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetConsensusInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetConsensusInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetConsensusInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetConsensusInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetConsensusInfo(ctx, req.(*GetConsensusInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetAccountRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetAccount(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetAccount_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetAccount(ctx, req.(*GetAccountRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetValidator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetValidatorRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetValidator(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetValidator_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetValidator(ctx, req.(*GetValidatorRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetValidatorByNumber_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetValidatorByNumberRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetValidatorByNumber(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetValidatorByNumber_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetValidatorByNumber(ctx, req.(*GetValidatorByNumberRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetValidatorAddresses_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetValidatorAddressesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetValidatorAddresses(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetValidatorAddresses_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetValidatorAddresses(ctx, req.(*GetValidatorAddressesRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetPublicKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetPublicKeyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetPublicKey(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetPublicKey_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetPublicKey(ctx, req.(*GetPublicKeyRequest)) } return interceptor(ctx, in, info, handler) } func _Blockchain_GetTxPoolContent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetTxPoolContentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BlockchainServer).GetTxPoolContent(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Blockchain_GetTxPoolContent_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BlockchainServer).GetTxPoolContent(ctx, req.(*GetTxPoolContentRequest)) } return interceptor(ctx, in, info, handler) } // Blockchain_ServiceDesc is the grpc.ServiceDesc for Blockchain service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var Blockchain_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Blockchain", HandlerType: (*BlockchainServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetBlock", Handler: _Blockchain_GetBlock_Handler, }, { MethodName: "GetBlockHash", Handler: _Blockchain_GetBlockHash_Handler, }, { MethodName: "GetBlockHeight", Handler: _Blockchain_GetBlockHeight_Handler, }, { MethodName: "GetBlockchainInfo", Handler: _Blockchain_GetBlockchainInfo_Handler, }, { MethodName: "GetCommitteeInfo", Handler: _Blockchain_GetCommitteeInfo_Handler, }, { MethodName: "GetConsensusInfo", Handler: _Blockchain_GetConsensusInfo_Handler, }, { MethodName: "GetAccount", Handler: _Blockchain_GetAccount_Handler, }, { MethodName: "GetValidator", Handler: _Blockchain_GetValidator_Handler, }, { MethodName: "GetValidatorByNumber", Handler: _Blockchain_GetValidatorByNumber_Handler, }, { MethodName: "GetValidatorAddresses", Handler: _Blockchain_GetValidatorAddresses_Handler, }, { MethodName: "GetPublicKey", Handler: _Blockchain_GetPublicKey_Handler, }, { MethodName: "GetTxPoolContent", Handler: _Blockchain_GetTxPoolContent_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "blockchain.proto", } ================================================ FILE: www/grpc/gen/go/blockchain_jgw.pb.go ================================================ // Code generated by protoc-gen-jrpc-gateway. DO NOT EDIT. // source: blockchain.proto /* Package pactus is a reverse proxy. It translates gRPC into JSON-RPC 2.0 */ package pactus import ( "context" "encoding/json" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" ) type BlockchainJsonRPC struct { client BlockchainClient } type paramsAndHeadersBlockchain struct { Headers metadata.MD `json:"headers,omitempty"` Params json.RawMessage `json:"params"` } // RegisterBlockchainJsonRPC register the grpc client Blockchain for json-rpc. // The handlers forward requests to the grpc endpoint over "conn". func RegisterBlockchainJsonRPC(conn *grpc.ClientConn) *BlockchainJsonRPC { return &BlockchainJsonRPC{ client: NewBlockchainClient(conn), } } func (s *BlockchainJsonRPC) Methods() map[string]func(ctx context.Context, message json.RawMessage) (any, error) { return map[string]func(ctx context.Context, params json.RawMessage) (any, error){ "pactus.blockchain.get_block": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetBlockRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetBlock(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_block_hash": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetBlockHashRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetBlockHash(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_block_height": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetBlockHeightRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetBlockHeight(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_blockchain_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetBlockchainInfoRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetBlockchainInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_committee_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetCommitteeInfoRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetCommitteeInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_consensus_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetConsensusInfoRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetConsensusInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_account": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetAccountRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetAccount(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_validator": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetValidatorRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetValidator(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_validator_by_number": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetValidatorByNumberRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetValidatorByNumber(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_validator_addresses": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetValidatorAddressesRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetValidatorAddresses(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_public_key": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetPublicKeyRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetPublicKey(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.blockchain.get_tx_pool_content": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetTxPoolContentRequest) var jrpcData paramsAndHeadersBlockchain if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetTxPoolContent(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, } } ================================================ FILE: www/grpc/gen/go/network.cobra.pb.go ================================================ // Code generated by protoc-gen-cobra. DO NOT EDIT. package pactus import ( client "github.com/NathanBaulch/protoc-gen-cobra/client" flag "github.com/NathanBaulch/protoc-gen-cobra/flag" iocodec "github.com/NathanBaulch/protoc-gen-cobra/iocodec" cobra "github.com/spf13/cobra" grpc "google.golang.org/grpc" proto "google.golang.org/protobuf/proto" ) func NetworkClientCommand(options ...client.Option) *cobra.Command { cfg := client.NewConfig(options...) cmd := &cobra.Command{ Use: cfg.CommandNamer("Network"), Short: "Network service client", Long: "Network service provides RPCs for retrieving information about the network.", } cfg.BindFlags(cmd.PersistentFlags()) cmd.AddCommand( _NetworkGetNetworkInfoCommand(cfg), _NetworkListPeersCommand(cfg), _NetworkGetNodeInfoCommand(cfg), _NetworkPingCommand(cfg), ) return cmd } func _NetworkGetNetworkInfoCommand(cfg *client.Config) *cobra.Command { req := &GetNetworkInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetNetworkInfo"), Short: "GetNetworkInfo RPC client", Long: "GetNetworkInfo retrieves information about the overall network.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network", "GetNetworkInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewNetworkClient(cc) v := &GetNetworkInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetNetworkInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _NetworkListPeersCommand(cfg *client.Config) *cobra.Command { req := &ListPeersRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("ListPeers"), Short: "ListPeers RPC client", Long: "ListPeers lists all peers in the network.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network", "ListPeers"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewNetworkClient(cc) v := &ListPeersRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.ListPeers(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().BoolVar(&req.IncludeDisconnected, cfg.FlagNamer("IncludeDisconnected"), false, "If true, includes disconnected peers (default: connected peers only).") return cmd } func _NetworkGetNodeInfoCommand(cfg *client.Config) *cobra.Command { req := &GetNodeInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetNodeInfo"), Short: "GetNodeInfo RPC client", Long: "GetNodeInfo retrieves information about a specific node in the network.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network", "GetNodeInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewNetworkClient(cc) v := &GetNodeInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetNodeInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _NetworkPingCommand(cfg *client.Config) *cobra.Command { req := &PingRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("Ping"), Short: "Ping RPC client", Long: "Ping provides a simple connectivity test and latency measurement.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Network", "Ping"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewNetworkClient(cc) v := &PingRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.Ping(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } ================================================ FILE: www/grpc/gen/go/network.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: network.proto package pactus import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Direction represents the connection direction between peers. type Direction int32 const ( // Unknown direction (default value). Direction_DIRECTION_UNKNOWN Direction = 0 // Inbound connection - peer connected to us. Direction_DIRECTION_INBOUND Direction = 1 // Outbound connection - we connected to peer. Direction_DIRECTION_OUTBOUND Direction = 2 ) // Enum value maps for Direction. var ( Direction_name = map[int32]string{ 0: "DIRECTION_UNKNOWN", 1: "DIRECTION_INBOUND", 2: "DIRECTION_OUTBOUND", } Direction_value = map[string]int32{ "DIRECTION_UNKNOWN": 0, "DIRECTION_INBOUND": 1, "DIRECTION_OUTBOUND": 2, } ) func (x Direction) Enum() *Direction { p := new(Direction) *p = x return p } func (x Direction) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Direction) Descriptor() protoreflect.EnumDescriptor { return file_network_proto_enumTypes[0].Descriptor() } func (Direction) Type() protoreflect.EnumType { return &file_network_proto_enumTypes[0] } func (x Direction) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Direction.Descriptor instead. func (Direction) EnumDescriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{0} } // Request message for retrieving overall network information. type GetNetworkInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetNetworkInfoRequest) Reset() { *x = GetNetworkInfoRequest{} mi := &file_network_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetNetworkInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetNetworkInfoRequest) ProtoMessage() {} func (x *GetNetworkInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetNetworkInfoRequest.ProtoReflect.Descriptor instead. func (*GetNetworkInfoRequest) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{0} } // Response message contains information about the overall network. type GetNetworkInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Name of the P2P network. NetworkName string `protobuf:"bytes,1,opt,name=network_name,json=networkName,proto3" json:"network_name,omitempty"` // Number of connected peers. ConnectedPeersCount uint32 `protobuf:"varint,2,opt,name=connected_peers_count,json=connectedPeersCount,proto3" json:"connected_peers_count,omitempty"` // Metrics related to node activity. MetricInfo *MetricInfo `protobuf:"bytes,4,opt,name=metric_info,json=metricInfo,proto3" json:"metric_info,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetNetworkInfoResponse) Reset() { *x = GetNetworkInfoResponse{} mi := &file_network_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetNetworkInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetNetworkInfoResponse) ProtoMessage() {} func (x *GetNetworkInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetNetworkInfoResponse.ProtoReflect.Descriptor instead. func (*GetNetworkInfoResponse) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{1} } func (x *GetNetworkInfoResponse) GetNetworkName() string { if x != nil { return x.NetworkName } return "" } func (x *GetNetworkInfoResponse) GetConnectedPeersCount() uint32 { if x != nil { return x.ConnectedPeersCount } return 0 } func (x *GetNetworkInfoResponse) GetMetricInfo() *MetricInfo { if x != nil { return x.MetricInfo } return nil } // Request message for listing peers. type ListPeersRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // If true, includes disconnected peers (default: connected peers only). IncludeDisconnected bool `protobuf:"varint,1,opt,name=include_disconnected,json=includeDisconnected,proto3" json:"include_disconnected,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListPeersRequest) Reset() { *x = ListPeersRequest{} mi := &file_network_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListPeersRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListPeersRequest) ProtoMessage() {} func (x *ListPeersRequest) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListPeersRequest.ProtoReflect.Descriptor instead. func (*ListPeersRequest) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{2} } func (x *ListPeersRequest) GetIncludeDisconnected() bool { if x != nil { return x.IncludeDisconnected } return false } // Response message for listing peers. type ListPeersResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // List of peers. Peers []*PeerInfo `protobuf:"bytes,1,rep,name=peers,proto3" json:"peers,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListPeersResponse) Reset() { *x = ListPeersResponse{} mi := &file_network_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListPeersResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListPeersResponse) ProtoMessage() {} func (x *ListPeersResponse) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListPeersResponse.ProtoReflect.Descriptor instead. func (*ListPeersResponse) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{3} } func (x *ListPeersResponse) GetPeers() []*PeerInfo { if x != nil { return x.Peers } return nil } // Request message for retrieving information of the node. type GetNodeInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetNodeInfoRequest) Reset() { *x = GetNodeInfoRequest{} mi := &file_network_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetNodeInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetNodeInfoRequest) ProtoMessage() {} func (x *GetNodeInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetNodeInfoRequest.ProtoReflect.Descriptor instead. func (*GetNodeInfoRequest) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{4} } // Response message contains information about a specific node in the network. type GetNodeInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Moniker or Human-readable name identifying this node in the network. Moniker string `protobuf:"bytes,1,opt,name=moniker,proto3" json:"moniker,omitempty"` // Version and agent details of the node. Agent string `protobuf:"bytes,2,opt,name=agent,proto3" json:"agent,omitempty"` // Peer ID of the node. PeerId string `protobuf:"bytes,3,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` // Unix timestamp when the node was started (UTC). StartedAt uint64 `protobuf:"varint,4,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"` // Reachability status of the node. Reachability string `protobuf:"bytes,5,opt,name=reachability,proto3" json:"reachability,omitempty"` // Bitfield representing the services provided by the node. Services int32 `protobuf:"varint,6,opt,name=services,proto3" json:"services,omitempty"` // Names of services provided by the node. ServicesNames string `protobuf:"bytes,7,opt,name=services_names,json=servicesNames,proto3" json:"services_names,omitempty"` // List of addresses associated with the node. LocalAddrs []string `protobuf:"bytes,8,rep,name=local_addrs,json=localAddrs,proto3" json:"local_addrs,omitempty"` // List of protocols supported by the node. Protocols []string `protobuf:"bytes,9,rep,name=protocols,proto3" json:"protocols,omitempty"` // Offset between the node's clock and the network's clock (in seconds). ClockOffset float64 `protobuf:"fixed64,13,opt,name=clock_offset,json=clockOffset,proto3" json:"clock_offset,omitempty"` // Information about the node's connections. ConnectionInfo *ConnectionInfo `protobuf:"bytes,14,opt,name=connection_info,json=connectionInfo,proto3" json:"connection_info,omitempty"` // List of active ZeroMQ publishers. ZmqPublishers []*ZMQPublisherInfo `protobuf:"bytes,15,rep,name=zmq_publishers,json=zmqPublishers,proto3" json:"zmq_publishers,omitempty"` // Current Unix timestamp of the node (UTC). CurrentTime uint64 `protobuf:"varint,16,opt,name=current_time,json=currentTime,proto3" json:"current_time,omitempty"` // Name of the P2P network. NetworkName string `protobuf:"bytes,17,opt,name=network_name,json=networkName,proto3" json:"network_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetNodeInfoResponse) Reset() { *x = GetNodeInfoResponse{} mi := &file_network_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetNodeInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetNodeInfoResponse) ProtoMessage() {} func (x *GetNodeInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetNodeInfoResponse.ProtoReflect.Descriptor instead. func (*GetNodeInfoResponse) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{5} } func (x *GetNodeInfoResponse) GetMoniker() string { if x != nil { return x.Moniker } return "" } func (x *GetNodeInfoResponse) GetAgent() string { if x != nil { return x.Agent } return "" } func (x *GetNodeInfoResponse) GetPeerId() string { if x != nil { return x.PeerId } return "" } func (x *GetNodeInfoResponse) GetStartedAt() uint64 { if x != nil { return x.StartedAt } return 0 } func (x *GetNodeInfoResponse) GetReachability() string { if x != nil { return x.Reachability } return "" } func (x *GetNodeInfoResponse) GetServices() int32 { if x != nil { return x.Services } return 0 } func (x *GetNodeInfoResponse) GetServicesNames() string { if x != nil { return x.ServicesNames } return "" } func (x *GetNodeInfoResponse) GetLocalAddrs() []string { if x != nil { return x.LocalAddrs } return nil } func (x *GetNodeInfoResponse) GetProtocols() []string { if x != nil { return x.Protocols } return nil } func (x *GetNodeInfoResponse) GetClockOffset() float64 { if x != nil { return x.ClockOffset } return 0 } func (x *GetNodeInfoResponse) GetConnectionInfo() *ConnectionInfo { if x != nil { return x.ConnectionInfo } return nil } func (x *GetNodeInfoResponse) GetZmqPublishers() []*ZMQPublisherInfo { if x != nil { return x.ZmqPublishers } return nil } func (x *GetNodeInfoResponse) GetCurrentTime() uint64 { if x != nil { return x.CurrentTime } return 0 } func (x *GetNodeInfoResponse) GetNetworkName() string { if x != nil { return x.NetworkName } return "" } // ZMQPublisherInfo contains information about a ZeroMQ publisher. type ZMQPublisherInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The topic associated with the publisher. Topic string `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"` // The address of the publisher. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` // The high-water mark (HWM) for the publisher, indicating the // maximum number of messages to queue before dropping older ones. Hwm int32 `protobuf:"varint,3,opt,name=hwm,proto3" json:"hwm,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ZMQPublisherInfo) Reset() { *x = ZMQPublisherInfo{} mi := &file_network_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ZMQPublisherInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*ZMQPublisherInfo) ProtoMessage() {} func (x *ZMQPublisherInfo) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ZMQPublisherInfo.ProtoReflect.Descriptor instead. func (*ZMQPublisherInfo) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{6} } func (x *ZMQPublisherInfo) GetTopic() string { if x != nil { return x.Topic } return "" } func (x *ZMQPublisherInfo) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ZMQPublisherInfo) GetHwm() int32 { if x != nil { return x.Hwm } return 0 } // PeerInfo contains information about a peer in the network. type PeerInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // Current status of the peer (e.g., connected, disconnected). Status int32 `protobuf:"varint,1,opt,name=status,proto3" json:"status,omitempty"` // Moniker or Human-Readable name of the peer. Moniker string `protobuf:"bytes,2,opt,name=moniker,proto3" json:"moniker,omitempty"` // Version and agent details of the peer. Agent string `protobuf:"bytes,3,opt,name=agent,proto3" json:"agent,omitempty"` // Peer ID of the peer in P2P network. PeerId string `protobuf:"bytes,4,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` // List of consensus keys used by the peer. ConsensusKeys []string `protobuf:"bytes,5,rep,name=consensus_keys,json=consensusKeys,proto3" json:"consensus_keys,omitempty"` // List of consensus addresses used by the peer. ConsensusAddresses []string `protobuf:"bytes,6,rep,name=consensus_addresses,json=consensusAddresses,proto3" json:"consensus_addresses,omitempty"` // Bitfield representing the services provided by the peer. Services uint32 `protobuf:"varint,7,opt,name=services,proto3" json:"services,omitempty"` // Hash of the last block the peer knows. LastBlockHash string `protobuf:"bytes,8,opt,name=last_block_hash,json=lastBlockHash,proto3" json:"last_block_hash,omitempty"` // Blockchain height of the peer. Height uint32 `protobuf:"varint,9,opt,name=height,proto3" json:"height,omitempty"` // Unix timestamp of the last bundle sent to the peer (UTC). LastSent int64 `protobuf:"varint,10,opt,name=last_sent,json=lastSent,proto3" json:"last_sent,omitempty"` // Unix timestamp of the last bundle received from the peer (UTC). LastReceived int64 `protobuf:"varint,11,opt,name=last_received,json=lastReceived,proto3" json:"last_received,omitempty"` // Network address of the peer. Address string `protobuf:"bytes,12,opt,name=address,proto3" json:"address,omitempty"` // Connection direction (e.g., inbound, outbound). Direction Direction `protobuf:"varint,13,opt,name=direction,proto3,enum=pactus.Direction" json:"direction,omitempty"` // List of protocols supported by the peer. Protocols []string `protobuf:"bytes,14,rep,name=protocols,proto3" json:"protocols,omitempty"` // Total download sessions with the peer. TotalSessions int32 `protobuf:"varint,15,opt,name=total_sessions,json=totalSessions,proto3" json:"total_sessions,omitempty"` // Completed download sessions with the peer. CompletedSessions int32 `protobuf:"varint,16,opt,name=completed_sessions,json=completedSessions,proto3" json:"completed_sessions,omitempty"` // Metrics related to peer activity. MetricInfo *MetricInfo `protobuf:"bytes,17,opt,name=metric_info,json=metricInfo,proto3" json:"metric_info,omitempty"` // Whether the hello message was sent from the outbound connection. OutboundHelloSent bool `protobuf:"varint,18,opt,name=outbound_hello_sent,json=outboundHelloSent,proto3" json:"outbound_hello_sent,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PeerInfo) Reset() { *x = PeerInfo{} mi := &file_network_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PeerInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*PeerInfo) ProtoMessage() {} func (x *PeerInfo) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PeerInfo.ProtoReflect.Descriptor instead. func (*PeerInfo) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{7} } func (x *PeerInfo) GetStatus() int32 { if x != nil { return x.Status } return 0 } func (x *PeerInfo) GetMoniker() string { if x != nil { return x.Moniker } return "" } func (x *PeerInfo) GetAgent() string { if x != nil { return x.Agent } return "" } func (x *PeerInfo) GetPeerId() string { if x != nil { return x.PeerId } return "" } func (x *PeerInfo) GetConsensusKeys() []string { if x != nil { return x.ConsensusKeys } return nil } func (x *PeerInfo) GetConsensusAddresses() []string { if x != nil { return x.ConsensusAddresses } return nil } func (x *PeerInfo) GetServices() uint32 { if x != nil { return x.Services } return 0 } func (x *PeerInfo) GetLastBlockHash() string { if x != nil { return x.LastBlockHash } return "" } func (x *PeerInfo) GetHeight() uint32 { if x != nil { return x.Height } return 0 } func (x *PeerInfo) GetLastSent() int64 { if x != nil { return x.LastSent } return 0 } func (x *PeerInfo) GetLastReceived() int64 { if x != nil { return x.LastReceived } return 0 } func (x *PeerInfo) GetAddress() string { if x != nil { return x.Address } return "" } func (x *PeerInfo) GetDirection() Direction { if x != nil { return x.Direction } return Direction_DIRECTION_UNKNOWN } func (x *PeerInfo) GetProtocols() []string { if x != nil { return x.Protocols } return nil } func (x *PeerInfo) GetTotalSessions() int32 { if x != nil { return x.TotalSessions } return 0 } func (x *PeerInfo) GetCompletedSessions() int32 { if x != nil { return x.CompletedSessions } return 0 } func (x *PeerInfo) GetMetricInfo() *MetricInfo { if x != nil { return x.MetricInfo } return nil } func (x *PeerInfo) GetOutboundHelloSent() bool { if x != nil { return x.OutboundHelloSent } return false } // ConnectionInfo contains information about the node's connections. type ConnectionInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // Total number of connections. Connections uint64 `protobuf:"varint,1,opt,name=connections,proto3" json:"connections,omitempty"` // Number of inbound connections. InboundConnections uint64 `protobuf:"varint,2,opt,name=inbound_connections,json=inboundConnections,proto3" json:"inbound_connections,omitempty"` // Number of outbound connections. OutboundConnections uint64 `protobuf:"varint,3,opt,name=outbound_connections,json=outboundConnections,proto3" json:"outbound_connections,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ConnectionInfo) Reset() { *x = ConnectionInfo{} mi := &file_network_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ConnectionInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConnectionInfo) ProtoMessage() {} func (x *ConnectionInfo) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConnectionInfo.ProtoReflect.Descriptor instead. func (*ConnectionInfo) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{8} } func (x *ConnectionInfo) GetConnections() uint64 { if x != nil { return x.Connections } return 0 } func (x *ConnectionInfo) GetInboundConnections() uint64 { if x != nil { return x.InboundConnections } return 0 } func (x *ConnectionInfo) GetOutboundConnections() uint64 { if x != nil { return x.OutboundConnections } return 0 } // MetricInfo contains metrics data regarding network activity. type MetricInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // Total number of invalid bundles. TotalInvalid *CounterInfo `protobuf:"bytes,1,opt,name=total_invalid,json=totalInvalid,proto3" json:"total_invalid,omitempty"` // Total number of bundles sent. TotalSent *CounterInfo `protobuf:"bytes,2,opt,name=total_sent,json=totalSent,proto3" json:"total_sent,omitempty"` // Total number of bundles received. TotalReceived *CounterInfo `protobuf:"bytes,3,opt,name=total_received,json=totalReceived,proto3" json:"total_received,omitempty"` // Number of sent bundles categorized by message type. MessageSent map[int32]*CounterInfo `protobuf:"bytes,4,rep,name=message_sent,json=messageSent,proto3" json:"message_sent,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // Number of received bundles categorized by message type. MessageReceived map[int32]*CounterInfo `protobuf:"bytes,5,rep,name=message_received,json=messageReceived,proto3" json:"message_received,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *MetricInfo) Reset() { *x = MetricInfo{} mi := &file_network_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *MetricInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*MetricInfo) ProtoMessage() {} func (x *MetricInfo) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MetricInfo.ProtoReflect.Descriptor instead. func (*MetricInfo) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{9} } func (x *MetricInfo) GetTotalInvalid() *CounterInfo { if x != nil { return x.TotalInvalid } return nil } func (x *MetricInfo) GetTotalSent() *CounterInfo { if x != nil { return x.TotalSent } return nil } func (x *MetricInfo) GetTotalReceived() *CounterInfo { if x != nil { return x.TotalReceived } return nil } func (x *MetricInfo) GetMessageSent() map[int32]*CounterInfo { if x != nil { return x.MessageSent } return nil } func (x *MetricInfo) GetMessageReceived() map[int32]*CounterInfo { if x != nil { return x.MessageReceived } return nil } // CounterInfo holds counter data regarding byte and bundle counts. type CounterInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // Total number of bytes. Bytes uint64 `protobuf:"varint,1,opt,name=bytes,proto3" json:"bytes,omitempty"` // Total number of bundles. Bundles uint64 `protobuf:"varint,2,opt,name=bundles,proto3" json:"bundles,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CounterInfo) Reset() { *x = CounterInfo{} mi := &file_network_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CounterInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*CounterInfo) ProtoMessage() {} func (x *CounterInfo) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CounterInfo.ProtoReflect.Descriptor instead. func (*CounterInfo) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{10} } func (x *CounterInfo) GetBytes() uint64 { if x != nil { return x.Bytes } return 0 } func (x *CounterInfo) GetBundles() uint64 { if x != nil { return x.Bundles } return 0 } // Request message for ping - intentionally empty for measuring round-trip time. type PingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PingRequest) Reset() { *x = PingRequest{} mi := &file_network_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PingRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PingRequest) ProtoMessage() {} func (x *PingRequest) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PingRequest.ProtoReflect.Descriptor instead. func (*PingRequest) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{11} } // Response message for ping - intentionally empty for measuring round-trip time. type PingResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PingResponse) Reset() { *x = PingResponse{} mi := &file_network_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PingResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*PingResponse) ProtoMessage() {} func (x *PingResponse) ProtoReflect() protoreflect.Message { mi := &file_network_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PingResponse.ProtoReflect.Descriptor instead. func (*PingResponse) Descriptor() ([]byte, []int) { return file_network_proto_rawDescGZIP(), []int{12} } var File_network_proto protoreflect.FileDescriptor const file_network_proto_rawDesc = "" + "\n" + "\rnetwork.proto\x12\x06pactus\"\x17\n" + "\x15GetNetworkInfoRequest\"\xa4\x01\n" + "\x16GetNetworkInfoResponse\x12!\n" + "\fnetwork_name\x18\x01 \x01(\tR\vnetworkName\x122\n" + "\x15connected_peers_count\x18\x02 \x01(\rR\x13connectedPeersCount\x123\n" + "\vmetric_info\x18\x04 \x01(\v2\x12.pactus.MetricInfoR\n" + "metricInfo\"E\n" + "\x10ListPeersRequest\x121\n" + "\x14include_disconnected\x18\x01 \x01(\bR\x13includeDisconnected\";\n" + "\x11ListPeersResponse\x12&\n" + "\x05peers\x18\x01 \x03(\v2\x10.pactus.PeerInfoR\x05peers\"\x14\n" + "\x12GetNodeInfoRequest\"\x8e\x04\n" + "\x13GetNodeInfoResponse\x12\x18\n" + "\amoniker\x18\x01 \x01(\tR\amoniker\x12\x14\n" + "\x05agent\x18\x02 \x01(\tR\x05agent\x12\x17\n" + "\apeer_id\x18\x03 \x01(\tR\x06peerId\x12\x1d\n" + "\n" + "started_at\x18\x04 \x01(\x04R\tstartedAt\x12\"\n" + "\freachability\x18\x05 \x01(\tR\freachability\x12\x1a\n" + "\bservices\x18\x06 \x01(\x05R\bservices\x12%\n" + "\x0eservices_names\x18\a \x01(\tR\rservicesNames\x12\x1f\n" + "\vlocal_addrs\x18\b \x03(\tR\n" + "localAddrs\x12\x1c\n" + "\tprotocols\x18\t \x03(\tR\tprotocols\x12!\n" + "\fclock_offset\x18\r \x01(\x01R\vclockOffset\x12?\n" + "\x0fconnection_info\x18\x0e \x01(\v2\x16.pactus.ConnectionInfoR\x0econnectionInfo\x12?\n" + "\x0ezmq_publishers\x18\x0f \x03(\v2\x18.pactus.ZMQPublisherInfoR\rzmqPublishers\x12!\n" + "\fcurrent_time\x18\x10 \x01(\x04R\vcurrentTime\x12!\n" + "\fnetwork_name\x18\x11 \x01(\tR\vnetworkName\"T\n" + "\x10ZMQPublisherInfo\x12\x14\n" + "\x05topic\x18\x01 \x01(\tR\x05topic\x12\x18\n" + "\aaddress\x18\x02 \x01(\tR\aaddress\x12\x10\n" + "\x03hwm\x18\x03 \x01(\x05R\x03hwm\"\x85\x05\n" + "\bPeerInfo\x12\x16\n" + "\x06status\x18\x01 \x01(\x05R\x06status\x12\x18\n" + "\amoniker\x18\x02 \x01(\tR\amoniker\x12\x14\n" + "\x05agent\x18\x03 \x01(\tR\x05agent\x12\x17\n" + "\apeer_id\x18\x04 \x01(\tR\x06peerId\x12%\n" + "\x0econsensus_keys\x18\x05 \x03(\tR\rconsensusKeys\x12/\n" + "\x13consensus_addresses\x18\x06 \x03(\tR\x12consensusAddresses\x12\x1a\n" + "\bservices\x18\a \x01(\rR\bservices\x12&\n" + "\x0flast_block_hash\x18\b \x01(\tR\rlastBlockHash\x12\x16\n" + "\x06height\x18\t \x01(\rR\x06height\x12\x1b\n" + "\tlast_sent\x18\n" + " \x01(\x03R\blastSent\x12#\n" + "\rlast_received\x18\v \x01(\x03R\flastReceived\x12\x18\n" + "\aaddress\x18\f \x01(\tR\aaddress\x12/\n" + "\tdirection\x18\r \x01(\x0e2\x11.pactus.DirectionR\tdirection\x12\x1c\n" + "\tprotocols\x18\x0e \x03(\tR\tprotocols\x12%\n" + "\x0etotal_sessions\x18\x0f \x01(\x05R\rtotalSessions\x12-\n" + "\x12completed_sessions\x18\x10 \x01(\x05R\x11completedSessions\x123\n" + "\vmetric_info\x18\x11 \x01(\v2\x12.pactus.MetricInfoR\n" + "metricInfo\x12.\n" + "\x13outbound_hello_sent\x18\x12 \x01(\bR\x11outboundHelloSent\"\x96\x01\n" + "\x0eConnectionInfo\x12 \n" + "\vconnections\x18\x01 \x01(\x04R\vconnections\x12/\n" + "\x13inbound_connections\x18\x02 \x01(\x04R\x12inboundConnections\x121\n" + "\x14outbound_connections\x18\x03 \x01(\x04R\x13outboundConnections\"\x80\x04\n" + "\n" + "MetricInfo\x128\n" + "\rtotal_invalid\x18\x01 \x01(\v2\x13.pactus.CounterInfoR\ftotalInvalid\x122\n" + "\n" + "total_sent\x18\x02 \x01(\v2\x13.pactus.CounterInfoR\ttotalSent\x12:\n" + "\x0etotal_received\x18\x03 \x01(\v2\x13.pactus.CounterInfoR\rtotalReceived\x12F\n" + "\fmessage_sent\x18\x04 \x03(\v2#.pactus.MetricInfo.MessageSentEntryR\vmessageSent\x12R\n" + "\x10message_received\x18\x05 \x03(\v2'.pactus.MetricInfo.MessageReceivedEntryR\x0fmessageReceived\x1aS\n" + "\x10MessageSentEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\x05R\x03key\x12)\n" + "\x05value\x18\x02 \x01(\v2\x13.pactus.CounterInfoR\x05value:\x028\x01\x1aW\n" + "\x14MessageReceivedEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\x05R\x03key\x12)\n" + "\x05value\x18\x02 \x01(\v2\x13.pactus.CounterInfoR\x05value:\x028\x01\"=\n" + "\vCounterInfo\x12\x14\n" + "\x05bytes\x18\x01 \x01(\x04R\x05bytes\x12\x18\n" + "\abundles\x18\x02 \x01(\x04R\abundles\"\r\n" + "\vPingRequest\"\x0e\n" + "\fPingResponse*Q\n" + "\tDirection\x12\x15\n" + "\x11DIRECTION_UNKNOWN\x10\x00\x12\x15\n" + "\x11DIRECTION_INBOUND\x10\x01\x12\x16\n" + "\x12DIRECTION_OUTBOUND\x10\x022\x97\x02\n" + "\aNetwork\x12O\n" + "\x0eGetNetworkInfo\x12\x1d.pactus.GetNetworkInfoRequest\x1a\x1e.pactus.GetNetworkInfoResponse\x12@\n" + "\tListPeers\x12\x18.pactus.ListPeersRequest\x1a\x19.pactus.ListPeersResponse\x12F\n" + "\vGetNodeInfo\x12\x1a.pactus.GetNodeInfoRequest\x1a\x1b.pactus.GetNodeInfoResponse\x121\n" + "\x04Ping\x12\x13.pactus.PingRequest\x1a\x14.pactus.PingResponseB:\n" + "\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3" var ( file_network_proto_rawDescOnce sync.Once file_network_proto_rawDescData []byte ) func file_network_proto_rawDescGZIP() []byte { file_network_proto_rawDescOnce.Do(func() { file_network_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_network_proto_rawDesc), len(file_network_proto_rawDesc))) }) return file_network_proto_rawDescData } var file_network_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_network_proto_msgTypes = make([]protoimpl.MessageInfo, 15) var file_network_proto_goTypes = []any{ (Direction)(0), // 0: pactus.Direction (*GetNetworkInfoRequest)(nil), // 1: pactus.GetNetworkInfoRequest (*GetNetworkInfoResponse)(nil), // 2: pactus.GetNetworkInfoResponse (*ListPeersRequest)(nil), // 3: pactus.ListPeersRequest (*ListPeersResponse)(nil), // 4: pactus.ListPeersResponse (*GetNodeInfoRequest)(nil), // 5: pactus.GetNodeInfoRequest (*GetNodeInfoResponse)(nil), // 6: pactus.GetNodeInfoResponse (*ZMQPublisherInfo)(nil), // 7: pactus.ZMQPublisherInfo (*PeerInfo)(nil), // 8: pactus.PeerInfo (*ConnectionInfo)(nil), // 9: pactus.ConnectionInfo (*MetricInfo)(nil), // 10: pactus.MetricInfo (*CounterInfo)(nil), // 11: pactus.CounterInfo (*PingRequest)(nil), // 12: pactus.PingRequest (*PingResponse)(nil), // 13: pactus.PingResponse nil, // 14: pactus.MetricInfo.MessageSentEntry nil, // 15: pactus.MetricInfo.MessageReceivedEntry } var file_network_proto_depIdxs = []int32{ 10, // 0: pactus.GetNetworkInfoResponse.metric_info:type_name -> pactus.MetricInfo 8, // 1: pactus.ListPeersResponse.peers:type_name -> pactus.PeerInfo 9, // 2: pactus.GetNodeInfoResponse.connection_info:type_name -> pactus.ConnectionInfo 7, // 3: pactus.GetNodeInfoResponse.zmq_publishers:type_name -> pactus.ZMQPublisherInfo 0, // 4: pactus.PeerInfo.direction:type_name -> pactus.Direction 10, // 5: pactus.PeerInfo.metric_info:type_name -> pactus.MetricInfo 11, // 6: pactus.MetricInfo.total_invalid:type_name -> pactus.CounterInfo 11, // 7: pactus.MetricInfo.total_sent:type_name -> pactus.CounterInfo 11, // 8: pactus.MetricInfo.total_received:type_name -> pactus.CounterInfo 14, // 9: pactus.MetricInfo.message_sent:type_name -> pactus.MetricInfo.MessageSentEntry 15, // 10: pactus.MetricInfo.message_received:type_name -> pactus.MetricInfo.MessageReceivedEntry 11, // 11: pactus.MetricInfo.MessageSentEntry.value:type_name -> pactus.CounterInfo 11, // 12: pactus.MetricInfo.MessageReceivedEntry.value:type_name -> pactus.CounterInfo 1, // 13: pactus.Network.GetNetworkInfo:input_type -> pactus.GetNetworkInfoRequest 3, // 14: pactus.Network.ListPeers:input_type -> pactus.ListPeersRequest 5, // 15: pactus.Network.GetNodeInfo:input_type -> pactus.GetNodeInfoRequest 12, // 16: pactus.Network.Ping:input_type -> pactus.PingRequest 2, // 17: pactus.Network.GetNetworkInfo:output_type -> pactus.GetNetworkInfoResponse 4, // 18: pactus.Network.ListPeers:output_type -> pactus.ListPeersResponse 6, // 19: pactus.Network.GetNodeInfo:output_type -> pactus.GetNodeInfoResponse 13, // 20: pactus.Network.Ping:output_type -> pactus.PingResponse 17, // [17:21] is the sub-list for method output_type 13, // [13:17] is the sub-list for method input_type 13, // [13:13] is the sub-list for extension type_name 13, // [13:13] is the sub-list for extension extendee 0, // [0:13] is the sub-list for field type_name } func init() { file_network_proto_init() } func file_network_proto_init() { if File_network_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_network_proto_rawDesc), len(file_network_proto_rawDesc)), NumEnums: 1, NumMessages: 15, NumExtensions: 0, NumServices: 1, }, GoTypes: file_network_proto_goTypes, DependencyIndexes: file_network_proto_depIdxs, EnumInfos: file_network_proto_enumTypes, MessageInfos: file_network_proto_msgTypes, }.Build() File_network_proto = out.File file_network_proto_goTypes = nil file_network_proto_depIdxs = nil } ================================================ FILE: www/grpc/gen/go/network.pb.gw.go ================================================ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: network.proto /* Package pactus is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package pactus import ( "context" "errors" "io" "net/http" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors var ( _ codes.Code _ io.Reader _ status.Status _ = errors.New _ = runtime.String _ = utilities.NewDoubleArray _ = metadata.Join ) func request_Network_GetNetworkInfo_0(ctx context.Context, marshaler runtime.Marshaler, client NetworkClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetNetworkInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetNetworkInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Network_GetNetworkInfo_0(ctx context.Context, marshaler runtime.Marshaler, server NetworkServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetNetworkInfoRequest metadata runtime.ServerMetadata ) msg, err := server.GetNetworkInfo(ctx, &protoReq) return msg, metadata, err } func request_Network_GetNodeInfo_0(ctx context.Context, marshaler runtime.Marshaler, client NetworkClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetNodeInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetNodeInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Network_GetNodeInfo_0(ctx context.Context, marshaler runtime.Marshaler, server NetworkServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetNodeInfoRequest metadata runtime.ServerMetadata ) msg, err := server.GetNodeInfo(ctx, &protoReq) return msg, metadata, err } func request_Network_Ping_0(ctx context.Context, marshaler runtime.Marshaler, client NetworkClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq PingRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.Ping(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Network_Ping_0(ctx context.Context, marshaler runtime.Marshaler, server NetworkServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq PingRequest metadata runtime.ServerMetadata ) msg, err := server.Ping(ctx, &protoReq) return msg, metadata, err } // RegisterNetworkHandlerServer registers the http handlers for service Network to "mux". // UnaryRPC :call NetworkServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterNetworkHandlerFromEndpoint instead. // GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterNetworkHandlerServer(ctx context.Context, mux *runtime.ServeMux, server NetworkServer) error { mux.Handle(http.MethodGet, pattern_Network_GetNetworkInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Network/GetNetworkInfo", runtime.WithHTTPPathPattern("/pactus/network/get_network_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Network_GetNetworkInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Network_GetNetworkInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Network_GetNodeInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Network/GetNodeInfo", runtime.WithHTTPPathPattern("/pactus/network/get_node_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Network_GetNodeInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Network_GetNodeInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Network_Ping_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Network/Ping", runtime.WithHTTPPathPattern("/pactus/network/ping")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Network_Ping_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Network_Ping_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterNetworkHandlerFromEndpoint is same as RegisterNetworkHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterNetworkHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterNetworkHandler(ctx, mux, conn) } // RegisterNetworkHandler registers the http handlers for service Network to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterNetworkHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterNetworkHandlerClient(ctx, mux, NewNetworkClient(conn)) } // RegisterNetworkHandlerClient registers the http handlers for service Network // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "NetworkClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "NetworkClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "NetworkClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterNetworkHandlerClient(ctx context.Context, mux *runtime.ServeMux, client NetworkClient) error { mux.Handle(http.MethodGet, pattern_Network_GetNetworkInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Network/GetNetworkInfo", runtime.WithHTTPPathPattern("/pactus/network/get_network_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Network_GetNetworkInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Network_GetNetworkInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Network_GetNodeInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Network/GetNodeInfo", runtime.WithHTTPPathPattern("/pactus/network/get_node_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Network_GetNodeInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Network_GetNodeInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Network_Ping_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Network/Ping", runtime.WithHTTPPathPattern("/pactus/network/ping")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Network_Ping_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Network_Ping_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_Network_GetNetworkInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "network", "get_network_info"}, "")) pattern_Network_GetNodeInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "network", "get_node_info"}, "")) pattern_Network_Ping_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "network", "ping"}, "")) ) var ( forward_Network_GetNetworkInfo_0 = runtime.ForwardResponseMessage forward_Network_GetNodeInfo_0 = runtime.ForwardResponseMessage forward_Network_Ping_0 = runtime.ForwardResponseMessage ) ================================================ FILE: www/grpc/gen/go/network_grpc.pb.go ================================================ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.6.0 // - protoc (unknown) // source: network.proto package pactus import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( Network_GetNetworkInfo_FullMethodName = "/pactus.Network/GetNetworkInfo" Network_ListPeers_FullMethodName = "/pactus.Network/ListPeers" Network_GetNodeInfo_FullMethodName = "/pactus.Network/GetNodeInfo" Network_Ping_FullMethodName = "/pactus.Network/Ping" ) // NetworkClient is the client API for Network service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. // // Network service provides RPCs for retrieving information about the network. type NetworkClient interface { // GetNetworkInfo retrieves information about the overall network. GetNetworkInfo(ctx context.Context, in *GetNetworkInfoRequest, opts ...grpc.CallOption) (*GetNetworkInfoResponse, error) // ListPeers lists all peers in the network. ListPeers(ctx context.Context, in *ListPeersRequest, opts ...grpc.CallOption) (*ListPeersResponse, error) // GetNodeInfo retrieves information about a specific node in the network. GetNodeInfo(ctx context.Context, in *GetNodeInfoRequest, opts ...grpc.CallOption) (*GetNodeInfoResponse, error) // Ping provides a simple connectivity test and latency measurement. Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) } type networkClient struct { cc grpc.ClientConnInterface } func NewNetworkClient(cc grpc.ClientConnInterface) NetworkClient { return &networkClient{cc} } func (c *networkClient) GetNetworkInfo(ctx context.Context, in *GetNetworkInfoRequest, opts ...grpc.CallOption) (*GetNetworkInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetNetworkInfoResponse) err := c.cc.Invoke(ctx, Network_GetNetworkInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *networkClient) ListPeers(ctx context.Context, in *ListPeersRequest, opts ...grpc.CallOption) (*ListPeersResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListPeersResponse) err := c.cc.Invoke(ctx, Network_ListPeers_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *networkClient) GetNodeInfo(ctx context.Context, in *GetNodeInfoRequest, opts ...grpc.CallOption) (*GetNodeInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetNodeInfoResponse) err := c.cc.Invoke(ctx, Network_GetNodeInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *networkClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(PingResponse) err := c.cc.Invoke(ctx, Network_Ping_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // NetworkServer is the server API for Network service. // All implementations should embed UnimplementedNetworkServer // for forward compatibility. // // Network service provides RPCs for retrieving information about the network. type NetworkServer interface { // GetNetworkInfo retrieves information about the overall network. GetNetworkInfo(context.Context, *GetNetworkInfoRequest) (*GetNetworkInfoResponse, error) // ListPeers lists all peers in the network. ListPeers(context.Context, *ListPeersRequest) (*ListPeersResponse, error) // GetNodeInfo retrieves information about a specific node in the network. GetNodeInfo(context.Context, *GetNodeInfoRequest) (*GetNodeInfoResponse, error) // Ping provides a simple connectivity test and latency measurement. Ping(context.Context, *PingRequest) (*PingResponse, error) } // UnimplementedNetworkServer should be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedNetworkServer struct{} func (UnimplementedNetworkServer) GetNetworkInfo(context.Context, *GetNetworkInfoRequest) (*GetNetworkInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetNetworkInfo not implemented") } func (UnimplementedNetworkServer) ListPeers(context.Context, *ListPeersRequest) (*ListPeersResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListPeers not implemented") } func (UnimplementedNetworkServer) GetNodeInfo(context.Context, *GetNodeInfoRequest) (*GetNodeInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetNodeInfo not implemented") } func (UnimplementedNetworkServer) Ping(context.Context, *PingRequest) (*PingResponse, error) { return nil, status.Error(codes.Unimplemented, "method Ping not implemented") } func (UnimplementedNetworkServer) testEmbeddedByValue() {} // UnsafeNetworkServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to NetworkServer will // result in compilation errors. type UnsafeNetworkServer interface { mustEmbedUnimplementedNetworkServer() } func RegisterNetworkServer(s grpc.ServiceRegistrar, srv NetworkServer) { // If the following call panics, it indicates UnimplementedNetworkServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&Network_ServiceDesc, srv) } func _Network_GetNetworkInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetNetworkInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NetworkServer).GetNetworkInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Network_GetNetworkInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NetworkServer).GetNetworkInfo(ctx, req.(*GetNetworkInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Network_ListPeers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListPeersRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NetworkServer).ListPeers(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Network_ListPeers_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NetworkServer).ListPeers(ctx, req.(*ListPeersRequest)) } return interceptor(ctx, in, info, handler) } func _Network_GetNodeInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetNodeInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NetworkServer).GetNodeInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Network_GetNodeInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NetworkServer).GetNodeInfo(ctx, req.(*GetNodeInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Network_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PingRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NetworkServer).Ping(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Network_Ping_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NetworkServer).Ping(ctx, req.(*PingRequest)) } return interceptor(ctx, in, info, handler) } // Network_ServiceDesc is the grpc.ServiceDesc for Network service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var Network_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Network", HandlerType: (*NetworkServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetNetworkInfo", Handler: _Network_GetNetworkInfo_Handler, }, { MethodName: "ListPeers", Handler: _Network_ListPeers_Handler, }, { MethodName: "GetNodeInfo", Handler: _Network_GetNodeInfo_Handler, }, { MethodName: "Ping", Handler: _Network_Ping_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "network.proto", } ================================================ FILE: www/grpc/gen/go/network_jgw.pb.go ================================================ // Code generated by protoc-gen-jrpc-gateway. DO NOT EDIT. // source: network.proto /* Package pactus is a reverse proxy. It translates gRPC into JSON-RPC 2.0 */ package pactus import ( "context" "encoding/json" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" ) type NetworkJsonRPC struct { client NetworkClient } type paramsAndHeadersNetwork struct { Headers metadata.MD `json:"headers,omitempty"` Params json.RawMessage `json:"params"` } // RegisterNetworkJsonRPC register the grpc client Network for json-rpc. // The handlers forward requests to the grpc endpoint over "conn". func RegisterNetworkJsonRPC(conn *grpc.ClientConn) *NetworkJsonRPC { return &NetworkJsonRPC{ client: NewNetworkClient(conn), } } func (s *NetworkJsonRPC) Methods() map[string]func(ctx context.Context, message json.RawMessage) (any, error) { return map[string]func(ctx context.Context, params json.RawMessage) (any, error){ "pactus.network.get_network_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetNetworkInfoRequest) var jrpcData paramsAndHeadersNetwork if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetNetworkInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.network.list_peers": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(ListPeersRequest) var jrpcData paramsAndHeadersNetwork if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.ListPeers(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.network.get_node_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetNodeInfoRequest) var jrpcData paramsAndHeadersNetwork if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetNodeInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.network.ping": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(PingRequest) var jrpcData paramsAndHeadersNetwork if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.Ping(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, } } ================================================ FILE: www/grpc/gen/go/transaction.cobra.pb.go ================================================ // Code generated by protoc-gen-cobra. DO NOT EDIT. package pactus import ( client "github.com/NathanBaulch/protoc-gen-cobra/client" flag "github.com/NathanBaulch/protoc-gen-cobra/flag" iocodec "github.com/NathanBaulch/protoc-gen-cobra/iocodec" cobra "github.com/spf13/cobra" grpc "google.golang.org/grpc" proto "google.golang.org/protobuf/proto" ) func TransactionClientCommand(options ...client.Option) *cobra.Command { cfg := client.NewConfig(options...) cmd := &cobra.Command{ Use: cfg.CommandNamer("Transaction"), Short: "Transaction service client", Long: "Transaction service defines various RPC methods for interacting with transactions.", } cfg.BindFlags(cmd.PersistentFlags()) cmd.AddCommand( _TransactionGetTransactionCommand(cfg), _TransactionCalculateFeeCommand(cfg), _TransactionBroadcastTransactionCommand(cfg), _TransactionGetRawTransferTransactionCommand(cfg), _TransactionGetRawBondTransactionCommand(cfg), _TransactionGetRawUnbondTransactionCommand(cfg), _TransactionGetRawWithdrawTransactionCommand(cfg), _TransactionGetRawBatchTransferTransactionCommand(cfg), _TransactionDecodeRawTransactionCommand(cfg), _TransactionCheckTransactionCommand(cfg), ) return cmd } func _TransactionGetTransactionCommand(cfg *client.Config) *cobra.Command { req := &GetTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetTransaction"), Short: "GetTransaction RPC client", Long: "GetTransaction retrieves transaction details based on the provided request parameters.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "GetTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &GetTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.Id, cfg.FlagNamer("Id"), "", "The unique ID of the transaction to retrieve.") flag.EnumVar(cmd.PersistentFlags(), &req.Verbosity, cfg.FlagNamer("Verbosity"), "The verbosity level for transaction details.") return cmd } func _TransactionCalculateFeeCommand(cfg *client.Config) *cobra.Command { req := &CalculateFeeRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("CalculateFee"), Short: "CalculateFee RPC client", Long: "CalculateFee calculates the transaction fee based on the specified amount and payload type.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "CalculateFee"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &CalculateFeeRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.CalculateFee(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Int64Var(&req.Amount, cfg.FlagNamer("Amount"), 0, "The amount involved in the transaction, specified in NanoPAC.") flag.EnumVar(cmd.PersistentFlags(), &req.PayloadType, cfg.FlagNamer("PayloadType"), "The type of transaction payload.") cmd.PersistentFlags().BoolVar(&req.FixedAmount, cfg.FlagNamer("FixedAmount"), false, "Indicates if the amount should be fixed and include the fee.") return cmd } func _TransactionBroadcastTransactionCommand(cfg *client.Config) *cobra.Command { req := &BroadcastTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("BroadcastTransaction"), Short: "BroadcastTransaction RPC client", Long: "BroadcastTransaction broadcasts a signed transaction to the network.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "BroadcastTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &BroadcastTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.BroadcastTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.SignedRawTransaction, cfg.FlagNamer("SignedRawTransaction"), "", "The signed raw transaction data to be broadcasted.") return cmd } func _TransactionGetRawTransferTransactionCommand(cfg *client.Config) *cobra.Command { req := &GetRawTransferTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetRawTransferTransaction"), Short: "GetRawTransferTransaction RPC client", Long: "GetRawTransferTransaction retrieves raw details of a transfer transaction.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "GetRawTransferTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &GetRawTransferTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetRawTransferTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.LockTime, cfg.FlagNamer("LockTime"), 0, "The lock time for the transaction. If not set, defaults to the last block height.") cmd.PersistentFlags().StringVar(&req.Sender, cfg.FlagNamer("Sender"), "", "The sender's account address.") cmd.PersistentFlags().StringVar(&req.Receiver, cfg.FlagNamer("Receiver"), "", "The receiver's account address.") cmd.PersistentFlags().Int64Var(&req.Amount, cfg.FlagNamer("Amount"), 0, "The amount to be transferred, specified in NanoPAC. Must be greater than 0.") cmd.PersistentFlags().Int64Var(&req.Fee, cfg.FlagNamer("Fee"), 0, "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.") cmd.PersistentFlags().StringVar(&req.Memo, cfg.FlagNamer("Memo"), "", "A memo string for the transaction.") return cmd } func _TransactionGetRawBondTransactionCommand(cfg *client.Config) *cobra.Command { req := &GetRawBondTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetRawBondTransaction"), Short: "GetRawBondTransaction RPC client", Long: "GetRawBondTransaction retrieves raw details of a bond transaction.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "GetRawBondTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &GetRawBondTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetRawBondTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.LockTime, cfg.FlagNamer("LockTime"), 0, "The lock time for the transaction. If not set, defaults to the last block height.") cmd.PersistentFlags().StringVar(&req.Sender, cfg.FlagNamer("Sender"), "", "The sender's account address.") cmd.PersistentFlags().StringVar(&req.Receiver, cfg.FlagNamer("Receiver"), "", "The receiver's validator address.") cmd.PersistentFlags().Int64Var(&req.Stake, cfg.FlagNamer("Stake"), 0, "The stake amount in NanoPAC. Must be greater than 0.") cmd.PersistentFlags().StringVar(&req.PublicKey, cfg.FlagNamer("PublicKey"), "", "The public key of the validator.\n Optional, but required when registering a new validator.;") cmd.PersistentFlags().Int64Var(&req.Fee, cfg.FlagNamer("Fee"), 0, "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.") cmd.PersistentFlags().StringVar(&req.Memo, cfg.FlagNamer("Memo"), "", "A memo string for the transaction.") cmd.PersistentFlags().StringVar(&req.DelegateOwner, cfg.FlagNamer("DelegateOwner"), "", "The address of the delegate owner.\n Optional, but required when registering a new validator with delegation.;") cmd.PersistentFlags().Int64Var(&req.DelegateShare, cfg.FlagNamer("DelegateShare"), 0, "The share percentage for the delegate owner.\n Optional, but required when registering a new validator with delegation.;\n Must be between 0 and 0.7 PAC in nano PAC.") cmd.PersistentFlags().Uint32Var(&req.DelegateExpiry, cfg.FlagNamer("DelegateExpiry"), 0, "The expiry height for the delegate relationship.\n Optional, but required when registering a new validator with delegation.;") return cmd } func _TransactionGetRawUnbondTransactionCommand(cfg *client.Config) *cobra.Command { req := &GetRawUnbondTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetRawUnbondTransaction"), Short: "GetRawUnbondTransaction RPC client", Long: "GetRawUnbondTransaction retrieves raw details of an unbond transaction.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "GetRawUnbondTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &GetRawUnbondTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetRawUnbondTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.LockTime, cfg.FlagNamer("LockTime"), 0, "The lock time for the transaction. If not set, defaults to the last block height.") cmd.PersistentFlags().StringVar(&req.ValidatorAddress, cfg.FlagNamer("ValidatorAddress"), "", "The address of the validator to unbond from.") cmd.PersistentFlags().StringVar(&req.Memo, cfg.FlagNamer("Memo"), "", "A memo string for the transaction.") cmd.PersistentFlags().StringVar(&req.DelegateOwner, cfg.FlagNamer("DelegateOwner"), "", "The address of the delegate owner.\n Optional, but required when the validator is a delegated validator.;") return cmd } func _TransactionGetRawWithdrawTransactionCommand(cfg *client.Config) *cobra.Command { req := &GetRawWithdrawTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetRawWithdrawTransaction"), Short: "GetRawWithdrawTransaction RPC client", Long: "GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "GetRawWithdrawTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &GetRawWithdrawTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetRawWithdrawTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.LockTime, cfg.FlagNamer("LockTime"), 0, "The lock time for the transaction. If not set, defaults to the last block height.") cmd.PersistentFlags().StringVar(&req.ValidatorAddress, cfg.FlagNamer("ValidatorAddress"), "", "The address of the validator to withdraw from.") cmd.PersistentFlags().StringVar(&req.AccountAddress, cfg.FlagNamer("AccountAddress"), "", "The address of the account to withdraw to.") cmd.PersistentFlags().Int64Var(&req.Amount, cfg.FlagNamer("Amount"), 0, "The withdrawal amount in NanoPAC. Must be greater than 0.") cmd.PersistentFlags().Int64Var(&req.Fee, cfg.FlagNamer("Fee"), 0, "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.") cmd.PersistentFlags().StringVar(&req.Memo, cfg.FlagNamer("Memo"), "", "A memo string for the transaction.") return cmd } func _TransactionGetRawBatchTransferTransactionCommand(cfg *client.Config) *cobra.Command { req := &GetRawBatchTransferTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetRawBatchTransferTransaction"), Short: "GetRawBatchTransferTransaction RPC client", Long: "GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "GetRawBatchTransferTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &GetRawBatchTransferTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetRawBatchTransferTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().Uint32Var(&req.LockTime, cfg.FlagNamer("LockTime"), 0, "The lock time for the transaction. If not set, defaults to the last block height.") cmd.PersistentFlags().StringVar(&req.Sender, cfg.FlagNamer("Sender"), "", "The sender's account address.") flag.SliceVar(cmd.PersistentFlags(), flag.ParseMessageE[*Recipient], &req.Recipients, cfg.FlagNamer("Recipients"), "The list of recipients with their amounts. Minimum 2 recipients required.") cmd.PersistentFlags().Int64Var(&req.Fee, cfg.FlagNamer("Fee"), 0, "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.") cmd.PersistentFlags().StringVar(&req.Memo, cfg.FlagNamer("Memo"), "", "A memo string for the transaction.") return cmd } func _TransactionDecodeRawTransactionCommand(cfg *client.Config) *cobra.Command { req := &DecodeRawTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("DecodeRawTransaction"), Short: "DecodeRawTransaction RPC client", Long: "DecodeRawTransaction accepts raw transaction and returns decoded transaction.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "DecodeRawTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &DecodeRawTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.DecodeRawTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.RawTransaction, cfg.FlagNamer("RawTransaction"), "", "The raw transaction data in hexadecimal format.") return cmd } func _TransactionCheckTransactionCommand(cfg *client.Config) *cobra.Command { req := &CheckTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("CheckTransaction"), Short: "CheckTransaction RPC client", Long: "CheckTransaction checks if the transaction is valid and can be included in the blockchain.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Transaction", "CheckTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewTransactionClient(cc) v := &CheckTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.CheckTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.RawTransaction, cfg.FlagNamer("RawTransaction"), "", "The raw transaction data to be checked.") return cmd } ================================================ FILE: www/grpc/gen/go/transaction.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: transaction.proto package pactus import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Enumeration for different types of transaction payloads. type PayloadType int32 const ( // Unspecified payload type. PayloadType_PAYLOAD_TYPE_UNSPECIFIED PayloadType = 0 // Transfer payload type. PayloadType_PAYLOAD_TYPE_TRANSFER PayloadType = 1 // Bond payload type. PayloadType_PAYLOAD_TYPE_BOND PayloadType = 2 // Sortition payload type. PayloadType_PAYLOAD_TYPE_SORTITION PayloadType = 3 // Unbond payload type. PayloadType_PAYLOAD_TYPE_UNBOND PayloadType = 4 // Withdraw payload type. PayloadType_PAYLOAD_TYPE_WITHDRAW PayloadType = 5 // Batch transfer payload type. PayloadType_PAYLOAD_TYPE_BATCH_TRANSFER PayloadType = 6 ) // Enum value maps for PayloadType. var ( PayloadType_name = map[int32]string{ 0: "PAYLOAD_TYPE_UNSPECIFIED", 1: "PAYLOAD_TYPE_TRANSFER", 2: "PAYLOAD_TYPE_BOND", 3: "PAYLOAD_TYPE_SORTITION", 4: "PAYLOAD_TYPE_UNBOND", 5: "PAYLOAD_TYPE_WITHDRAW", 6: "PAYLOAD_TYPE_BATCH_TRANSFER", } PayloadType_value = map[string]int32{ "PAYLOAD_TYPE_UNSPECIFIED": 0, "PAYLOAD_TYPE_TRANSFER": 1, "PAYLOAD_TYPE_BOND": 2, "PAYLOAD_TYPE_SORTITION": 3, "PAYLOAD_TYPE_UNBOND": 4, "PAYLOAD_TYPE_WITHDRAW": 5, "PAYLOAD_TYPE_BATCH_TRANSFER": 6, } ) func (x PayloadType) Enum() *PayloadType { p := new(PayloadType) *p = x return p } func (x PayloadType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (PayloadType) Descriptor() protoreflect.EnumDescriptor { return file_transaction_proto_enumTypes[0].Descriptor() } func (PayloadType) Type() protoreflect.EnumType { return &file_transaction_proto_enumTypes[0] } func (x PayloadType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use PayloadType.Descriptor instead. func (PayloadType) EnumDescriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{0} } // Enumeration for verbosity levels when requesting transaction details. type TransactionVerbosity int32 const ( // Request transaction data only. TransactionVerbosity_TRANSACTION_VERBOSITY_DATA TransactionVerbosity = 0 // Request detailed transaction information. TransactionVerbosity_TRANSACTION_VERBOSITY_INFO TransactionVerbosity = 1 ) // Enum value maps for TransactionVerbosity. var ( TransactionVerbosity_name = map[int32]string{ 0: "TRANSACTION_VERBOSITY_DATA", 1: "TRANSACTION_VERBOSITY_INFO", } TransactionVerbosity_value = map[string]int32{ "TRANSACTION_VERBOSITY_DATA": 0, "TRANSACTION_VERBOSITY_INFO": 1, } ) func (x TransactionVerbosity) Enum() *TransactionVerbosity { p := new(TransactionVerbosity) *p = x return p } func (x TransactionVerbosity) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TransactionVerbosity) Descriptor() protoreflect.EnumDescriptor { return file_transaction_proto_enumTypes[1].Descriptor() } func (TransactionVerbosity) Type() protoreflect.EnumType { return &file_transaction_proto_enumTypes[1] } func (x TransactionVerbosity) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TransactionVerbosity.Descriptor instead. func (TransactionVerbosity) EnumDescriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{1} } // Request message for retrieving transaction details. type GetTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The unique ID of the transaction to retrieve. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // The verbosity level for transaction details. Verbosity TransactionVerbosity `protobuf:"varint,2,opt,name=verbosity,proto3,enum=pactus.TransactionVerbosity" json:"verbosity,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTransactionRequest) Reset() { *x = GetTransactionRequest{} mi := &file_transaction_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTransactionRequest) ProtoMessage() {} func (x *GetTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTransactionRequest.ProtoReflect.Descriptor instead. func (*GetTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{0} } func (x *GetTransactionRequest) GetId() string { if x != nil { return x.Id } return "" } func (x *GetTransactionRequest) GetVerbosity() TransactionVerbosity { if x != nil { return x.Verbosity } return TransactionVerbosity_TRANSACTION_VERBOSITY_DATA } // Response message contains details of a transaction. type GetTransactionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The height of the block containing the transaction. BlockHeight uint32 `protobuf:"varint,1,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` // The UNIX timestamp of the block containing the transaction. BlockTime uint32 `protobuf:"varint,2,opt,name=block_time,json=blockTime,proto3" json:"block_time,omitempty"` // Detailed information about the transaction. Transaction *TransactionInfo `protobuf:"bytes,3,opt,name=transaction,proto3" json:"transaction,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTransactionResponse) Reset() { *x = GetTransactionResponse{} mi := &file_transaction_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTransactionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTransactionResponse) ProtoMessage() {} func (x *GetTransactionResponse) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTransactionResponse.ProtoReflect.Descriptor instead. func (*GetTransactionResponse) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{1} } func (x *GetTransactionResponse) GetBlockHeight() uint32 { if x != nil { return x.BlockHeight } return 0 } func (x *GetTransactionResponse) GetBlockTime() uint32 { if x != nil { return x.BlockTime } return 0 } func (x *GetTransactionResponse) GetTransaction() *TransactionInfo { if x != nil { return x.Transaction } return nil } // Request message for calculating transaction fee. type CalculateFeeRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The amount involved in the transaction, specified in NanoPAC. Amount int64 `protobuf:"varint,1,opt,name=amount,proto3" json:"amount,omitempty"` // The type of transaction payload. PayloadType PayloadType `protobuf:"varint,2,opt,name=payload_type,json=payloadType,proto3,enum=pactus.PayloadType" json:"payload_type,omitempty"` // Indicates if the amount should be fixed and include the fee. FixedAmount bool `protobuf:"varint,3,opt,name=fixed_amount,json=fixedAmount,proto3" json:"fixed_amount,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CalculateFeeRequest) Reset() { *x = CalculateFeeRequest{} mi := &file_transaction_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CalculateFeeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*CalculateFeeRequest) ProtoMessage() {} func (x *CalculateFeeRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CalculateFeeRequest.ProtoReflect.Descriptor instead. func (*CalculateFeeRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{2} } func (x *CalculateFeeRequest) GetAmount() int64 { if x != nil { return x.Amount } return 0 } func (x *CalculateFeeRequest) GetPayloadType() PayloadType { if x != nil { return x.PayloadType } return PayloadType_PAYLOAD_TYPE_UNSPECIFIED } func (x *CalculateFeeRequest) GetFixedAmount() bool { if x != nil { return x.FixedAmount } return false } // Response message contains the calculated transaction fee. type CalculateFeeResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The calculated amount in NanoPAC. Amount int64 `protobuf:"varint,1,opt,name=amount,proto3" json:"amount,omitempty"` // The calculated transaction fee in NanoPAC. Fee int64 `protobuf:"varint,2,opt,name=fee,proto3" json:"fee,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CalculateFeeResponse) Reset() { *x = CalculateFeeResponse{} mi := &file_transaction_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CalculateFeeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*CalculateFeeResponse) ProtoMessage() {} func (x *CalculateFeeResponse) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CalculateFeeResponse.ProtoReflect.Descriptor instead. func (*CalculateFeeResponse) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{3} } func (x *CalculateFeeResponse) GetAmount() int64 { if x != nil { return x.Amount } return 0 } func (x *CalculateFeeResponse) GetFee() int64 { if x != nil { return x.Fee } return 0 } // Request message for broadcasting a signed transaction to the network. type BroadcastTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The signed raw transaction data to be broadcasted. SignedRawTransaction string `protobuf:"bytes,1,opt,name=signed_raw_transaction,json=signedRawTransaction,proto3" json:"signed_raw_transaction,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *BroadcastTransactionRequest) Reset() { *x = BroadcastTransactionRequest{} mi := &file_transaction_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *BroadcastTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*BroadcastTransactionRequest) ProtoMessage() {} func (x *BroadcastTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BroadcastTransactionRequest.ProtoReflect.Descriptor instead. func (*BroadcastTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{4} } func (x *BroadcastTransactionRequest) GetSignedRawTransaction() string { if x != nil { return x.SignedRawTransaction } return "" } // Response message contains the ID of the broadcasted transaction. type BroadcastTransactionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The unique ID of the broadcasted transaction. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *BroadcastTransactionResponse) Reset() { *x = BroadcastTransactionResponse{} mi := &file_transaction_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *BroadcastTransactionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*BroadcastTransactionResponse) ProtoMessage() {} func (x *BroadcastTransactionResponse) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BroadcastTransactionResponse.ProtoReflect.Descriptor instead. func (*BroadcastTransactionResponse) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{5} } func (x *BroadcastTransactionResponse) GetId() string { if x != nil { return x.Id } return "" } // Request message for retrieving raw details of a transfer transaction. type GetRawTransferTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The lock time for the transaction. If not set, defaults to the last block height. LockTime uint32 `protobuf:"varint,1,opt,name=lock_time,json=lockTime,proto3" json:"lock_time,omitempty"` // The sender's account address. Sender string `protobuf:"bytes,2,opt,name=sender,proto3" json:"sender,omitempty"` // The receiver's account address. Receiver string `protobuf:"bytes,3,opt,name=receiver,proto3" json:"receiver,omitempty"` // The amount to be transferred, specified in NanoPAC. Must be greater than 0. Amount int64 `protobuf:"varint,4,opt,name=amount,proto3" json:"amount,omitempty"` // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. Fee int64 `protobuf:"varint,5,opt,name=fee,proto3" json:"fee,omitempty"` // A memo string for the transaction. Memo string `protobuf:"bytes,6,opt,name=memo,proto3" json:"memo,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetRawTransferTransactionRequest) Reset() { *x = GetRawTransferTransactionRequest{} mi := &file_transaction_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetRawTransferTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetRawTransferTransactionRequest) ProtoMessage() {} func (x *GetRawTransferTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetRawTransferTransactionRequest.ProtoReflect.Descriptor instead. func (*GetRawTransferTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{6} } func (x *GetRawTransferTransactionRequest) GetLockTime() uint32 { if x != nil { return x.LockTime } return 0 } func (x *GetRawTransferTransactionRequest) GetSender() string { if x != nil { return x.Sender } return "" } func (x *GetRawTransferTransactionRequest) GetReceiver() string { if x != nil { return x.Receiver } return "" } func (x *GetRawTransferTransactionRequest) GetAmount() int64 { if x != nil { return x.Amount } return 0 } func (x *GetRawTransferTransactionRequest) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *GetRawTransferTransactionRequest) GetMemo() string { if x != nil { return x.Memo } return "" } // Request message for retrieving raw details of a bond transaction. type GetRawBondTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The lock time for the transaction. If not set, defaults to the last block height. LockTime uint32 `protobuf:"varint,1,opt,name=lock_time,json=lockTime,proto3" json:"lock_time,omitempty"` // The sender's account address. Sender string `protobuf:"bytes,2,opt,name=sender,proto3" json:"sender,omitempty"` // The receiver's validator address. Receiver string `protobuf:"bytes,3,opt,name=receiver,proto3" json:"receiver,omitempty"` // The stake amount in NanoPAC. Must be greater than 0. Stake int64 `protobuf:"varint,4,opt,name=stake,proto3" json:"stake,omitempty"` // The public key of the validator. // Optional, but required when registering a new validator.; PublicKey string `protobuf:"bytes,5,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. Fee int64 `protobuf:"varint,6,opt,name=fee,proto3" json:"fee,omitempty"` // A memo string for the transaction. Memo string `protobuf:"bytes,7,opt,name=memo,proto3" json:"memo,omitempty"` // The address of the delegate owner. // Optional, but required when registering a new validator with delegation.; DelegateOwner string `protobuf:"bytes,8,opt,name=delegate_owner,json=delegateOwner,proto3" json:"delegate_owner,omitempty"` // The share percentage for the delegate owner. // Optional, but required when registering a new validator with delegation.; // Must be between 0 and 0.7 PAC in nano PAC. DelegateShare int64 `protobuf:"varint,9,opt,name=delegate_share,json=delegateShare,proto3" json:"delegate_share,omitempty"` // The expiry height for the delegate relationship. // Optional, but required when registering a new validator with delegation.; DelegateExpiry uint32 `protobuf:"varint,10,opt,name=delegate_expiry,json=delegateExpiry,proto3" json:"delegate_expiry,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetRawBondTransactionRequest) Reset() { *x = GetRawBondTransactionRequest{} mi := &file_transaction_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetRawBondTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetRawBondTransactionRequest) ProtoMessage() {} func (x *GetRawBondTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetRawBondTransactionRequest.ProtoReflect.Descriptor instead. func (*GetRawBondTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{7} } func (x *GetRawBondTransactionRequest) GetLockTime() uint32 { if x != nil { return x.LockTime } return 0 } func (x *GetRawBondTransactionRequest) GetSender() string { if x != nil { return x.Sender } return "" } func (x *GetRawBondTransactionRequest) GetReceiver() string { if x != nil { return x.Receiver } return "" } func (x *GetRawBondTransactionRequest) GetStake() int64 { if x != nil { return x.Stake } return 0 } func (x *GetRawBondTransactionRequest) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *GetRawBondTransactionRequest) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *GetRawBondTransactionRequest) GetMemo() string { if x != nil { return x.Memo } return "" } func (x *GetRawBondTransactionRequest) GetDelegateOwner() string { if x != nil { return x.DelegateOwner } return "" } func (x *GetRawBondTransactionRequest) GetDelegateShare() int64 { if x != nil { return x.DelegateShare } return 0 } func (x *GetRawBondTransactionRequest) GetDelegateExpiry() uint32 { if x != nil { return x.DelegateExpiry } return 0 } // Request message for retrieving raw details of an unbond transaction. type GetRawUnbondTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The lock time for the transaction. If not set, defaults to the last block height. LockTime uint32 `protobuf:"varint,1,opt,name=lock_time,json=lockTime,proto3" json:"lock_time,omitempty"` // The address of the validator to unbond from. ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` // A memo string for the transaction. Memo string `protobuf:"bytes,3,opt,name=memo,proto3" json:"memo,omitempty"` // The address of the delegate owner. // Optional, but required when the validator is a delegated validator.; DelegateOwner string `protobuf:"bytes,4,opt,name=delegate_owner,json=delegateOwner,proto3" json:"delegate_owner,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetRawUnbondTransactionRequest) Reset() { *x = GetRawUnbondTransactionRequest{} mi := &file_transaction_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetRawUnbondTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetRawUnbondTransactionRequest) ProtoMessage() {} func (x *GetRawUnbondTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetRawUnbondTransactionRequest.ProtoReflect.Descriptor instead. func (*GetRawUnbondTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{8} } func (x *GetRawUnbondTransactionRequest) GetLockTime() uint32 { if x != nil { return x.LockTime } return 0 } func (x *GetRawUnbondTransactionRequest) GetValidatorAddress() string { if x != nil { return x.ValidatorAddress } return "" } func (x *GetRawUnbondTransactionRequest) GetMemo() string { if x != nil { return x.Memo } return "" } func (x *GetRawUnbondTransactionRequest) GetDelegateOwner() string { if x != nil { return x.DelegateOwner } return "" } // Request message for retrieving raw details of a withdraw transaction. type GetRawWithdrawTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The lock time for the transaction. If not set, defaults to the last block height. LockTime uint32 `protobuf:"varint,1,opt,name=lock_time,json=lockTime,proto3" json:"lock_time,omitempty"` // The address of the validator to withdraw from. ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` // The address of the account to withdraw to. AccountAddress string `protobuf:"bytes,3,opt,name=account_address,json=accountAddress,proto3" json:"account_address,omitempty"` // The withdrawal amount in NanoPAC. Must be greater than 0. Amount int64 `protobuf:"varint,4,opt,name=amount,proto3" json:"amount,omitempty"` // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. Fee int64 `protobuf:"varint,5,opt,name=fee,proto3" json:"fee,omitempty"` // A memo string for the transaction. Memo string `protobuf:"bytes,6,opt,name=memo,proto3" json:"memo,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetRawWithdrawTransactionRequest) Reset() { *x = GetRawWithdrawTransactionRequest{} mi := &file_transaction_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetRawWithdrawTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetRawWithdrawTransactionRequest) ProtoMessage() {} func (x *GetRawWithdrawTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetRawWithdrawTransactionRequest.ProtoReflect.Descriptor instead. func (*GetRawWithdrawTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{9} } func (x *GetRawWithdrawTransactionRequest) GetLockTime() uint32 { if x != nil { return x.LockTime } return 0 } func (x *GetRawWithdrawTransactionRequest) GetValidatorAddress() string { if x != nil { return x.ValidatorAddress } return "" } func (x *GetRawWithdrawTransactionRequest) GetAccountAddress() string { if x != nil { return x.AccountAddress } return "" } func (x *GetRawWithdrawTransactionRequest) GetAmount() int64 { if x != nil { return x.Amount } return 0 } func (x *GetRawWithdrawTransactionRequest) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *GetRawWithdrawTransactionRequest) GetMemo() string { if x != nil { return x.Memo } return "" } // Request message for retrieving raw details of a batch transfer transaction. type GetRawBatchTransferTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The lock time for the transaction. If not set, defaults to the last block height. LockTime uint32 `protobuf:"varint,1,opt,name=lock_time,json=lockTime,proto3" json:"lock_time,omitempty"` // The sender's account address. Sender string `protobuf:"bytes,2,opt,name=sender,proto3" json:"sender,omitempty"` // The list of recipients with their amounts. Minimum 2 recipients required. Recipients []*Recipient `protobuf:"bytes,3,rep,name=recipients,proto3" json:"recipients,omitempty"` // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. Fee int64 `protobuf:"varint,4,opt,name=fee,proto3" json:"fee,omitempty"` // A memo string for the transaction. Memo string `protobuf:"bytes,5,opt,name=memo,proto3" json:"memo,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetRawBatchTransferTransactionRequest) Reset() { *x = GetRawBatchTransferTransactionRequest{} mi := &file_transaction_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetRawBatchTransferTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetRawBatchTransferTransactionRequest) ProtoMessage() {} func (x *GetRawBatchTransferTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetRawBatchTransferTransactionRequest.ProtoReflect.Descriptor instead. func (*GetRawBatchTransferTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{10} } func (x *GetRawBatchTransferTransactionRequest) GetLockTime() uint32 { if x != nil { return x.LockTime } return 0 } func (x *GetRawBatchTransferTransactionRequest) GetSender() string { if x != nil { return x.Sender } return "" } func (x *GetRawBatchTransferTransactionRequest) GetRecipients() []*Recipient { if x != nil { return x.Recipients } return nil } func (x *GetRawBatchTransferTransactionRequest) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *GetRawBatchTransferTransactionRequest) GetMemo() string { if x != nil { return x.Memo } return "" } // Response message contains raw transaction data. type GetRawTransactionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The raw transaction data in hexadecimal format. RawTransaction string `protobuf:"bytes,1,opt,name=raw_transaction,json=rawTransaction,proto3" json:"raw_transaction,omitempty"` // The unique ID of the transaction. Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetRawTransactionResponse) Reset() { *x = GetRawTransactionResponse{} mi := &file_transaction_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetRawTransactionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetRawTransactionResponse) ProtoMessage() {} func (x *GetRawTransactionResponse) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetRawTransactionResponse.ProtoReflect.Descriptor instead. func (*GetRawTransactionResponse) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{11} } func (x *GetRawTransactionResponse) GetRawTransaction() string { if x != nil { return x.RawTransaction } return "" } func (x *GetRawTransactionResponse) GetId() string { if x != nil { return x.Id } return "" } // Payload for a transfer transaction. type PayloadTransfer struct { state protoimpl.MessageState `protogen:"open.v1"` // The sender's address. Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` // The receiver's address. Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` // The amount to be transferred in NanoPAC. Amount int64 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PayloadTransfer) Reset() { *x = PayloadTransfer{} mi := &file_transaction_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PayloadTransfer) String() string { return protoimpl.X.MessageStringOf(x) } func (*PayloadTransfer) ProtoMessage() {} func (x *PayloadTransfer) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PayloadTransfer.ProtoReflect.Descriptor instead. func (*PayloadTransfer) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{12} } func (x *PayloadTransfer) GetSender() string { if x != nil { return x.Sender } return "" } func (x *PayloadTransfer) GetReceiver() string { if x != nil { return x.Receiver } return "" } func (x *PayloadTransfer) GetAmount() int64 { if x != nil { return x.Amount } return 0 } // Payload for a bond transaction. type PayloadBond struct { state protoimpl.MessageState `protogen:"open.v1"` // The sender's address. Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` // The receiver's address. Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` // The stake amount in NanoPAC. Stake int64 `protobuf:"varint,3,opt,name=stake,proto3" json:"stake,omitempty"` // The public key of the validator. PublicKey string `protobuf:"bytes,4,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // Indicates whether the bond transaction is a delegation. IsDelegated bool `protobuf:"varint,5,opt,name=is_delegated,json=isDelegated,proto3" json:"is_delegated,omitempty"` // The address of the delegate owner. // Optional, but required when registering a new validator with delegation.; DelegateOwner string `protobuf:"bytes,6,opt,name=delegate_owner,json=delegateOwner,proto3" json:"delegate_owner,omitempty"` // The share percentage for the delegate owner. // Optional, but required when registering a new validator with delegation.; // Must be between 0 and 0.7 PAC in nano PAC. DelegateShare int64 `protobuf:"varint,7,opt,name=delegate_share,json=delegateShare,proto3" json:"delegate_share,omitempty"` // The expiry height for the delegate relationship. // Optional, but required when registering a new validator with delegation.; DelegateExpiry uint32 `protobuf:"varint,8,opt,name=delegate_expiry,json=delegateExpiry,proto3" json:"delegate_expiry,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PayloadBond) Reset() { *x = PayloadBond{} mi := &file_transaction_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PayloadBond) String() string { return protoimpl.X.MessageStringOf(x) } func (*PayloadBond) ProtoMessage() {} func (x *PayloadBond) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PayloadBond.ProtoReflect.Descriptor instead. func (*PayloadBond) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{13} } func (x *PayloadBond) GetSender() string { if x != nil { return x.Sender } return "" } func (x *PayloadBond) GetReceiver() string { if x != nil { return x.Receiver } return "" } func (x *PayloadBond) GetStake() int64 { if x != nil { return x.Stake } return 0 } func (x *PayloadBond) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *PayloadBond) GetIsDelegated() bool { if x != nil { return x.IsDelegated } return false } func (x *PayloadBond) GetDelegateOwner() string { if x != nil { return x.DelegateOwner } return "" } func (x *PayloadBond) GetDelegateShare() int64 { if x != nil { return x.DelegateShare } return 0 } func (x *PayloadBond) GetDelegateExpiry() uint32 { if x != nil { return x.DelegateExpiry } return 0 } // Payload for a sortition transaction. type PayloadSortition struct { state protoimpl.MessageState `protogen:"open.v1"` // The validator address associated with the sortition proof. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` // The proof for the sortition. Proof string `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PayloadSortition) Reset() { *x = PayloadSortition{} mi := &file_transaction_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PayloadSortition) String() string { return protoimpl.X.MessageStringOf(x) } func (*PayloadSortition) ProtoMessage() {} func (x *PayloadSortition) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PayloadSortition.ProtoReflect.Descriptor instead. func (*PayloadSortition) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{14} } func (x *PayloadSortition) GetAddress() string { if x != nil { return x.Address } return "" } func (x *PayloadSortition) GetProof() string { if x != nil { return x.Proof } return "" } // Payload for an unbond transaction. type PayloadUnbond struct { state protoimpl.MessageState `protogen:"open.v1"` // The address of the validator to unbond from. Validator string `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator,omitempty"` // The address of the delegate owner. // Optional, but required when the validator is a delegated validator.; DelegateOwner string `protobuf:"bytes,2,opt,name=delegate_owner,json=delegateOwner,proto3" json:"delegate_owner,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PayloadUnbond) Reset() { *x = PayloadUnbond{} mi := &file_transaction_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PayloadUnbond) String() string { return protoimpl.X.MessageStringOf(x) } func (*PayloadUnbond) ProtoMessage() {} func (x *PayloadUnbond) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PayloadUnbond.ProtoReflect.Descriptor instead. func (*PayloadUnbond) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{15} } func (x *PayloadUnbond) GetValidator() string { if x != nil { return x.Validator } return "" } func (x *PayloadUnbond) GetDelegateOwner() string { if x != nil { return x.DelegateOwner } return "" } // Payload for a withdraw transaction. type PayloadWithdraw struct { state protoimpl.MessageState `protogen:"open.v1"` // The address of the validator to withdraw from. ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` // The address of the account to withdraw to. AccountAddress string `protobuf:"bytes,2,opt,name=account_address,json=accountAddress,proto3" json:"account_address,omitempty"` // The withdrawal amount in NanoPAC. Amount int64 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PayloadWithdraw) Reset() { *x = PayloadWithdraw{} mi := &file_transaction_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PayloadWithdraw) String() string { return protoimpl.X.MessageStringOf(x) } func (*PayloadWithdraw) ProtoMessage() {} func (x *PayloadWithdraw) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PayloadWithdraw.ProtoReflect.Descriptor instead. func (*PayloadWithdraw) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{16} } func (x *PayloadWithdraw) GetValidatorAddress() string { if x != nil { return x.ValidatorAddress } return "" } func (x *PayloadWithdraw) GetAccountAddress() string { if x != nil { return x.AccountAddress } return "" } func (x *PayloadWithdraw) GetAmount() int64 { if x != nil { return x.Amount } return 0 } // Payload for a batch transfer transaction. type PayloadBatchTransfer struct { state protoimpl.MessageState `protogen:"open.v1"` // The sender's address. Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` // The list of recipients with their amounts. Recipients []*Recipient `protobuf:"bytes,2,rep,name=recipients,proto3" json:"recipients,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PayloadBatchTransfer) Reset() { *x = PayloadBatchTransfer{} mi := &file_transaction_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PayloadBatchTransfer) String() string { return protoimpl.X.MessageStringOf(x) } func (*PayloadBatchTransfer) ProtoMessage() {} func (x *PayloadBatchTransfer) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PayloadBatchTransfer.ProtoReflect.Descriptor instead. func (*PayloadBatchTransfer) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{17} } func (x *PayloadBatchTransfer) GetSender() string { if x != nil { return x.Sender } return "" } func (x *PayloadBatchTransfer) GetRecipients() []*Recipient { if x != nil { return x.Recipients } return nil } // Recipient is receiver with amount. type Recipient struct { state protoimpl.MessageState `protogen:"open.v1"` // The receiver's address. Receiver string `protobuf:"bytes,1,opt,name=receiver,proto3" json:"receiver,omitempty"` // The amount in NanoPAC. Amount int64 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Recipient) Reset() { *x = Recipient{} mi := &file_transaction_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Recipient) String() string { return protoimpl.X.MessageStringOf(x) } func (*Recipient) ProtoMessage() {} func (x *Recipient) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Recipient.ProtoReflect.Descriptor instead. func (*Recipient) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{18} } func (x *Recipient) GetReceiver() string { if x != nil { return x.Receiver } return "" } func (x *Recipient) GetAmount() int64 { if x != nil { return x.Amount } return 0 } // Information about a transaction. type TransactionInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The unique ID of the transaction. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // The raw transaction data in hexadecimal format. Data string `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` // The version of the transaction. Version int32 `protobuf:"varint,3,opt,name=version,proto3" json:"version,omitempty"` // The lock time for the transaction. LockTime uint32 `protobuf:"varint,4,opt,name=lock_time,json=lockTime,proto3" json:"lock_time,omitempty"` // The value of the transaction in NanoPAC. Value int64 `protobuf:"varint,5,opt,name=value,proto3" json:"value,omitempty"` // The fee for the transaction in NanoPAC. Fee int64 `protobuf:"varint,6,opt,name=fee,proto3" json:"fee,omitempty"` // The type of transaction payload. PayloadType PayloadType `protobuf:"varint,7,opt,name=payload_type,json=payloadType,proto3,enum=pactus.PayloadType" json:"payload_type,omitempty"` // Transaction payload. // // Types that are valid to be assigned to Payload: // // *TransactionInfo_Transfer // *TransactionInfo_Bond // *TransactionInfo_Sortition // *TransactionInfo_Unbond // *TransactionInfo_Withdraw // *TransactionInfo_BatchTransfer Payload isTransactionInfo_Payload `protobuf_oneof:"payload"` // A memo string for the transaction. Memo string `protobuf:"bytes,8,opt,name=memo,proto3" json:"memo,omitempty"` // The public key associated with the transaction. PublicKey string `protobuf:"bytes,9,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // The signature for the transaction. Signature string `protobuf:"bytes,10,opt,name=signature,proto3" json:"signature,omitempty"` // The block height containing the transaction. // A value of zero means the transaction is unconfirmed and may still in the transaction pool. BlockHeight uint32 `protobuf:"varint,11,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` // Indicates whether the transaction is confirmed. Confirmed bool `protobuf:"varint,12,opt,name=confirmed,proto3" json:"confirmed,omitempty"` // The number of blocks that have been added to the chain after this transaction was included in a block. // A value of zero means the transaction is unconfirmed and may still in the transaction pool. Confirmations int32 `protobuf:"varint,13,opt,name=confirmations,proto3" json:"confirmations,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *TransactionInfo) Reset() { *x = TransactionInfo{} mi := &file_transaction_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *TransactionInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionInfo) ProtoMessage() {} func (x *TransactionInfo) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TransactionInfo.ProtoReflect.Descriptor instead. func (*TransactionInfo) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{19} } func (x *TransactionInfo) GetId() string { if x != nil { return x.Id } return "" } func (x *TransactionInfo) GetData() string { if x != nil { return x.Data } return "" } func (x *TransactionInfo) GetVersion() int32 { if x != nil { return x.Version } return 0 } func (x *TransactionInfo) GetLockTime() uint32 { if x != nil { return x.LockTime } return 0 } func (x *TransactionInfo) GetValue() int64 { if x != nil { return x.Value } return 0 } func (x *TransactionInfo) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *TransactionInfo) GetPayloadType() PayloadType { if x != nil { return x.PayloadType } return PayloadType_PAYLOAD_TYPE_UNSPECIFIED } func (x *TransactionInfo) GetPayload() isTransactionInfo_Payload { if x != nil { return x.Payload } return nil } func (x *TransactionInfo) GetTransfer() *PayloadTransfer { if x != nil { if x, ok := x.Payload.(*TransactionInfo_Transfer); ok { return x.Transfer } } return nil } func (x *TransactionInfo) GetBond() *PayloadBond { if x != nil { if x, ok := x.Payload.(*TransactionInfo_Bond); ok { return x.Bond } } return nil } func (x *TransactionInfo) GetSortition() *PayloadSortition { if x != nil { if x, ok := x.Payload.(*TransactionInfo_Sortition); ok { return x.Sortition } } return nil } func (x *TransactionInfo) GetUnbond() *PayloadUnbond { if x != nil { if x, ok := x.Payload.(*TransactionInfo_Unbond); ok { return x.Unbond } } return nil } func (x *TransactionInfo) GetWithdraw() *PayloadWithdraw { if x != nil { if x, ok := x.Payload.(*TransactionInfo_Withdraw); ok { return x.Withdraw } } return nil } func (x *TransactionInfo) GetBatchTransfer() *PayloadBatchTransfer { if x != nil { if x, ok := x.Payload.(*TransactionInfo_BatchTransfer); ok { return x.BatchTransfer } } return nil } func (x *TransactionInfo) GetMemo() string { if x != nil { return x.Memo } return "" } func (x *TransactionInfo) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *TransactionInfo) GetSignature() string { if x != nil { return x.Signature } return "" } func (x *TransactionInfo) GetBlockHeight() uint32 { if x != nil { return x.BlockHeight } return 0 } func (x *TransactionInfo) GetConfirmed() bool { if x != nil { return x.Confirmed } return false } func (x *TransactionInfo) GetConfirmations() int32 { if x != nil { return x.Confirmations } return 0 } type isTransactionInfo_Payload interface { isTransactionInfo_Payload() } type TransactionInfo_Transfer struct { // Transfer transaction payload. Transfer *PayloadTransfer `protobuf:"bytes,30,opt,name=transfer,proto3,oneof"` } type TransactionInfo_Bond struct { // Bond transaction payload. Bond *PayloadBond `protobuf:"bytes,31,opt,name=bond,proto3,oneof"` } type TransactionInfo_Sortition struct { // Sortition transaction payload. Sortition *PayloadSortition `protobuf:"bytes,32,opt,name=sortition,proto3,oneof"` } type TransactionInfo_Unbond struct { // Unbond transaction payload. Unbond *PayloadUnbond `protobuf:"bytes,33,opt,name=unbond,proto3,oneof"` } type TransactionInfo_Withdraw struct { // Withdraw transaction payload. Withdraw *PayloadWithdraw `protobuf:"bytes,34,opt,name=withdraw,proto3,oneof"` } type TransactionInfo_BatchTransfer struct { // Batch Transfer transaction payload. BatchTransfer *PayloadBatchTransfer `protobuf:"bytes,35,opt,name=batch_transfer,json=batchTransfer,proto3,oneof"` } func (*TransactionInfo_Transfer) isTransactionInfo_Payload() {} func (*TransactionInfo_Bond) isTransactionInfo_Payload() {} func (*TransactionInfo_Sortition) isTransactionInfo_Payload() {} func (*TransactionInfo_Unbond) isTransactionInfo_Payload() {} func (*TransactionInfo_Withdraw) isTransactionInfo_Payload() {} func (*TransactionInfo_BatchTransfer) isTransactionInfo_Payload() {} // Request message for decoding a raw transaction. type DecodeRawTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The raw transaction data in hexadecimal format. RawTransaction string `protobuf:"bytes,1,opt,name=raw_transaction,json=rawTransaction,proto3" json:"raw_transaction,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *DecodeRawTransactionRequest) Reset() { *x = DecodeRawTransactionRequest{} mi := &file_transaction_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *DecodeRawTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*DecodeRawTransactionRequest) ProtoMessage() {} func (x *DecodeRawTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DecodeRawTransactionRequest.ProtoReflect.Descriptor instead. func (*DecodeRawTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{20} } func (x *DecodeRawTransactionRequest) GetRawTransaction() string { if x != nil { return x.RawTransaction } return "" } // Response message contains the decoded transaction. type DecodeRawTransactionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The decoded transaction information. Transaction *TransactionInfo `protobuf:"bytes,1,opt,name=transaction,proto3" json:"transaction,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *DecodeRawTransactionResponse) Reset() { *x = DecodeRawTransactionResponse{} mi := &file_transaction_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *DecodeRawTransactionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*DecodeRawTransactionResponse) ProtoMessage() {} func (x *DecodeRawTransactionResponse) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DecodeRawTransactionResponse.ProtoReflect.Descriptor instead. func (*DecodeRawTransactionResponse) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{21} } func (x *DecodeRawTransactionResponse) GetTransaction() *TransactionInfo { if x != nil { return x.Transaction } return nil } // Request message for checking a transaction. type CheckTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The raw transaction data to be checked. RawTransaction string `protobuf:"bytes,1,opt,name=raw_transaction,json=rawTransaction,proto3" json:"raw_transaction,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CheckTransactionRequest) Reset() { *x = CheckTransactionRequest{} mi := &file_transaction_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CheckTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*CheckTransactionRequest) ProtoMessage() {} func (x *CheckTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CheckTransactionRequest.ProtoReflect.Descriptor instead. func (*CheckTransactionRequest) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{22} } func (x *CheckTransactionRequest) GetRawTransaction() string { if x != nil { return x.RawTransaction } return "" } // Response message contains the result of the transaction check. type CheckTransactionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Indicates whether the transaction is valid. IsValid bool `protobuf:"varint,1,opt,name=is_valid,json=isValid,proto3" json:"is_valid,omitempty"` // An error message if the transaction is invalid. // Empty if the transaction is valid. ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CheckTransactionResponse) Reset() { *x = CheckTransactionResponse{} mi := &file_transaction_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CheckTransactionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*CheckTransactionResponse) ProtoMessage() {} func (x *CheckTransactionResponse) ProtoReflect() protoreflect.Message { mi := &file_transaction_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CheckTransactionResponse.ProtoReflect.Descriptor instead. func (*CheckTransactionResponse) Descriptor() ([]byte, []int) { return file_transaction_proto_rawDescGZIP(), []int{23} } func (x *CheckTransactionResponse) GetIsValid() bool { if x != nil { return x.IsValid } return false } func (x *CheckTransactionResponse) GetErrorMessage() string { if x != nil { return x.ErrorMessage } return "" } var File_transaction_proto protoreflect.FileDescriptor const file_transaction_proto_rawDesc = "" + "\n" + "\x11transaction.proto\x12\x06pactus\"c\n" + "\x15GetTransactionRequest\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12:\n" + "\tverbosity\x18\x02 \x01(\x0e2\x1c.pactus.TransactionVerbosityR\tverbosity\"\x95\x01\n" + "\x16GetTransactionResponse\x12!\n" + "\fblock_height\x18\x01 \x01(\rR\vblockHeight\x12\x1d\n" + "\n" + "block_time\x18\x02 \x01(\rR\tblockTime\x129\n" + "\vtransaction\x18\x03 \x01(\v2\x17.pactus.TransactionInfoR\vtransaction\"\x88\x01\n" + "\x13CalculateFeeRequest\x12\x16\n" + "\x06amount\x18\x01 \x01(\x03R\x06amount\x126\n" + "\fpayload_type\x18\x02 \x01(\x0e2\x13.pactus.PayloadTypeR\vpayloadType\x12!\n" + "\ffixed_amount\x18\x03 \x01(\bR\vfixedAmount\"@\n" + "\x14CalculateFeeResponse\x12\x16\n" + "\x06amount\x18\x01 \x01(\x03R\x06amount\x12\x10\n" + "\x03fee\x18\x02 \x01(\x03R\x03fee\"S\n" + "\x1bBroadcastTransactionRequest\x124\n" + "\x16signed_raw_transaction\x18\x01 \x01(\tR\x14signedRawTransaction\".\n" + "\x1cBroadcastTransactionResponse\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\"\xb1\x01\n" + " GetRawTransferTransactionRequest\x12\x1b\n" + "\tlock_time\x18\x01 \x01(\rR\blockTime\x12\x16\n" + "\x06sender\x18\x02 \x01(\tR\x06sender\x12\x1a\n" + "\breceiver\x18\x03 \x01(\tR\breceiver\x12\x16\n" + "\x06amount\x18\x04 \x01(\x03R\x06amount\x12\x10\n" + "\x03fee\x18\x05 \x01(\x03R\x03fee\x12\x12\n" + "\x04memo\x18\x06 \x01(\tR\x04memo\"\xc1\x02\n" + "\x1cGetRawBondTransactionRequest\x12\x1b\n" + "\tlock_time\x18\x01 \x01(\rR\blockTime\x12\x16\n" + "\x06sender\x18\x02 \x01(\tR\x06sender\x12\x1a\n" + "\breceiver\x18\x03 \x01(\tR\breceiver\x12\x14\n" + "\x05stake\x18\x04 \x01(\x03R\x05stake\x12\x1d\n" + "\n" + "public_key\x18\x05 \x01(\tR\tpublicKey\x12\x10\n" + "\x03fee\x18\x06 \x01(\x03R\x03fee\x12\x12\n" + "\x04memo\x18\a \x01(\tR\x04memo\x12%\n" + "\x0edelegate_owner\x18\b \x01(\tR\rdelegateOwner\x12%\n" + "\x0edelegate_share\x18\t \x01(\x03R\rdelegateShare\x12'\n" + "\x0fdelegate_expiry\x18\n" + " \x01(\rR\x0edelegateExpiry\"\xa5\x01\n" + "\x1eGetRawUnbondTransactionRequest\x12\x1b\n" + "\tlock_time\x18\x01 \x01(\rR\blockTime\x12+\n" + "\x11validator_address\x18\x02 \x01(\tR\x10validatorAddress\x12\x12\n" + "\x04memo\x18\x03 \x01(\tR\x04memo\x12%\n" + "\x0edelegate_owner\x18\x04 \x01(\tR\rdelegateOwner\"\xd3\x01\n" + " GetRawWithdrawTransactionRequest\x12\x1b\n" + "\tlock_time\x18\x01 \x01(\rR\blockTime\x12+\n" + "\x11validator_address\x18\x02 \x01(\tR\x10validatorAddress\x12'\n" + "\x0faccount_address\x18\x03 \x01(\tR\x0eaccountAddress\x12\x16\n" + "\x06amount\x18\x04 \x01(\x03R\x06amount\x12\x10\n" + "\x03fee\x18\x05 \x01(\x03R\x03fee\x12\x12\n" + "\x04memo\x18\x06 \x01(\tR\x04memo\"\xb5\x01\n" + "%GetRawBatchTransferTransactionRequest\x12\x1b\n" + "\tlock_time\x18\x01 \x01(\rR\blockTime\x12\x16\n" + "\x06sender\x18\x02 \x01(\tR\x06sender\x121\n" + "\n" + "recipients\x18\x03 \x03(\v2\x11.pactus.RecipientR\n" + "recipients\x12\x10\n" + "\x03fee\x18\x04 \x01(\x03R\x03fee\x12\x12\n" + "\x04memo\x18\x05 \x01(\tR\x04memo\"T\n" + "\x19GetRawTransactionResponse\x12'\n" + "\x0fraw_transaction\x18\x01 \x01(\tR\x0erawTransaction\x12\x0e\n" + "\x02id\x18\x02 \x01(\tR\x02id\"]\n" + "\x0fPayloadTransfer\x12\x16\n" + "\x06sender\x18\x01 \x01(\tR\x06sender\x12\x1a\n" + "\breceiver\x18\x02 \x01(\tR\breceiver\x12\x16\n" + "\x06amount\x18\x03 \x01(\x03R\x06amount\"\x90\x02\n" + "\vPayloadBond\x12\x16\n" + "\x06sender\x18\x01 \x01(\tR\x06sender\x12\x1a\n" + "\breceiver\x18\x02 \x01(\tR\breceiver\x12\x14\n" + "\x05stake\x18\x03 \x01(\x03R\x05stake\x12\x1d\n" + "\n" + "public_key\x18\x04 \x01(\tR\tpublicKey\x12!\n" + "\fis_delegated\x18\x05 \x01(\bR\visDelegated\x12%\n" + "\x0edelegate_owner\x18\x06 \x01(\tR\rdelegateOwner\x12%\n" + "\x0edelegate_share\x18\a \x01(\x03R\rdelegateShare\x12'\n" + "\x0fdelegate_expiry\x18\b \x01(\rR\x0edelegateExpiry\"B\n" + "\x10PayloadSortition\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\x12\x14\n" + "\x05proof\x18\x02 \x01(\tR\x05proof\"T\n" + "\rPayloadUnbond\x12\x1c\n" + "\tvalidator\x18\x01 \x01(\tR\tvalidator\x12%\n" + "\x0edelegate_owner\x18\x02 \x01(\tR\rdelegateOwner\"\x7f\n" + "\x0fPayloadWithdraw\x12+\n" + "\x11validator_address\x18\x01 \x01(\tR\x10validatorAddress\x12'\n" + "\x0faccount_address\x18\x02 \x01(\tR\x0eaccountAddress\x12\x16\n" + "\x06amount\x18\x03 \x01(\x03R\x06amount\"a\n" + "\x14PayloadBatchTransfer\x12\x16\n" + "\x06sender\x18\x01 \x01(\tR\x06sender\x121\n" + "\n" + "recipients\x18\x02 \x03(\v2\x11.pactus.RecipientR\n" + "recipients\"?\n" + "\tRecipient\x12\x1a\n" + "\breceiver\x18\x01 \x01(\tR\breceiver\x12\x16\n" + "\x06amount\x18\x02 \x01(\x03R\x06amount\"\xda\x05\n" + "\x0fTransactionInfo\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + "\x04data\x18\x02 \x01(\tR\x04data\x12\x18\n" + "\aversion\x18\x03 \x01(\x05R\aversion\x12\x1b\n" + "\tlock_time\x18\x04 \x01(\rR\blockTime\x12\x14\n" + "\x05value\x18\x05 \x01(\x03R\x05value\x12\x10\n" + "\x03fee\x18\x06 \x01(\x03R\x03fee\x126\n" + "\fpayload_type\x18\a \x01(\x0e2\x13.pactus.PayloadTypeR\vpayloadType\x125\n" + "\btransfer\x18\x1e \x01(\v2\x17.pactus.PayloadTransferH\x00R\btransfer\x12)\n" + "\x04bond\x18\x1f \x01(\v2\x13.pactus.PayloadBondH\x00R\x04bond\x128\n" + "\tsortition\x18 \x01(\v2\x18.pactus.PayloadSortitionH\x00R\tsortition\x12/\n" + "\x06unbond\x18! \x01(\v2\x15.pactus.PayloadUnbondH\x00R\x06unbond\x125\n" + "\bwithdraw\x18\" \x01(\v2\x17.pactus.PayloadWithdrawH\x00R\bwithdraw\x12E\n" + "\x0ebatch_transfer\x18# \x01(\v2\x1c.pactus.PayloadBatchTransferH\x00R\rbatchTransfer\x12\x12\n" + "\x04memo\x18\b \x01(\tR\x04memo\x12\x1d\n" + "\n" + "public_key\x18\t \x01(\tR\tpublicKey\x12\x1c\n" + "\tsignature\x18\n" + " \x01(\tR\tsignature\x12!\n" + "\fblock_height\x18\v \x01(\rR\vblockHeight\x12\x1c\n" + "\tconfirmed\x18\f \x01(\bR\tconfirmed\x12$\n" + "\rconfirmations\x18\r \x01(\x05R\rconfirmationsB\t\n" + "\apayload\"F\n" + "\x1bDecodeRawTransactionRequest\x12'\n" + "\x0fraw_transaction\x18\x01 \x01(\tR\x0erawTransaction\"Y\n" + "\x1cDecodeRawTransactionResponse\x129\n" + "\vtransaction\x18\x01 \x01(\v2\x17.pactus.TransactionInfoR\vtransaction\"B\n" + "\x17CheckTransactionRequest\x12'\n" + "\x0fraw_transaction\x18\x01 \x01(\tR\x0erawTransaction\"Z\n" + "\x18CheckTransactionResponse\x12\x19\n" + "\bis_valid\x18\x01 \x01(\bR\aisValid\x12#\n" + "\rerror_message\x18\x02 \x01(\tR\ferrorMessage*\xce\x01\n" + "\vPayloadType\x12\x1c\n" + "\x18PAYLOAD_TYPE_UNSPECIFIED\x10\x00\x12\x19\n" + "\x15PAYLOAD_TYPE_TRANSFER\x10\x01\x12\x15\n" + "\x11PAYLOAD_TYPE_BOND\x10\x02\x12\x1a\n" + "\x16PAYLOAD_TYPE_SORTITION\x10\x03\x12\x17\n" + "\x13PAYLOAD_TYPE_UNBOND\x10\x04\x12\x19\n" + "\x15PAYLOAD_TYPE_WITHDRAW\x10\x05\x12\x1f\n" + "\x1bPAYLOAD_TYPE_BATCH_TRANSFER\x10\x06*V\n" + "\x14TransactionVerbosity\x12\x1e\n" + "\x1aTRANSACTION_VERBOSITY_DATA\x10\x00\x12\x1e\n" + "\x1aTRANSACTION_VERBOSITY_INFO\x10\x012\xd6\a\n" + "\vTransaction\x12O\n" + "\x0eGetTransaction\x12\x1d.pactus.GetTransactionRequest\x1a\x1e.pactus.GetTransactionResponse\x12I\n" + "\fCalculateFee\x12\x1b.pactus.CalculateFeeRequest\x1a\x1c.pactus.CalculateFeeResponse\x12a\n" + "\x14BroadcastTransaction\x12#.pactus.BroadcastTransactionRequest\x1a$.pactus.BroadcastTransactionResponse\x12h\n" + "\x19GetRawTransferTransaction\x12(.pactus.GetRawTransferTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12`\n" + "\x15GetRawBondTransaction\x12$.pactus.GetRawBondTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12d\n" + "\x17GetRawUnbondTransaction\x12&.pactus.GetRawUnbondTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12h\n" + "\x19GetRawWithdrawTransaction\x12(.pactus.GetRawWithdrawTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12r\n" + "\x1eGetRawBatchTransferTransaction\x12-.pactus.GetRawBatchTransferTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12a\n" + "\x14DecodeRawTransaction\x12#.pactus.DecodeRawTransactionRequest\x1a$.pactus.DecodeRawTransactionResponse\x12U\n" + "\x10CheckTransaction\x12\x1f.pactus.CheckTransactionRequest\x1a .pactus.CheckTransactionResponseB:\n" + "\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3" var ( file_transaction_proto_rawDescOnce sync.Once file_transaction_proto_rawDescData []byte ) func file_transaction_proto_rawDescGZIP() []byte { file_transaction_proto_rawDescOnce.Do(func() { file_transaction_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_transaction_proto_rawDesc), len(file_transaction_proto_rawDesc))) }) return file_transaction_proto_rawDescData } var file_transaction_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_transaction_proto_msgTypes = make([]protoimpl.MessageInfo, 24) var file_transaction_proto_goTypes = []any{ (PayloadType)(0), // 0: pactus.PayloadType (TransactionVerbosity)(0), // 1: pactus.TransactionVerbosity (*GetTransactionRequest)(nil), // 2: pactus.GetTransactionRequest (*GetTransactionResponse)(nil), // 3: pactus.GetTransactionResponse (*CalculateFeeRequest)(nil), // 4: pactus.CalculateFeeRequest (*CalculateFeeResponse)(nil), // 5: pactus.CalculateFeeResponse (*BroadcastTransactionRequest)(nil), // 6: pactus.BroadcastTransactionRequest (*BroadcastTransactionResponse)(nil), // 7: pactus.BroadcastTransactionResponse (*GetRawTransferTransactionRequest)(nil), // 8: pactus.GetRawTransferTransactionRequest (*GetRawBondTransactionRequest)(nil), // 9: pactus.GetRawBondTransactionRequest (*GetRawUnbondTransactionRequest)(nil), // 10: pactus.GetRawUnbondTransactionRequest (*GetRawWithdrawTransactionRequest)(nil), // 11: pactus.GetRawWithdrawTransactionRequest (*GetRawBatchTransferTransactionRequest)(nil), // 12: pactus.GetRawBatchTransferTransactionRequest (*GetRawTransactionResponse)(nil), // 13: pactus.GetRawTransactionResponse (*PayloadTransfer)(nil), // 14: pactus.PayloadTransfer (*PayloadBond)(nil), // 15: pactus.PayloadBond (*PayloadSortition)(nil), // 16: pactus.PayloadSortition (*PayloadUnbond)(nil), // 17: pactus.PayloadUnbond (*PayloadWithdraw)(nil), // 18: pactus.PayloadWithdraw (*PayloadBatchTransfer)(nil), // 19: pactus.PayloadBatchTransfer (*Recipient)(nil), // 20: pactus.Recipient (*TransactionInfo)(nil), // 21: pactus.TransactionInfo (*DecodeRawTransactionRequest)(nil), // 22: pactus.DecodeRawTransactionRequest (*DecodeRawTransactionResponse)(nil), // 23: pactus.DecodeRawTransactionResponse (*CheckTransactionRequest)(nil), // 24: pactus.CheckTransactionRequest (*CheckTransactionResponse)(nil), // 25: pactus.CheckTransactionResponse } var file_transaction_proto_depIdxs = []int32{ 1, // 0: pactus.GetTransactionRequest.verbosity:type_name -> pactus.TransactionVerbosity 21, // 1: pactus.GetTransactionResponse.transaction:type_name -> pactus.TransactionInfo 0, // 2: pactus.CalculateFeeRequest.payload_type:type_name -> pactus.PayloadType 20, // 3: pactus.GetRawBatchTransferTransactionRequest.recipients:type_name -> pactus.Recipient 20, // 4: pactus.PayloadBatchTransfer.recipients:type_name -> pactus.Recipient 0, // 5: pactus.TransactionInfo.payload_type:type_name -> pactus.PayloadType 14, // 6: pactus.TransactionInfo.transfer:type_name -> pactus.PayloadTransfer 15, // 7: pactus.TransactionInfo.bond:type_name -> pactus.PayloadBond 16, // 8: pactus.TransactionInfo.sortition:type_name -> pactus.PayloadSortition 17, // 9: pactus.TransactionInfo.unbond:type_name -> pactus.PayloadUnbond 18, // 10: pactus.TransactionInfo.withdraw:type_name -> pactus.PayloadWithdraw 19, // 11: pactus.TransactionInfo.batch_transfer:type_name -> pactus.PayloadBatchTransfer 21, // 12: pactus.DecodeRawTransactionResponse.transaction:type_name -> pactus.TransactionInfo 2, // 13: pactus.Transaction.GetTransaction:input_type -> pactus.GetTransactionRequest 4, // 14: pactus.Transaction.CalculateFee:input_type -> pactus.CalculateFeeRequest 6, // 15: pactus.Transaction.BroadcastTransaction:input_type -> pactus.BroadcastTransactionRequest 8, // 16: pactus.Transaction.GetRawTransferTransaction:input_type -> pactus.GetRawTransferTransactionRequest 9, // 17: pactus.Transaction.GetRawBondTransaction:input_type -> pactus.GetRawBondTransactionRequest 10, // 18: pactus.Transaction.GetRawUnbondTransaction:input_type -> pactus.GetRawUnbondTransactionRequest 11, // 19: pactus.Transaction.GetRawWithdrawTransaction:input_type -> pactus.GetRawWithdrawTransactionRequest 12, // 20: pactus.Transaction.GetRawBatchTransferTransaction:input_type -> pactus.GetRawBatchTransferTransactionRequest 22, // 21: pactus.Transaction.DecodeRawTransaction:input_type -> pactus.DecodeRawTransactionRequest 24, // 22: pactus.Transaction.CheckTransaction:input_type -> pactus.CheckTransactionRequest 3, // 23: pactus.Transaction.GetTransaction:output_type -> pactus.GetTransactionResponse 5, // 24: pactus.Transaction.CalculateFee:output_type -> pactus.CalculateFeeResponse 7, // 25: pactus.Transaction.BroadcastTransaction:output_type -> pactus.BroadcastTransactionResponse 13, // 26: pactus.Transaction.GetRawTransferTransaction:output_type -> pactus.GetRawTransactionResponse 13, // 27: pactus.Transaction.GetRawBondTransaction:output_type -> pactus.GetRawTransactionResponse 13, // 28: pactus.Transaction.GetRawUnbondTransaction:output_type -> pactus.GetRawTransactionResponse 13, // 29: pactus.Transaction.GetRawWithdrawTransaction:output_type -> pactus.GetRawTransactionResponse 13, // 30: pactus.Transaction.GetRawBatchTransferTransaction:output_type -> pactus.GetRawTransactionResponse 23, // 31: pactus.Transaction.DecodeRawTransaction:output_type -> pactus.DecodeRawTransactionResponse 25, // 32: pactus.Transaction.CheckTransaction:output_type -> pactus.CheckTransactionResponse 23, // [23:33] is the sub-list for method output_type 13, // [13:23] is the sub-list for method input_type 13, // [13:13] is the sub-list for extension type_name 13, // [13:13] is the sub-list for extension extendee 0, // [0:13] is the sub-list for field type_name } func init() { file_transaction_proto_init() } func file_transaction_proto_init() { if File_transaction_proto != nil { return } file_transaction_proto_msgTypes[19].OneofWrappers = []any{ (*TransactionInfo_Transfer)(nil), (*TransactionInfo_Bond)(nil), (*TransactionInfo_Sortition)(nil), (*TransactionInfo_Unbond)(nil), (*TransactionInfo_Withdraw)(nil), (*TransactionInfo_BatchTransfer)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_transaction_proto_rawDesc), len(file_transaction_proto_rawDesc)), NumEnums: 2, NumMessages: 24, NumExtensions: 0, NumServices: 1, }, GoTypes: file_transaction_proto_goTypes, DependencyIndexes: file_transaction_proto_depIdxs, EnumInfos: file_transaction_proto_enumTypes, MessageInfos: file_transaction_proto_msgTypes, }.Build() File_transaction_proto = out.File file_transaction_proto_goTypes = nil file_transaction_proto_depIdxs = nil } ================================================ FILE: www/grpc/gen/go/transaction.pb.gw.go ================================================ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: transaction.proto /* Package pactus is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package pactus import ( "context" "errors" "io" "net/http" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors var ( _ codes.Code _ io.Reader _ status.Status _ = errors.New _ = runtime.String _ = utilities.NewDoubleArray _ = metadata.Join ) var filter_Transaction_GetTransaction_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Transaction_GetTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTransactionRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Transaction_GetTransaction_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_GetTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTransactionRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Transaction_GetTransaction_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_CalculateFee_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq CalculateFeeRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.CalculateFee(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_CalculateFee_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq CalculateFeeRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CalculateFee(ctx, &protoReq) return msg, metadata, err } func request_Transaction_BroadcastTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq BroadcastTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.BroadcastTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_BroadcastTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq BroadcastTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.BroadcastTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_GetRawTransferTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawTransferTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetRawTransferTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_GetRawTransferTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawTransferTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetRawTransferTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_GetRawBondTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawBondTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetRawBondTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_GetRawBondTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawBondTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetRawBondTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_GetRawUnbondTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawUnbondTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetRawUnbondTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_GetRawUnbondTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawUnbondTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetRawUnbondTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_GetRawWithdrawTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawWithdrawTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetRawWithdrawTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_GetRawWithdrawTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawWithdrawTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetRawWithdrawTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_GetRawBatchTransferTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawBatchTransferTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetRawBatchTransferTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_GetRawBatchTransferTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetRawBatchTransferTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetRawBatchTransferTransaction(ctx, &protoReq) return msg, metadata, err } func request_Transaction_DecodeRawTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq DecodeRawTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.DecodeRawTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Transaction_DecodeRawTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq DecodeRawTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.DecodeRawTransaction(ctx, &protoReq) return msg, metadata, err } // RegisterTransactionHandlerServer registers the http handlers for service Transaction to "mux". // UnaryRPC :call TransactionServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterTransactionHandlerFromEndpoint instead. // GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterTransactionHandlerServer(ctx context.Context, mux *runtime.ServeMux, server TransactionServer) error { mux.Handle(http.MethodGet, pattern_Transaction_GetTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/GetTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_GetTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_CalculateFee_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/CalculateFee", runtime.WithHTTPPathPattern("/pactus/transaction/calculate_fee")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_CalculateFee_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_CalculateFee_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_BroadcastTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/BroadcastTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/broadcast_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_BroadcastTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_BroadcastTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawTransferTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/GetRawTransferTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_transfer_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_GetRawTransferTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawTransferTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawBondTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/GetRawBondTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_bond_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_GetRawBondTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawBondTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawUnbondTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/GetRawUnbondTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_unbond_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_GetRawUnbondTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawUnbondTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawWithdrawTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/GetRawWithdrawTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_withdraw_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_GetRawWithdrawTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawWithdrawTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawBatchTransferTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/GetRawBatchTransferTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_batch_transfer_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_GetRawBatchTransferTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawBatchTransferTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_DecodeRawTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Transaction/DecodeRawTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/decode_raw_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Transaction_DecodeRawTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_DecodeRawTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterTransactionHandlerFromEndpoint is same as RegisterTransactionHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterTransactionHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterTransactionHandler(ctx, mux, conn) } // RegisterTransactionHandler registers the http handlers for service Transaction to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterTransactionHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterTransactionHandlerClient(ctx, mux, NewTransactionClient(conn)) } // RegisterTransactionHandlerClient registers the http handlers for service Transaction // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "TransactionClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "TransactionClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "TransactionClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterTransactionHandlerClient(ctx context.Context, mux *runtime.ServeMux, client TransactionClient) error { mux.Handle(http.MethodGet, pattern_Transaction_GetTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/GetTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_GetTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_CalculateFee_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/CalculateFee", runtime.WithHTTPPathPattern("/pactus/transaction/calculate_fee")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_CalculateFee_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_CalculateFee_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_BroadcastTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/BroadcastTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/broadcast_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_BroadcastTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_BroadcastTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawTransferTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/GetRawTransferTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_transfer_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_GetRawTransferTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawTransferTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawBondTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/GetRawBondTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_bond_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_GetRawBondTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawBondTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawUnbondTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/GetRawUnbondTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_unbond_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_GetRawUnbondTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawUnbondTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawWithdrawTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/GetRawWithdrawTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_withdraw_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_GetRawWithdrawTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawWithdrawTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_GetRawBatchTransferTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/GetRawBatchTransferTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/get_raw_batch_transfer_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_GetRawBatchTransferTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_GetRawBatchTransferTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Transaction_DecodeRawTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Transaction/DecodeRawTransaction", runtime.WithHTTPPathPattern("/pactus/transaction/decode_raw_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Transaction_DecodeRawTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Transaction_DecodeRawTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_Transaction_GetTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "get_transaction"}, "")) pattern_Transaction_CalculateFee_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "calculate_fee"}, "")) pattern_Transaction_BroadcastTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "broadcast_transaction"}, "")) pattern_Transaction_GetRawTransferTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "get_raw_transfer_transaction"}, "")) pattern_Transaction_GetRawBondTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "get_raw_bond_transaction"}, "")) pattern_Transaction_GetRawUnbondTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "get_raw_unbond_transaction"}, "")) pattern_Transaction_GetRawWithdrawTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "get_raw_withdraw_transaction"}, "")) pattern_Transaction_GetRawBatchTransferTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "get_raw_batch_transfer_transaction"}, "")) pattern_Transaction_DecodeRawTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "transaction", "decode_raw_transaction"}, "")) ) var ( forward_Transaction_GetTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_CalculateFee_0 = runtime.ForwardResponseMessage forward_Transaction_BroadcastTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_GetRawTransferTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_GetRawBondTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_GetRawUnbondTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_GetRawWithdrawTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_GetRawBatchTransferTransaction_0 = runtime.ForwardResponseMessage forward_Transaction_DecodeRawTransaction_0 = runtime.ForwardResponseMessage ) ================================================ FILE: www/grpc/gen/go/transaction_grpc.pb.go ================================================ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.6.0 // - protoc (unknown) // source: transaction.proto package pactus import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( Transaction_GetTransaction_FullMethodName = "/pactus.Transaction/GetTransaction" Transaction_CalculateFee_FullMethodName = "/pactus.Transaction/CalculateFee" Transaction_BroadcastTransaction_FullMethodName = "/pactus.Transaction/BroadcastTransaction" Transaction_GetRawTransferTransaction_FullMethodName = "/pactus.Transaction/GetRawTransferTransaction" Transaction_GetRawBondTransaction_FullMethodName = "/pactus.Transaction/GetRawBondTransaction" Transaction_GetRawUnbondTransaction_FullMethodName = "/pactus.Transaction/GetRawUnbondTransaction" Transaction_GetRawWithdrawTransaction_FullMethodName = "/pactus.Transaction/GetRawWithdrawTransaction" Transaction_GetRawBatchTransferTransaction_FullMethodName = "/pactus.Transaction/GetRawBatchTransferTransaction" Transaction_DecodeRawTransaction_FullMethodName = "/pactus.Transaction/DecodeRawTransaction" Transaction_CheckTransaction_FullMethodName = "/pactus.Transaction/CheckTransaction" ) // TransactionClient is the client API for Transaction service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. // // Transaction service defines various RPC methods for interacting with transactions. type TransactionClient interface { // GetTransaction retrieves transaction details based on the provided request parameters. GetTransaction(ctx context.Context, in *GetTransactionRequest, opts ...grpc.CallOption) (*GetTransactionResponse, error) // CalculateFee calculates the transaction fee based on the specified amount and payload type. CalculateFee(ctx context.Context, in *CalculateFeeRequest, opts ...grpc.CallOption) (*CalculateFeeResponse, error) // BroadcastTransaction broadcasts a signed transaction to the network. BroadcastTransaction(ctx context.Context, in *BroadcastTransactionRequest, opts ...grpc.CallOption) (*BroadcastTransactionResponse, error) // GetRawTransferTransaction retrieves raw details of a transfer transaction. GetRawTransferTransaction(ctx context.Context, in *GetRawTransferTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) // GetRawBondTransaction retrieves raw details of a bond transaction. GetRawBondTransaction(ctx context.Context, in *GetRawBondTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) // GetRawUnbondTransaction retrieves raw details of an unbond transaction. GetRawUnbondTransaction(ctx context.Context, in *GetRawUnbondTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) // GetRawWithdrawTransaction retrieves raw details of a withdraw transaction. GetRawWithdrawTransaction(ctx context.Context, in *GetRawWithdrawTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) // GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction. GetRawBatchTransferTransaction(ctx context.Context, in *GetRawBatchTransferTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) // DecodeRawTransaction accepts raw transaction and returns decoded transaction. DecodeRawTransaction(ctx context.Context, in *DecodeRawTransactionRequest, opts ...grpc.CallOption) (*DecodeRawTransactionResponse, error) // CheckTransaction checks if the transaction is valid and can be included in the blockchain. CheckTransaction(ctx context.Context, in *CheckTransactionRequest, opts ...grpc.CallOption) (*CheckTransactionResponse, error) } type transactionClient struct { cc grpc.ClientConnInterface } func NewTransactionClient(cc grpc.ClientConnInterface) TransactionClient { return &transactionClient{cc} } func (c *transactionClient) GetTransaction(ctx context.Context, in *GetTransactionRequest, opts ...grpc.CallOption) (*GetTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetTransactionResponse) err := c.cc.Invoke(ctx, Transaction_GetTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) CalculateFee(ctx context.Context, in *CalculateFeeRequest, opts ...grpc.CallOption) (*CalculateFeeResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(CalculateFeeResponse) err := c.cc.Invoke(ctx, Transaction_CalculateFee_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) BroadcastTransaction(ctx context.Context, in *BroadcastTransactionRequest, opts ...grpc.CallOption) (*BroadcastTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(BroadcastTransactionResponse) err := c.cc.Invoke(ctx, Transaction_BroadcastTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) GetRawTransferTransaction(ctx context.Context, in *GetRawTransferTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetRawTransactionResponse) err := c.cc.Invoke(ctx, Transaction_GetRawTransferTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) GetRawBondTransaction(ctx context.Context, in *GetRawBondTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetRawTransactionResponse) err := c.cc.Invoke(ctx, Transaction_GetRawBondTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) GetRawUnbondTransaction(ctx context.Context, in *GetRawUnbondTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetRawTransactionResponse) err := c.cc.Invoke(ctx, Transaction_GetRawUnbondTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) GetRawWithdrawTransaction(ctx context.Context, in *GetRawWithdrawTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetRawTransactionResponse) err := c.cc.Invoke(ctx, Transaction_GetRawWithdrawTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) GetRawBatchTransferTransaction(ctx context.Context, in *GetRawBatchTransferTransactionRequest, opts ...grpc.CallOption) (*GetRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetRawTransactionResponse) err := c.cc.Invoke(ctx, Transaction_GetRawBatchTransferTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) DecodeRawTransaction(ctx context.Context, in *DecodeRawTransactionRequest, opts ...grpc.CallOption) (*DecodeRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(DecodeRawTransactionResponse) err := c.cc.Invoke(ctx, Transaction_DecodeRawTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *transactionClient) CheckTransaction(ctx context.Context, in *CheckTransactionRequest, opts ...grpc.CallOption) (*CheckTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(CheckTransactionResponse) err := c.cc.Invoke(ctx, Transaction_CheckTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // TransactionServer is the server API for Transaction service. // All implementations should embed UnimplementedTransactionServer // for forward compatibility. // // Transaction service defines various RPC methods for interacting with transactions. type TransactionServer interface { // GetTransaction retrieves transaction details based on the provided request parameters. GetTransaction(context.Context, *GetTransactionRequest) (*GetTransactionResponse, error) // CalculateFee calculates the transaction fee based on the specified amount and payload type. CalculateFee(context.Context, *CalculateFeeRequest) (*CalculateFeeResponse, error) // BroadcastTransaction broadcasts a signed transaction to the network. BroadcastTransaction(context.Context, *BroadcastTransactionRequest) (*BroadcastTransactionResponse, error) // GetRawTransferTransaction retrieves raw details of a transfer transaction. GetRawTransferTransaction(context.Context, *GetRawTransferTransactionRequest) (*GetRawTransactionResponse, error) // GetRawBondTransaction retrieves raw details of a bond transaction. GetRawBondTransaction(context.Context, *GetRawBondTransactionRequest) (*GetRawTransactionResponse, error) // GetRawUnbondTransaction retrieves raw details of an unbond transaction. GetRawUnbondTransaction(context.Context, *GetRawUnbondTransactionRequest) (*GetRawTransactionResponse, error) // GetRawWithdrawTransaction retrieves raw details of a withdraw transaction. GetRawWithdrawTransaction(context.Context, *GetRawWithdrawTransactionRequest) (*GetRawTransactionResponse, error) // GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction. GetRawBatchTransferTransaction(context.Context, *GetRawBatchTransferTransactionRequest) (*GetRawTransactionResponse, error) // DecodeRawTransaction accepts raw transaction and returns decoded transaction. DecodeRawTransaction(context.Context, *DecodeRawTransactionRequest) (*DecodeRawTransactionResponse, error) // CheckTransaction checks if the transaction is valid and can be included in the blockchain. CheckTransaction(context.Context, *CheckTransactionRequest) (*CheckTransactionResponse, error) } // UnimplementedTransactionServer should be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedTransactionServer struct{} func (UnimplementedTransactionServer) GetTransaction(context.Context, *GetTransactionRequest) (*GetTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetTransaction not implemented") } func (UnimplementedTransactionServer) CalculateFee(context.Context, *CalculateFeeRequest) (*CalculateFeeResponse, error) { return nil, status.Error(codes.Unimplemented, "method CalculateFee not implemented") } func (UnimplementedTransactionServer) BroadcastTransaction(context.Context, *BroadcastTransactionRequest) (*BroadcastTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method BroadcastTransaction not implemented") } func (UnimplementedTransactionServer) GetRawTransferTransaction(context.Context, *GetRawTransferTransactionRequest) (*GetRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetRawTransferTransaction not implemented") } func (UnimplementedTransactionServer) GetRawBondTransaction(context.Context, *GetRawBondTransactionRequest) (*GetRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetRawBondTransaction not implemented") } func (UnimplementedTransactionServer) GetRawUnbondTransaction(context.Context, *GetRawUnbondTransactionRequest) (*GetRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetRawUnbondTransaction not implemented") } func (UnimplementedTransactionServer) GetRawWithdrawTransaction(context.Context, *GetRawWithdrawTransactionRequest) (*GetRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetRawWithdrawTransaction not implemented") } func (UnimplementedTransactionServer) GetRawBatchTransferTransaction(context.Context, *GetRawBatchTransferTransactionRequest) (*GetRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetRawBatchTransferTransaction not implemented") } func (UnimplementedTransactionServer) DecodeRawTransaction(context.Context, *DecodeRawTransactionRequest) (*DecodeRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method DecodeRawTransaction not implemented") } func (UnimplementedTransactionServer) CheckTransaction(context.Context, *CheckTransactionRequest) (*CheckTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method CheckTransaction not implemented") } func (UnimplementedTransactionServer) testEmbeddedByValue() {} // UnsafeTransactionServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to TransactionServer will // result in compilation errors. type UnsafeTransactionServer interface { mustEmbedUnimplementedTransactionServer() } func RegisterTransactionServer(s grpc.ServiceRegistrar, srv TransactionServer) { // If the following call panics, it indicates UnimplementedTransactionServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&Transaction_ServiceDesc, srv) } func _Transaction_GetTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).GetTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_GetTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).GetTransaction(ctx, req.(*GetTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_CalculateFee_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CalculateFeeRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).CalculateFee(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_CalculateFee_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).CalculateFee(ctx, req.(*CalculateFeeRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_BroadcastTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(BroadcastTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).BroadcastTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_BroadcastTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).BroadcastTransaction(ctx, req.(*BroadcastTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_GetRawTransferTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRawTransferTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).GetRawTransferTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_GetRawTransferTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).GetRawTransferTransaction(ctx, req.(*GetRawTransferTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_GetRawBondTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRawBondTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).GetRawBondTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_GetRawBondTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).GetRawBondTransaction(ctx, req.(*GetRawBondTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_GetRawUnbondTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRawUnbondTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).GetRawUnbondTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_GetRawUnbondTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).GetRawUnbondTransaction(ctx, req.(*GetRawUnbondTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_GetRawWithdrawTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRawWithdrawTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).GetRawWithdrawTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_GetRawWithdrawTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).GetRawWithdrawTransaction(ctx, req.(*GetRawWithdrawTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_GetRawBatchTransferTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRawBatchTransferTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).GetRawBatchTransferTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_GetRawBatchTransferTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).GetRawBatchTransferTransaction(ctx, req.(*GetRawBatchTransferTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_DecodeRawTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DecodeRawTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).DecodeRawTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_DecodeRawTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).DecodeRawTransaction(ctx, req.(*DecodeRawTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Transaction_CheckTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CheckTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TransactionServer).CheckTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Transaction_CheckTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TransactionServer).CheckTransaction(ctx, req.(*CheckTransactionRequest)) } return interceptor(ctx, in, info, handler) } // Transaction_ServiceDesc is the grpc.ServiceDesc for Transaction service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var Transaction_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Transaction", HandlerType: (*TransactionServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetTransaction", Handler: _Transaction_GetTransaction_Handler, }, { MethodName: "CalculateFee", Handler: _Transaction_CalculateFee_Handler, }, { MethodName: "BroadcastTransaction", Handler: _Transaction_BroadcastTransaction_Handler, }, { MethodName: "GetRawTransferTransaction", Handler: _Transaction_GetRawTransferTransaction_Handler, }, { MethodName: "GetRawBondTransaction", Handler: _Transaction_GetRawBondTransaction_Handler, }, { MethodName: "GetRawUnbondTransaction", Handler: _Transaction_GetRawUnbondTransaction_Handler, }, { MethodName: "GetRawWithdrawTransaction", Handler: _Transaction_GetRawWithdrawTransaction_Handler, }, { MethodName: "GetRawBatchTransferTransaction", Handler: _Transaction_GetRawBatchTransferTransaction_Handler, }, { MethodName: "DecodeRawTransaction", Handler: _Transaction_DecodeRawTransaction_Handler, }, { MethodName: "CheckTransaction", Handler: _Transaction_CheckTransaction_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "transaction.proto", } ================================================ FILE: www/grpc/gen/go/transaction_jgw.pb.go ================================================ // Code generated by protoc-gen-jrpc-gateway. DO NOT EDIT. // source: transaction.proto /* Package pactus is a reverse proxy. It translates gRPC into JSON-RPC 2.0 */ package pactus import ( "context" "encoding/json" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" ) type TransactionJsonRPC struct { client TransactionClient } type paramsAndHeadersTransaction struct { Headers metadata.MD `json:"headers,omitempty"` Params json.RawMessage `json:"params"` } // RegisterTransactionJsonRPC register the grpc client Transaction for json-rpc. // The handlers forward requests to the grpc endpoint over "conn". func RegisterTransactionJsonRPC(conn *grpc.ClientConn) *TransactionJsonRPC { return &TransactionJsonRPC{ client: NewTransactionClient(conn), } } func (s *TransactionJsonRPC) Methods() map[string]func(ctx context.Context, message json.RawMessage) (any, error) { return map[string]func(ctx context.Context, params json.RawMessage) (any, error){ "pactus.transaction.get_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.calculate_fee": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(CalculateFeeRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.CalculateFee(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.broadcast_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(BroadcastTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.BroadcastTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.get_raw_transfer_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetRawTransferTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetRawTransferTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.get_raw_bond_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetRawBondTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetRawBondTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.get_raw_unbond_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetRawUnbondTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetRawUnbondTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.get_raw_withdraw_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetRawWithdrawTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetRawWithdrawTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.get_raw_batch_transfer_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetRawBatchTransferTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetRawBatchTransferTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.decode_raw_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(DecodeRawTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.DecodeRawTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.transaction.check_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(CheckTransactionRequest) var jrpcData paramsAndHeadersTransaction if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.CheckTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, } } ================================================ FILE: www/grpc/gen/go/utils.cobra.pb.go ================================================ // Code generated by protoc-gen-cobra. DO NOT EDIT. package pactus import ( client "github.com/NathanBaulch/protoc-gen-cobra/client" flag "github.com/NathanBaulch/protoc-gen-cobra/flag" iocodec "github.com/NathanBaulch/protoc-gen-cobra/iocodec" cobra "github.com/spf13/cobra" grpc "google.golang.org/grpc" proto "google.golang.org/protobuf/proto" ) func UtilsClientCommand(options ...client.Option) *cobra.Command { cfg := client.NewConfig(options...) cmd := &cobra.Command{ Use: cfg.CommandNamer("Utils"), Short: "Utils service client", Long: "Utils service defines RPC methods for utility functions such as message\n signing, verification, and other cryptographic operations.", } cfg.BindFlags(cmd.PersistentFlags()) cmd.AddCommand( _UtilsSignMessageWithPrivateKeyCommand(cfg), _UtilsVerifyMessageCommand(cfg), _UtilsPublicKeyAggregationCommand(cfg), _UtilsSignatureAggregationCommand(cfg), ) return cmd } func _UtilsSignMessageWithPrivateKeyCommand(cfg *client.Config) *cobra.Command { req := &SignMessageWithPrivateKeyRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("SignMessageWithPrivateKey"), Short: "SignMessageWithPrivateKey RPC client", Long: "SignMessageWithPrivateKey signs a message with the provided private key.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils", "SignMessageWithPrivateKey"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewUtilsClient(cc) v := &SignMessageWithPrivateKeyRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.SignMessageWithPrivateKey(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.PrivateKey, cfg.FlagNamer("PrivateKey"), "", "The private key to sign the message.") cmd.PersistentFlags().StringVar(&req.Message, cfg.FlagNamer("Message"), "", "The message content to be signed.") return cmd } func _UtilsVerifyMessageCommand(cfg *client.Config) *cobra.Command { req := &VerifyMessageRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("VerifyMessage"), Short: "VerifyMessage RPC client", Long: "VerifyMessage verifies a signature against the public key and message.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils", "VerifyMessage"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewUtilsClient(cc) v := &VerifyMessageRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.VerifyMessage(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.Message, cfg.FlagNamer("Message"), "", "The original message content that was signed.") cmd.PersistentFlags().StringVar(&req.Signature, cfg.FlagNamer("Signature"), "", "The signature to verify in hexadecimal format.") cmd.PersistentFlags().StringVar(&req.PublicKey, cfg.FlagNamer("PublicKey"), "", "The public key of the signer.") return cmd } func _UtilsPublicKeyAggregationCommand(cfg *client.Config) *cobra.Command { req := &PublicKeyAggregationRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("PublicKeyAggregation"), Short: "PublicKeyAggregation RPC client", Long: "PublicKeyAggregation aggregates multiple BLS public keys into a single key.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils", "PublicKeyAggregation"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewUtilsClient(cc) v := &PublicKeyAggregationRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.PublicKeyAggregation(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringSliceVar(&req.PublicKeys, cfg.FlagNamer("PublicKeys"), nil, "List of BLS public keys to be aggregated.") return cmd } func _UtilsSignatureAggregationCommand(cfg *client.Config) *cobra.Command { req := &SignatureAggregationRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("SignatureAggregation"), Short: "SignatureAggregation RPC client", Long: "SignatureAggregation aggregates multiple BLS signatures into a single signature.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Utils", "SignatureAggregation"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewUtilsClient(cc) v := &SignatureAggregationRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.SignatureAggregation(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringSliceVar(&req.Signatures, cfg.FlagNamer("Signatures"), nil, "List of BLS signatures to be aggregated.") return cmd } ================================================ FILE: www/grpc/gen/go/utils.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: utils.proto package pactus import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Request message for signing a message with a private key. type SignMessageWithPrivateKeyRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The private key to sign the message. PrivateKey string `protobuf:"bytes,1,opt,name=private_key,json=privateKey,proto3" json:"private_key,omitempty"` // The message content to be signed. Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignMessageWithPrivateKeyRequest) Reset() { *x = SignMessageWithPrivateKeyRequest{} mi := &file_utils_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignMessageWithPrivateKeyRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignMessageWithPrivateKeyRequest) ProtoMessage() {} func (x *SignMessageWithPrivateKeyRequest) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignMessageWithPrivateKeyRequest.ProtoReflect.Descriptor instead. func (*SignMessageWithPrivateKeyRequest) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{0} } func (x *SignMessageWithPrivateKeyRequest) GetPrivateKey() string { if x != nil { return x.PrivateKey } return "" } func (x *SignMessageWithPrivateKeyRequest) GetMessage() string { if x != nil { return x.Message } return "" } // Response message contains the signature generated from the message. type SignMessageWithPrivateKeyResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The resulting signature in hexadecimal format. Signature string `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignMessageWithPrivateKeyResponse) Reset() { *x = SignMessageWithPrivateKeyResponse{} mi := &file_utils_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignMessageWithPrivateKeyResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignMessageWithPrivateKeyResponse) ProtoMessage() {} func (x *SignMessageWithPrivateKeyResponse) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignMessageWithPrivateKeyResponse.ProtoReflect.Descriptor instead. func (*SignMessageWithPrivateKeyResponse) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{1} } func (x *SignMessageWithPrivateKeyResponse) GetSignature() string { if x != nil { return x.Signature } return "" } // Request message for verifying a message signature. type VerifyMessageRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The original message content that was signed. Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` // The signature to verify in hexadecimal format. Signature string `protobuf:"bytes,2,opt,name=signature,proto3" json:"signature,omitempty"` // The public key of the signer. PublicKey string `protobuf:"bytes,3,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *VerifyMessageRequest) Reset() { *x = VerifyMessageRequest{} mi := &file_utils_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *VerifyMessageRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*VerifyMessageRequest) ProtoMessage() {} func (x *VerifyMessageRequest) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use VerifyMessageRequest.ProtoReflect.Descriptor instead. func (*VerifyMessageRequest) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{2} } func (x *VerifyMessageRequest) GetMessage() string { if x != nil { return x.Message } return "" } func (x *VerifyMessageRequest) GetSignature() string { if x != nil { return x.Signature } return "" } func (x *VerifyMessageRequest) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } // Response message contains the verification result. type VerifyMessageResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Boolean indicating whether the signature is valid for the given message and public key. IsValid bool `protobuf:"varint,1,opt,name=is_valid,json=isValid,proto3" json:"is_valid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *VerifyMessageResponse) Reset() { *x = VerifyMessageResponse{} mi := &file_utils_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *VerifyMessageResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*VerifyMessageResponse) ProtoMessage() {} func (x *VerifyMessageResponse) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use VerifyMessageResponse.ProtoReflect.Descriptor instead. func (*VerifyMessageResponse) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{3} } func (x *VerifyMessageResponse) GetIsValid() bool { if x != nil { return x.IsValid } return false } // Request message for aggregating multiple BLS public keys. type PublicKeyAggregationRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // List of BLS public keys to be aggregated. PublicKeys []string `protobuf:"bytes,1,rep,name=public_keys,json=publicKeys,proto3" json:"public_keys,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PublicKeyAggregationRequest) Reset() { *x = PublicKeyAggregationRequest{} mi := &file_utils_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PublicKeyAggregationRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PublicKeyAggregationRequest) ProtoMessage() {} func (x *PublicKeyAggregationRequest) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PublicKeyAggregationRequest.ProtoReflect.Descriptor instead. func (*PublicKeyAggregationRequest) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{4} } func (x *PublicKeyAggregationRequest) GetPublicKeys() []string { if x != nil { return x.PublicKeys } return nil } // Response message contains the aggregated BLS public key result. type PublicKeyAggregationResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The aggregated BLS public key. PublicKey string `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // The blockchain address derived from the aggregated public key. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PublicKeyAggregationResponse) Reset() { *x = PublicKeyAggregationResponse{} mi := &file_utils_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PublicKeyAggregationResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*PublicKeyAggregationResponse) ProtoMessage() {} func (x *PublicKeyAggregationResponse) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PublicKeyAggregationResponse.ProtoReflect.Descriptor instead. func (*PublicKeyAggregationResponse) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{5} } func (x *PublicKeyAggregationResponse) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *PublicKeyAggregationResponse) GetAddress() string { if x != nil { return x.Address } return "" } // Request message for aggregating multiple BLS signatures. type SignatureAggregationRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // List of BLS signatures to be aggregated. Signatures []string `protobuf:"bytes,1,rep,name=signatures,proto3" json:"signatures,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignatureAggregationRequest) Reset() { *x = SignatureAggregationRequest{} mi := &file_utils_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignatureAggregationRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignatureAggregationRequest) ProtoMessage() {} func (x *SignatureAggregationRequest) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignatureAggregationRequest.ProtoReflect.Descriptor instead. func (*SignatureAggregationRequest) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{6} } func (x *SignatureAggregationRequest) GetSignatures() []string { if x != nil { return x.Signatures } return nil } // Response message contains the aggregated BLS signature. type SignatureAggregationResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The aggregated BLS signature in hexadecimal format. Signature string `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignatureAggregationResponse) Reset() { *x = SignatureAggregationResponse{} mi := &file_utils_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignatureAggregationResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignatureAggregationResponse) ProtoMessage() {} func (x *SignatureAggregationResponse) ProtoReflect() protoreflect.Message { mi := &file_utils_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignatureAggregationResponse.ProtoReflect.Descriptor instead. func (*SignatureAggregationResponse) Descriptor() ([]byte, []int) { return file_utils_proto_rawDescGZIP(), []int{7} } func (x *SignatureAggregationResponse) GetSignature() string { if x != nil { return x.Signature } return "" } var File_utils_proto protoreflect.FileDescriptor const file_utils_proto_rawDesc = "" + "\n" + "\vutils.proto\x12\x06pactus\"]\n" + " SignMessageWithPrivateKeyRequest\x12\x1f\n" + "\vprivate_key\x18\x01 \x01(\tR\n" + "privateKey\x12\x18\n" + "\amessage\x18\x02 \x01(\tR\amessage\"A\n" + "!SignMessageWithPrivateKeyResponse\x12\x1c\n" + "\tsignature\x18\x01 \x01(\tR\tsignature\"m\n" + "\x14VerifyMessageRequest\x12\x18\n" + "\amessage\x18\x01 \x01(\tR\amessage\x12\x1c\n" + "\tsignature\x18\x02 \x01(\tR\tsignature\x12\x1d\n" + "\n" + "public_key\x18\x03 \x01(\tR\tpublicKey\"2\n" + "\x15VerifyMessageResponse\x12\x19\n" + "\bis_valid\x18\x01 \x01(\bR\aisValid\">\n" + "\x1bPublicKeyAggregationRequest\x12\x1f\n" + "\vpublic_keys\x18\x01 \x03(\tR\n" + "publicKeys\"W\n" + "\x1cPublicKeyAggregationResponse\x12\x1d\n" + "\n" + "public_key\x18\x01 \x01(\tR\tpublicKey\x12\x18\n" + "\aaddress\x18\x02 \x01(\tR\aaddress\"=\n" + "\x1bSignatureAggregationRequest\x12\x1e\n" + "\n" + "signatures\x18\x01 \x03(\tR\n" + "signatures\"<\n" + "\x1cSignatureAggregationResponse\x12\x1c\n" + "\tsignature\x18\x01 \x01(\tR\tsignature2\x8d\x03\n" + "\x05Utils\x12p\n" + "\x19SignMessageWithPrivateKey\x12(.pactus.SignMessageWithPrivateKeyRequest\x1a).pactus.SignMessageWithPrivateKeyResponse\x12L\n" + "\rVerifyMessage\x12\x1c.pactus.VerifyMessageRequest\x1a\x1d.pactus.VerifyMessageResponse\x12a\n" + "\x14PublicKeyAggregation\x12#.pactus.PublicKeyAggregationRequest\x1a$.pactus.PublicKeyAggregationResponse\x12a\n" + "\x14SignatureAggregation\x12#.pactus.SignatureAggregationRequest\x1a$.pactus.SignatureAggregationResponseB:\n" + "\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3" var ( file_utils_proto_rawDescOnce sync.Once file_utils_proto_rawDescData []byte ) func file_utils_proto_rawDescGZIP() []byte { file_utils_proto_rawDescOnce.Do(func() { file_utils_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_utils_proto_rawDesc), len(file_utils_proto_rawDesc))) }) return file_utils_proto_rawDescData } var file_utils_proto_msgTypes = make([]protoimpl.MessageInfo, 8) var file_utils_proto_goTypes = []any{ (*SignMessageWithPrivateKeyRequest)(nil), // 0: pactus.SignMessageWithPrivateKeyRequest (*SignMessageWithPrivateKeyResponse)(nil), // 1: pactus.SignMessageWithPrivateKeyResponse (*VerifyMessageRequest)(nil), // 2: pactus.VerifyMessageRequest (*VerifyMessageResponse)(nil), // 3: pactus.VerifyMessageResponse (*PublicKeyAggregationRequest)(nil), // 4: pactus.PublicKeyAggregationRequest (*PublicKeyAggregationResponse)(nil), // 5: pactus.PublicKeyAggregationResponse (*SignatureAggregationRequest)(nil), // 6: pactus.SignatureAggregationRequest (*SignatureAggregationResponse)(nil), // 7: pactus.SignatureAggregationResponse } var file_utils_proto_depIdxs = []int32{ 0, // 0: pactus.Utils.SignMessageWithPrivateKey:input_type -> pactus.SignMessageWithPrivateKeyRequest 2, // 1: pactus.Utils.VerifyMessage:input_type -> pactus.VerifyMessageRequest 4, // 2: pactus.Utils.PublicKeyAggregation:input_type -> pactus.PublicKeyAggregationRequest 6, // 3: pactus.Utils.SignatureAggregation:input_type -> pactus.SignatureAggregationRequest 1, // 4: pactus.Utils.SignMessageWithPrivateKey:output_type -> pactus.SignMessageWithPrivateKeyResponse 3, // 5: pactus.Utils.VerifyMessage:output_type -> pactus.VerifyMessageResponse 5, // 6: pactus.Utils.PublicKeyAggregation:output_type -> pactus.PublicKeyAggregationResponse 7, // 7: pactus.Utils.SignatureAggregation:output_type -> pactus.SignatureAggregationResponse 4, // [4:8] is the sub-list for method output_type 0, // [0:4] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_utils_proto_init() } func file_utils_proto_init() { if File_utils_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_utils_proto_rawDesc), len(file_utils_proto_rawDesc)), NumEnums: 0, NumMessages: 8, NumExtensions: 0, NumServices: 1, }, GoTypes: file_utils_proto_goTypes, DependencyIndexes: file_utils_proto_depIdxs, MessageInfos: file_utils_proto_msgTypes, }.Build() File_utils_proto = out.File file_utils_proto_goTypes = nil file_utils_proto_depIdxs = nil } ================================================ FILE: www/grpc/gen/go/utils.pb.gw.go ================================================ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: utils.proto /* Package pactus is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package pactus import ( "context" "errors" "io" "net/http" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors var ( _ codes.Code _ io.Reader _ status.Status _ = errors.New _ = runtime.String _ = utilities.NewDoubleArray _ = metadata.Join ) func request_Utils_SignMessageWithPrivateKey_0(ctx context.Context, marshaler runtime.Marshaler, client UtilsClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignMessageWithPrivateKeyRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.SignMessageWithPrivateKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Utils_SignMessageWithPrivateKey_0(ctx context.Context, marshaler runtime.Marshaler, server UtilsServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignMessageWithPrivateKeyRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SignMessageWithPrivateKey(ctx, &protoReq) return msg, metadata, err } func request_Utils_VerifyMessage_0(ctx context.Context, marshaler runtime.Marshaler, client UtilsClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq VerifyMessageRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.VerifyMessage(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Utils_VerifyMessage_0(ctx context.Context, marshaler runtime.Marshaler, server UtilsServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq VerifyMessageRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.VerifyMessage(ctx, &protoReq) return msg, metadata, err } func request_Utils_PublicKeyAggregation_0(ctx context.Context, marshaler runtime.Marshaler, client UtilsClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq PublicKeyAggregationRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.PublicKeyAggregation(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Utils_PublicKeyAggregation_0(ctx context.Context, marshaler runtime.Marshaler, server UtilsServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq PublicKeyAggregationRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.PublicKeyAggregation(ctx, &protoReq) return msg, metadata, err } func request_Utils_SignatureAggregation_0(ctx context.Context, marshaler runtime.Marshaler, client UtilsClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignatureAggregationRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.SignatureAggregation(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Utils_SignatureAggregation_0(ctx context.Context, marshaler runtime.Marshaler, server UtilsServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignatureAggregationRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SignatureAggregation(ctx, &protoReq) return msg, metadata, err } // RegisterUtilsHandlerServer registers the http handlers for service Utils to "mux". // UnaryRPC :call UtilsServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterUtilsHandlerFromEndpoint instead. // GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterUtilsHandlerServer(ctx context.Context, mux *runtime.ServeMux, server UtilsServer) error { mux.Handle(http.MethodPost, pattern_Utils_SignMessageWithPrivateKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Utils/SignMessageWithPrivateKey", runtime.WithHTTPPathPattern("/pactus/Utils/sign_message_with_private_key")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Utils_SignMessageWithPrivateKey_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_SignMessageWithPrivateKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Utils_VerifyMessage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Utils/VerifyMessage", runtime.WithHTTPPathPattern("/pactus/Utils/verify_message")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Utils_VerifyMessage_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_VerifyMessage_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Utils_PublicKeyAggregation_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Utils/PublicKeyAggregation", runtime.WithHTTPPathPattern("/pactus/Utils/public_key_aggregation")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Utils_PublicKeyAggregation_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_PublicKeyAggregation_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Utils_SignatureAggregation_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Utils/SignatureAggregation", runtime.WithHTTPPathPattern("/pactus/Utils/signature_aggregation")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Utils_SignatureAggregation_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_SignatureAggregation_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterUtilsHandlerFromEndpoint is same as RegisterUtilsHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterUtilsHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterUtilsHandler(ctx, mux, conn) } // RegisterUtilsHandler registers the http handlers for service Utils to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterUtilsHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterUtilsHandlerClient(ctx, mux, NewUtilsClient(conn)) } // RegisterUtilsHandlerClient registers the http handlers for service Utils // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "UtilsClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "UtilsClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "UtilsClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterUtilsHandlerClient(ctx context.Context, mux *runtime.ServeMux, client UtilsClient) error { mux.Handle(http.MethodPost, pattern_Utils_SignMessageWithPrivateKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Utils/SignMessageWithPrivateKey", runtime.WithHTTPPathPattern("/pactus/Utils/sign_message_with_private_key")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Utils_SignMessageWithPrivateKey_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_SignMessageWithPrivateKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Utils_VerifyMessage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Utils/VerifyMessage", runtime.WithHTTPPathPattern("/pactus/Utils/verify_message")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Utils_VerifyMessage_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_VerifyMessage_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Utils_PublicKeyAggregation_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Utils/PublicKeyAggregation", runtime.WithHTTPPathPattern("/pactus/Utils/public_key_aggregation")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Utils_PublicKeyAggregation_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_PublicKeyAggregation_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Utils_SignatureAggregation_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Utils/SignatureAggregation", runtime.WithHTTPPathPattern("/pactus/Utils/signature_aggregation")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Utils_SignatureAggregation_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Utils_SignatureAggregation_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_Utils_SignMessageWithPrivateKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "Utils", "sign_message_with_private_key"}, "")) pattern_Utils_VerifyMessage_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "Utils", "verify_message"}, "")) pattern_Utils_PublicKeyAggregation_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "Utils", "public_key_aggregation"}, "")) pattern_Utils_SignatureAggregation_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "Utils", "signature_aggregation"}, "")) ) var ( forward_Utils_SignMessageWithPrivateKey_0 = runtime.ForwardResponseMessage forward_Utils_VerifyMessage_0 = runtime.ForwardResponseMessage forward_Utils_PublicKeyAggregation_0 = runtime.ForwardResponseMessage forward_Utils_SignatureAggregation_0 = runtime.ForwardResponseMessage ) ================================================ FILE: www/grpc/gen/go/utils_grpc.pb.go ================================================ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.6.0 // - protoc (unknown) // source: utils.proto package pactus import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( Utils_SignMessageWithPrivateKey_FullMethodName = "/pactus.Utils/SignMessageWithPrivateKey" Utils_VerifyMessage_FullMethodName = "/pactus.Utils/VerifyMessage" Utils_PublicKeyAggregation_FullMethodName = "/pactus.Utils/PublicKeyAggregation" Utils_SignatureAggregation_FullMethodName = "/pactus.Utils/SignatureAggregation" ) // UtilsClient is the client API for Utils service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. // // Utils service defines RPC methods for utility functions such as message // signing, verification, and other cryptographic operations. type UtilsClient interface { // SignMessageWithPrivateKey signs a message with the provided private key. SignMessageWithPrivateKey(ctx context.Context, in *SignMessageWithPrivateKeyRequest, opts ...grpc.CallOption) (*SignMessageWithPrivateKeyResponse, error) // VerifyMessage verifies a signature against the public key and message. VerifyMessage(ctx context.Context, in *VerifyMessageRequest, opts ...grpc.CallOption) (*VerifyMessageResponse, error) // PublicKeyAggregation aggregates multiple BLS public keys into a single key. PublicKeyAggregation(ctx context.Context, in *PublicKeyAggregationRequest, opts ...grpc.CallOption) (*PublicKeyAggregationResponse, error) // SignatureAggregation aggregates multiple BLS signatures into a single signature. SignatureAggregation(ctx context.Context, in *SignatureAggregationRequest, opts ...grpc.CallOption) (*SignatureAggregationResponse, error) } type utilsClient struct { cc grpc.ClientConnInterface } func NewUtilsClient(cc grpc.ClientConnInterface) UtilsClient { return &utilsClient{cc} } func (c *utilsClient) SignMessageWithPrivateKey(ctx context.Context, in *SignMessageWithPrivateKeyRequest, opts ...grpc.CallOption) (*SignMessageWithPrivateKeyResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SignMessageWithPrivateKeyResponse) err := c.cc.Invoke(ctx, Utils_SignMessageWithPrivateKey_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *utilsClient) VerifyMessage(ctx context.Context, in *VerifyMessageRequest, opts ...grpc.CallOption) (*VerifyMessageResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(VerifyMessageResponse) err := c.cc.Invoke(ctx, Utils_VerifyMessage_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *utilsClient) PublicKeyAggregation(ctx context.Context, in *PublicKeyAggregationRequest, opts ...grpc.CallOption) (*PublicKeyAggregationResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(PublicKeyAggregationResponse) err := c.cc.Invoke(ctx, Utils_PublicKeyAggregation_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *utilsClient) SignatureAggregation(ctx context.Context, in *SignatureAggregationRequest, opts ...grpc.CallOption) (*SignatureAggregationResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SignatureAggregationResponse) err := c.cc.Invoke(ctx, Utils_SignatureAggregation_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // UtilsServer is the server API for Utils service. // All implementations should embed UnimplementedUtilsServer // for forward compatibility. // // Utils service defines RPC methods for utility functions such as message // signing, verification, and other cryptographic operations. type UtilsServer interface { // SignMessageWithPrivateKey signs a message with the provided private key. SignMessageWithPrivateKey(context.Context, *SignMessageWithPrivateKeyRequest) (*SignMessageWithPrivateKeyResponse, error) // VerifyMessage verifies a signature against the public key and message. VerifyMessage(context.Context, *VerifyMessageRequest) (*VerifyMessageResponse, error) // PublicKeyAggregation aggregates multiple BLS public keys into a single key. PublicKeyAggregation(context.Context, *PublicKeyAggregationRequest) (*PublicKeyAggregationResponse, error) // SignatureAggregation aggregates multiple BLS signatures into a single signature. SignatureAggregation(context.Context, *SignatureAggregationRequest) (*SignatureAggregationResponse, error) } // UnimplementedUtilsServer should be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedUtilsServer struct{} func (UnimplementedUtilsServer) SignMessageWithPrivateKey(context.Context, *SignMessageWithPrivateKeyRequest) (*SignMessageWithPrivateKeyResponse, error) { return nil, status.Error(codes.Unimplemented, "method SignMessageWithPrivateKey not implemented") } func (UnimplementedUtilsServer) VerifyMessage(context.Context, *VerifyMessageRequest) (*VerifyMessageResponse, error) { return nil, status.Error(codes.Unimplemented, "method VerifyMessage not implemented") } func (UnimplementedUtilsServer) PublicKeyAggregation(context.Context, *PublicKeyAggregationRequest) (*PublicKeyAggregationResponse, error) { return nil, status.Error(codes.Unimplemented, "method PublicKeyAggregation not implemented") } func (UnimplementedUtilsServer) SignatureAggregation(context.Context, *SignatureAggregationRequest) (*SignatureAggregationResponse, error) { return nil, status.Error(codes.Unimplemented, "method SignatureAggregation not implemented") } func (UnimplementedUtilsServer) testEmbeddedByValue() {} // UnsafeUtilsServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to UtilsServer will // result in compilation errors. type UnsafeUtilsServer interface { mustEmbedUnimplementedUtilsServer() } func RegisterUtilsServer(s grpc.ServiceRegistrar, srv UtilsServer) { // If the following call panics, it indicates UnimplementedUtilsServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&Utils_ServiceDesc, srv) } func _Utils_SignMessageWithPrivateKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SignMessageWithPrivateKeyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UtilsServer).SignMessageWithPrivateKey(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Utils_SignMessageWithPrivateKey_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UtilsServer).SignMessageWithPrivateKey(ctx, req.(*SignMessageWithPrivateKeyRequest)) } return interceptor(ctx, in, info, handler) } func _Utils_VerifyMessage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(VerifyMessageRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UtilsServer).VerifyMessage(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Utils_VerifyMessage_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UtilsServer).VerifyMessage(ctx, req.(*VerifyMessageRequest)) } return interceptor(ctx, in, info, handler) } func _Utils_PublicKeyAggregation_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PublicKeyAggregationRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UtilsServer).PublicKeyAggregation(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Utils_PublicKeyAggregation_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UtilsServer).PublicKeyAggregation(ctx, req.(*PublicKeyAggregationRequest)) } return interceptor(ctx, in, info, handler) } func _Utils_SignatureAggregation_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SignatureAggregationRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UtilsServer).SignatureAggregation(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Utils_SignatureAggregation_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UtilsServer).SignatureAggregation(ctx, req.(*SignatureAggregationRequest)) } return interceptor(ctx, in, info, handler) } // Utils_ServiceDesc is the grpc.ServiceDesc for Utils service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var Utils_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Utils", HandlerType: (*UtilsServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "SignMessageWithPrivateKey", Handler: _Utils_SignMessageWithPrivateKey_Handler, }, { MethodName: "VerifyMessage", Handler: _Utils_VerifyMessage_Handler, }, { MethodName: "PublicKeyAggregation", Handler: _Utils_PublicKeyAggregation_Handler, }, { MethodName: "SignatureAggregation", Handler: _Utils_SignatureAggregation_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "utils.proto", } ================================================ FILE: www/grpc/gen/go/utils_jgw.pb.go ================================================ // Code generated by protoc-gen-jrpc-gateway. DO NOT EDIT. // source: utils.proto /* Package pactus is a reverse proxy. It translates gRPC into JSON-RPC 2.0 */ package pactus import ( "context" "encoding/json" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" ) type UtilsJsonRPC struct { client UtilsClient } type paramsAndHeadersUtils struct { Headers metadata.MD `json:"headers,omitempty"` Params json.RawMessage `json:"params"` } // RegisterUtilsJsonRPC register the grpc client Utils for json-rpc. // The handlers forward requests to the grpc endpoint over "conn". func RegisterUtilsJsonRPC(conn *grpc.ClientConn) *UtilsJsonRPC { return &UtilsJsonRPC{ client: NewUtilsClient(conn), } } func (s *UtilsJsonRPC) Methods() map[string]func(ctx context.Context, message json.RawMessage) (any, error) { return map[string]func(ctx context.Context, params json.RawMessage) (any, error){ "pactus.utils.sign_message_with_private_key": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(SignMessageWithPrivateKeyRequest) var jrpcData paramsAndHeadersUtils if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.SignMessageWithPrivateKey(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.utils.verify_message": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(VerifyMessageRequest) var jrpcData paramsAndHeadersUtils if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.VerifyMessage(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.utils.public_key_aggregation": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(PublicKeyAggregationRequest) var jrpcData paramsAndHeadersUtils if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.PublicKeyAggregation(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.utils.signature_aggregation": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(SignatureAggregationRequest) var jrpcData paramsAndHeadersUtils if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.SignatureAggregation(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, } } ================================================ FILE: www/grpc/gen/go/wallet.cobra.pb.go ================================================ // Code generated by protoc-gen-cobra. DO NOT EDIT. package pactus import ( client "github.com/NathanBaulch/protoc-gen-cobra/client" flag "github.com/NathanBaulch/protoc-gen-cobra/flag" iocodec "github.com/NathanBaulch/protoc-gen-cobra/iocodec" cobra "github.com/spf13/cobra" grpc "google.golang.org/grpc" proto "google.golang.org/protobuf/proto" ) func WalletClientCommand(options ...client.Option) *cobra.Command { cfg := client.NewConfig(options...) cmd := &cobra.Command{ Use: cfg.CommandNamer("Wallet"), Short: "Wallet service client", Long: "Wallet service provides RPC methods for wallet management operations.", } cfg.BindFlags(cmd.PersistentFlags()) cmd.AddCommand( _WalletCreateWalletCommand(cfg), _WalletRestoreWalletCommand(cfg), _WalletLoadWalletCommand(cfg), _WalletUnloadWalletCommand(cfg), _WalletListWalletsCommand(cfg), _WalletGetWalletInfoCommand(cfg), _WalletUpdatePasswordCommand(cfg), _WalletGetTotalBalanceCommand(cfg), _WalletGetTotalStakeCommand(cfg), _WalletGetValidatorAddressCommand(cfg), _WalletGetAddressInfoCommand(cfg), _WalletSetAddressLabelCommand(cfg), _WalletGetNewAddressCommand(cfg), _WalletListAddressesCommand(cfg), _WalletSignMessageCommand(cfg), _WalletSignRawTransactionCommand(cfg), _WalletListTransactionsCommand(cfg), _WalletSetDefaultFeeCommand(cfg), _WalletGetMnemonicCommand(cfg), _WalletGetPrivateKeyCommand(cfg), ) return cmd } func _WalletCreateWalletCommand(cfg *client.Config) *cobra.Command { req := &CreateWalletRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("CreateWallet"), Short: "CreateWallet RPC client", Long: "CreateWallet creates a new wallet with the specified parameters.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "CreateWallet"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &CreateWalletRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.CreateWallet(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name for the new wallet.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Password to secure the new wallet.") return cmd } func _WalletRestoreWalletCommand(cfg *client.Config) *cobra.Command { req := &RestoreWalletRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("RestoreWallet"), Short: "RestoreWallet RPC client", Long: "RestoreWallet restores an existing wallet with the given mnemonic.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "RestoreWallet"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &RestoreWalletRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.RestoreWallet(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name for the restored wallet.") cmd.PersistentFlags().StringVar(&req.Mnemonic, cfg.FlagNamer("Mnemonic"), "", "The mnemonic (seed phrase) for wallet recovery.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Password to secure the restored wallet.") return cmd } func _WalletLoadWalletCommand(cfg *client.Config) *cobra.Command { req := &LoadWalletRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("LoadWallet"), Short: "LoadWallet RPC client", Long: "LoadWallet loads an existing wallet with the given name.\n deprecated: It will be removed in a future version.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "LoadWallet"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &LoadWalletRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.LoadWallet(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to load.") return cmd } func _WalletUnloadWalletCommand(cfg *client.Config) *cobra.Command { req := &UnloadWalletRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("UnloadWallet"), Short: "UnloadWallet RPC client", Long: "UnloadWallet unloads a currently loaded wallet with the specified name.\n deprecated: It will be removed in a future version.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "UnloadWallet"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &UnloadWalletRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.UnloadWallet(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to unload.") return cmd } func _WalletListWalletsCommand(cfg *client.Config) *cobra.Command { req := &ListWalletsRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("ListWallets"), Short: "ListWallets RPC client", Long: "ListWallets returns a list of all available wallets.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "ListWallets"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &ListWalletsRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.ListWallets(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } return cmd } func _WalletGetWalletInfoCommand(cfg *client.Config) *cobra.Command { req := &GetWalletInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetWalletInfo"), Short: "GetWalletInfo RPC client", Long: "GetWalletInfo returns detailed information about a specific wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetWalletInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetWalletInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetWalletInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to query.") return cmd } func _WalletUpdatePasswordCommand(cfg *client.Config) *cobra.Command { req := &UpdatePasswordRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("UpdatePassword"), Short: "UpdatePassword RPC client", Long: "UpdatePassword updates the password of an existing wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "UpdatePassword"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &UpdatePasswordRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.UpdatePassword(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet whose password will be updated.") cmd.PersistentFlags().StringVar(&req.OldPassword, cfg.FlagNamer("OldPassword"), "", "The current wallet password.") cmd.PersistentFlags().StringVar(&req.NewPassword, cfg.FlagNamer("NewPassword"), "", "The new wallet password.") return cmd } func _WalletGetTotalBalanceCommand(cfg *client.Config) *cobra.Command { req := &GetTotalBalanceRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetTotalBalance"), Short: "GetTotalBalance RPC client", Long: "GetTotalBalance returns the total available balance of the wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetTotalBalance"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetTotalBalanceRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetTotalBalance(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to get the total balance.") return cmd } func _WalletGetTotalStakeCommand(cfg *client.Config) *cobra.Command { req := &GetTotalStakeRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetTotalStake"), Short: "GetTotalStake RPC client", Long: "GetTotalStake returns the total stake amount in the wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetTotalStake"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetTotalStakeRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetTotalStake(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to get the total stake.") return cmd } func _WalletGetValidatorAddressCommand(cfg *client.Config) *cobra.Command { req := &GetValidatorAddressRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetValidatorAddress"), Short: "GetValidatorAddress RPC client", Long: "GetValidatorAddress retrieves the validator address associated with a public key.\n Deprecated: Will move into utils.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetValidatorAddress"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetValidatorAddressRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetValidatorAddress(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.PublicKey, cfg.FlagNamer("PublicKey"), "", "The public key of the validator.") return cmd } func _WalletGetAddressInfoCommand(cfg *client.Config) *cobra.Command { req := &GetAddressInfoRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetAddressInfo"), Short: "GetAddressInfo RPC client", Long: "GetAddressInfo returns detailed information about a specific address.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetAddressInfo"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetAddressInfoRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetAddressInfo(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet containing the address.") cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address to query.") return cmd } func _WalletSetAddressLabelCommand(cfg *client.Config) *cobra.Command { req := &SetAddressLabelRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("SetAddressLabel"), Short: "SetAddressLabel RPC client", Long: "SetAddressLabel sets or updates the label for a given address.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "SetAddressLabel"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &SetAddressLabelRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.SetAddressLabel(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet containing the address.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Wallet password required for modification.") cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address to label.") cmd.PersistentFlags().StringVar(&req.Label, cfg.FlagNamer("Label"), "", "The new label for the address.") return cmd } func _WalletGetNewAddressCommand(cfg *client.Config) *cobra.Command { req := &GetNewAddressRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetNewAddress"), Short: "GetNewAddress RPC client", Long: "GetNewAddress generates a new address for the specified wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetNewAddress"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetNewAddressRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetNewAddress(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to generate a new address.") flag.EnumVar(cmd.PersistentFlags(), &req.AddressType, cfg.FlagNamer("AddressType"), "The type of address to generate.") cmd.PersistentFlags().StringVar(&req.Label, cfg.FlagNamer("Label"), "", "A label for the new address.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Password for the new address. It's required when address_type is Ed25519 type.") return cmd } func _WalletListAddressesCommand(cfg *client.Config) *cobra.Command { req := &ListAddressesRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("ListAddresses"), Short: "ListAddresses RPC client", Long: "ListAddresses returns all addresses in the specified wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "ListAddresses"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &ListAddressesRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.ListAddresses(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the queried wallet.") flag.EnumSliceVar(cmd.PersistentFlags(), &req.AddressTypes, cfg.FlagNamer("AddressTypes"), "Filter addresses by their types. If empty, all address types are included.") return cmd } func _WalletSignMessageCommand(cfg *client.Config) *cobra.Command { req := &SignMessageRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("SignMessage"), Short: "SignMessage RPC client", Long: "SignMessage signs an arbitrary message using a wallet's private key.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "SignMessage"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &SignMessageRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.SignMessage(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to sign with.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Wallet password required for signing.") cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address whose private key should be used for signing the message.") cmd.PersistentFlags().StringVar(&req.Message, cfg.FlagNamer("Message"), "", "The arbitrary message to be signed.") return cmd } func _WalletSignRawTransactionCommand(cfg *client.Config) *cobra.Command { req := &SignRawTransactionRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("SignRawTransaction"), Short: "SignRawTransaction RPC client", Long: "SignRawTransaction signs a raw transaction for a specified wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "SignRawTransaction"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &SignRawTransactionRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.SignRawTransaction(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet used for signing.") cmd.PersistentFlags().StringVar(&req.RawTransaction, cfg.FlagNamer("RawTransaction"), "", "The raw transaction data to be signed.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Wallet password required for signing.") return cmd } func _WalletListTransactionsCommand(cfg *client.Config) *cobra.Command { req := &ListTransactionsRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("ListTransactions"), Short: "ListTransactions RPC client", Long: "ListTransactions returns a list of transactions for a wallet,\n optionally filtered by a specific address, with pagination support.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "ListTransactions"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &ListTransactionsRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.ListTransactions(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to query transactions for.") cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "Optional: The address to filter transactions.\n If empty or set to '*', transactions for all addresses in the wallet are included.") flag.EnumVar(cmd.PersistentFlags(), &req.Direction, cfg.FlagNamer("Direction"), "Filter transactions by direction relative to the wallet.\n Defaults to any direction if not set.") cmd.PersistentFlags().Int32Var(&req.Count, cfg.FlagNamer("Count"), 0, "Optional: The maximum number of transactions to return.\n Defaults to 10 if not set.") cmd.PersistentFlags().Int32Var(&req.Skip, cfg.FlagNamer("Skip"), 0, "Optional: The number of transactions to skip (for pagination).\n Defaults to 0 if not set.") return cmd } func _WalletSetDefaultFeeCommand(cfg *client.Config) *cobra.Command { req := &SetDefaultFeeRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("SetDefaultFee"), Short: "SetDefaultFee RPC client", Long: "SetDefaultFee sets the default fee for the wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "SetDefaultFee"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &SetDefaultFeeRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.SetDefaultFee(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to set the default fee.") cmd.PersistentFlags().Int64Var(&req.Amount, cfg.FlagNamer("Amount"), 0, "The default fee amount in NanoPAC.") return cmd } func _WalletGetMnemonicCommand(cfg *client.Config) *cobra.Command { req := &GetMnemonicRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetMnemonic"), Short: "GetMnemonic RPC client", Long: "GetMnemonic returns the mnemonic (seed phrase) for the wallet.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetMnemonic"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetMnemonicRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetMnemonic(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet to get the mnemonic.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Wallet password.") return cmd } func _WalletGetPrivateKeyCommand(cfg *client.Config) *cobra.Command { req := &GetPrivateKeyRequest{} cmd := &cobra.Command{ Use: cfg.CommandNamer("GetPrivateKey"), Short: "GetPrivateKey RPC client", Long: "GetPrivateKey returns the private key for a given address.", RunE: func(cmd *cobra.Command, args []string) error { if cfg.UseEnvVars { if err := flag.SetFlagsFromEnv(cmd.Parent().PersistentFlags(), true, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet"); err != nil { return err } if err := flag.SetFlagsFromEnv(cmd.PersistentFlags(), false, cfg.EnvVarNamer, cfg.EnvVarPrefix, "Wallet", "GetPrivateKey"); err != nil { return err } } return client.RoundTrip(cmd.Context(), cfg, func(cc grpc.ClientConnInterface, in iocodec.Decoder, out iocodec.Encoder) error { cli := NewWalletClient(cc) v := &GetPrivateKeyRequest{} if err := in(v); err != nil { return err } proto.Merge(v, req) res, err := cli.GetPrivateKey(cmd.Context(), v) if err != nil { return err } return out(res) }) }, } cmd.PersistentFlags().StringVar(&req.WalletName, cfg.FlagNamer("WalletName"), "", "The name of the wallet containing the address.") cmd.PersistentFlags().StringVar(&req.Password, cfg.FlagNamer("Password"), "", "Wallet password.") cmd.PersistentFlags().StringVar(&req.Address, cfg.FlagNamer("Address"), "", "The address to get the private key.") return cmd } ================================================ FILE: www/grpc/gen/go/wallet.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: wallet.proto package pactus import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // AddressType defines different types of blockchain addresses. type AddressType int32 const ( // Treasury address type. // Should not be used to generate new addresses. AddressType_ADDRESS_TYPE_TREASURY AddressType = 0 // Validator address type used for validator nodes. AddressType_ADDRESS_TYPE_VALIDATOR AddressType = 1 // Account address type with BLS signature scheme. AddressType_ADDRESS_TYPE_BLS_ACCOUNT AddressType = 2 // Account address type with Ed25519 signature scheme. // Note: Generating a new Ed25519 address requires the wallet password. AddressType_ADDRESS_TYPE_ED25519_ACCOUNT AddressType = 3 ) // Enum value maps for AddressType. var ( AddressType_name = map[int32]string{ 0: "ADDRESS_TYPE_TREASURY", 1: "ADDRESS_TYPE_VALIDATOR", 2: "ADDRESS_TYPE_BLS_ACCOUNT", 3: "ADDRESS_TYPE_ED25519_ACCOUNT", } AddressType_value = map[string]int32{ "ADDRESS_TYPE_TREASURY": 0, "ADDRESS_TYPE_VALIDATOR": 1, "ADDRESS_TYPE_BLS_ACCOUNT": 2, "ADDRESS_TYPE_ED25519_ACCOUNT": 3, } ) func (x AddressType) Enum() *AddressType { p := new(AddressType) *p = x return p } func (x AddressType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AddressType) Descriptor() protoreflect.EnumDescriptor { return file_wallet_proto_enumTypes[0].Descriptor() } func (AddressType) Type() protoreflect.EnumType { return &file_wallet_proto_enumTypes[0] } func (x AddressType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AddressType.Descriptor instead. func (AddressType) EnumDescriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{0} } // TxDirection indicates the direction of a transaction relative to the wallet. type TxDirection int32 const ( // include both incoming and outgoing transactions. TxDirection_TX_DIRECTION_ANY TxDirection = 0 // Include only incoming transactions where the wallet receives funds. TxDirection_TX_DIRECTION_INCOMING TxDirection = 1 // Include only outgoing transactions where the wallet sends funds. TxDirection_TX_DIRECTION_OUTGOING TxDirection = 2 ) // Enum value maps for TxDirection. var ( TxDirection_name = map[int32]string{ 0: "TX_DIRECTION_ANY", 1: "TX_DIRECTION_INCOMING", 2: "TX_DIRECTION_OUTGOING", } TxDirection_value = map[string]int32{ "TX_DIRECTION_ANY": 0, "TX_DIRECTION_INCOMING": 1, "TX_DIRECTION_OUTGOING": 2, } ) func (x TxDirection) Enum() *TxDirection { p := new(TxDirection) *p = x return p } func (x TxDirection) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TxDirection) Descriptor() protoreflect.EnumDescriptor { return file_wallet_proto_enumTypes[1].Descriptor() } func (TxDirection) Type() protoreflect.EnumType { return &file_wallet_proto_enumTypes[1] } func (x TxDirection) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TxDirection.Descriptor instead. func (TxDirection) EnumDescriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{1} } // TransactionStatus defines the status of a transaction. type TransactionStatus int32 const ( // Pending status for transactions in the mempool. TransactionStatus_TRANSACTION_STATUS_PENDING TransactionStatus = 0 // Confirmed status for transactions included in a block. TransactionStatus_TRANSACTION_STATUS_CONFIRMED TransactionStatus = 1 // Failed status for transactions that were not successful. TransactionStatus_TRANSACTION_STATUS_FAILED TransactionStatus = -1 ) // Enum value maps for TransactionStatus. var ( TransactionStatus_name = map[int32]string{ 0: "TRANSACTION_STATUS_PENDING", 1: "TRANSACTION_STATUS_CONFIRMED", -1: "TRANSACTION_STATUS_FAILED", } TransactionStatus_value = map[string]int32{ "TRANSACTION_STATUS_PENDING": 0, "TRANSACTION_STATUS_CONFIRMED": 1, "TRANSACTION_STATUS_FAILED": -1, } ) func (x TransactionStatus) Enum() *TransactionStatus { p := new(TransactionStatus) *p = x return p } func (x TransactionStatus) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TransactionStatus) Descriptor() protoreflect.EnumDescriptor { return file_wallet_proto_enumTypes[2].Descriptor() } func (TransactionStatus) Type() protoreflect.EnumType { return &file_wallet_proto_enumTypes[2] } func (x TransactionStatus) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TransactionStatus.Descriptor instead. func (TransactionStatus) EnumDescriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{2} } // AddressInfo contains detailed information about a wallet address. type AddressInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // The address string. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` // The public key associated with the address. PublicKey string `protobuf:"bytes,2,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // A human-readable label associated with the address. Label string `protobuf:"bytes,3,opt,name=label,proto3" json:"label,omitempty"` // The Hierarchical Deterministic (HD) path of the address within the wallet. Path string `protobuf:"bytes,4,opt,name=path,proto3" json:"path,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddressInfo) Reset() { *x = AddressInfo{} mi := &file_wallet_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AddressInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddressInfo) ProtoMessage() {} func (x *AddressInfo) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddressInfo.ProtoReflect.Descriptor instead. func (*AddressInfo) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{0} } func (x *AddressInfo) GetAddress() string { if x != nil { return x.Address } return "" } func (x *AddressInfo) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *AddressInfo) GetLabel() string { if x != nil { return x.Label } return "" } func (x *AddressInfo) GetPath() string { if x != nil { return x.Path } return "" } // Request message for generating a new wallet address. type GetNewAddressRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to generate a new address. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The type of address to generate. AddressType AddressType `protobuf:"varint,2,opt,name=address_type,json=addressType,proto3,enum=pactus.AddressType" json:"address_type,omitempty"` // A label for the new address. Label string `protobuf:"bytes,3,opt,name=label,proto3" json:"label,omitempty"` // Password for the new address. It's required when address_type is Ed25519 type. Password string `protobuf:"bytes,4,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetNewAddressRequest) Reset() { *x = GetNewAddressRequest{} mi := &file_wallet_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetNewAddressRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetNewAddressRequest) ProtoMessage() {} func (x *GetNewAddressRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetNewAddressRequest.ProtoReflect.Descriptor instead. func (*GetNewAddressRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{1} } func (x *GetNewAddressRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetNewAddressRequest) GetAddressType() AddressType { if x != nil { return x.AddressType } return AddressType_ADDRESS_TYPE_TREASURY } func (x *GetNewAddressRequest) GetLabel() string { if x != nil { return x.Label } return "" } func (x *GetNewAddressRequest) GetPassword() string { if x != nil { return x.Password } return "" } // Response message contains newly generated address information. type GetNewAddressResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet where address was generated. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Detailed information about the new address. Addr *AddressInfo `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetNewAddressResponse) Reset() { *x = GetNewAddressResponse{} mi := &file_wallet_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetNewAddressResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetNewAddressResponse) ProtoMessage() {} func (x *GetNewAddressResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetNewAddressResponse.ProtoReflect.Descriptor instead. func (*GetNewAddressResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{2} } func (x *GetNewAddressResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetNewAddressResponse) GetAddr() *AddressInfo { if x != nil { return x.Addr } return nil } // Request message for restoring a wallet from mnemonic (seed phrase). type RestoreWalletRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name for the restored wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The mnemonic (seed phrase) for wallet recovery. Mnemonic string `protobuf:"bytes,2,opt,name=mnemonic,proto3" json:"mnemonic,omitempty"` // Password to secure the restored wallet. Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RestoreWalletRequest) Reset() { *x = RestoreWalletRequest{} mi := &file_wallet_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RestoreWalletRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RestoreWalletRequest) ProtoMessage() {} func (x *RestoreWalletRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RestoreWalletRequest.ProtoReflect.Descriptor instead. func (*RestoreWalletRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{3} } func (x *RestoreWalletRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *RestoreWalletRequest) GetMnemonic() string { if x != nil { return x.Mnemonic } return "" } func (x *RestoreWalletRequest) GetPassword() string { if x != nil { return x.Password } return "" } // Response message confirming wallet restoration. type RestoreWalletResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the restored wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RestoreWalletResponse) Reset() { *x = RestoreWalletResponse{} mi := &file_wallet_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RestoreWalletResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RestoreWalletResponse) ProtoMessage() {} func (x *RestoreWalletResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RestoreWalletResponse.ProtoReflect.Descriptor instead. func (*RestoreWalletResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{4} } func (x *RestoreWalletResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Request message for creating a new wallet. type CreateWalletRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name for the new wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Password to secure the new wallet. Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CreateWalletRequest) Reset() { *x = CreateWalletRequest{} mi := &file_wallet_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CreateWalletRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*CreateWalletRequest) ProtoMessage() {} func (x *CreateWalletRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CreateWalletRequest.ProtoReflect.Descriptor instead. func (*CreateWalletRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{5} } func (x *CreateWalletRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *CreateWalletRequest) GetPassword() string { if x != nil { return x.Password } return "" } // Response message contains wallet recovery mnemonic (seed phrase). type CreateWalletResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name for the new wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The mnemonic (seed phrase) for wallet recovery. Mnemonic string `protobuf:"bytes,2,opt,name=mnemonic,proto3" json:"mnemonic,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CreateWalletResponse) Reset() { *x = CreateWalletResponse{} mi := &file_wallet_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CreateWalletResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*CreateWalletResponse) ProtoMessage() {} func (x *CreateWalletResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CreateWalletResponse.ProtoReflect.Descriptor instead. func (*CreateWalletResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{6} } func (x *CreateWalletResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *CreateWalletResponse) GetMnemonic() string { if x != nil { return x.Mnemonic } return "" } // Request message for loading an existing wallet. // Deprecated: It will be removed in a future version. type LoadWalletRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to load. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *LoadWalletRequest) Reset() { *x = LoadWalletRequest{} mi := &file_wallet_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *LoadWalletRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*LoadWalletRequest) ProtoMessage() {} func (x *LoadWalletRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LoadWalletRequest.ProtoReflect.Descriptor instead. func (*LoadWalletRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{7} } func (x *LoadWalletRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Response message confirming wallet loaded. // Deprecated: It will be removed in a future version. type LoadWalletResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the loaded wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *LoadWalletResponse) Reset() { *x = LoadWalletResponse{} mi := &file_wallet_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *LoadWalletResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*LoadWalletResponse) ProtoMessage() {} func (x *LoadWalletResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LoadWalletResponse.ProtoReflect.Descriptor instead. func (*LoadWalletResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{8} } func (x *LoadWalletResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Request message for unloading a wallet. // Deprecated: It will be removed in a future version. type UnloadWalletRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to unload. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *UnloadWalletRequest) Reset() { *x = UnloadWalletRequest{} mi := &file_wallet_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *UnloadWalletRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*UnloadWalletRequest) ProtoMessage() {} func (x *UnloadWalletRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UnloadWalletRequest.ProtoReflect.Descriptor instead. func (*UnloadWalletRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{9} } func (x *UnloadWalletRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Response message confirming wallet unloading. // Deprecated: It will be removed in a future version. type UnloadWalletResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the unloaded wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *UnloadWalletResponse) Reset() { *x = UnloadWalletResponse{} mi := &file_wallet_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *UnloadWalletResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*UnloadWalletResponse) ProtoMessage() {} func (x *UnloadWalletResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UnloadWalletResponse.ProtoReflect.Descriptor instead. func (*UnloadWalletResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{10} } func (x *UnloadWalletResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Request message for obtaining the validator address associated with a public key. type GetValidatorAddressRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The public key of the validator. PublicKey string `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorAddressRequest) Reset() { *x = GetValidatorAddressRequest{} mi := &file_wallet_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorAddressRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorAddressRequest) ProtoMessage() {} func (x *GetValidatorAddressRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorAddressRequest.ProtoReflect.Descriptor instead. func (*GetValidatorAddressRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{11} } func (x *GetValidatorAddressRequest) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } // Response message containing the validator address corresponding to a public key. type GetValidatorAddressResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The validator address associated with the public key. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetValidatorAddressResponse) Reset() { *x = GetValidatorAddressResponse{} mi := &file_wallet_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetValidatorAddressResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetValidatorAddressResponse) ProtoMessage() {} func (x *GetValidatorAddressResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetValidatorAddressResponse.ProtoReflect.Descriptor instead. func (*GetValidatorAddressResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{12} } func (x *GetValidatorAddressResponse) GetAddress() string { if x != nil { return x.Address } return "" } // Request message for signing a raw transaction. type SignRawTransactionRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet used for signing. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The raw transaction data to be signed. RawTransaction string `protobuf:"bytes,2,opt,name=raw_transaction,json=rawTransaction,proto3" json:"raw_transaction,omitempty"` // Wallet password required for signing. Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignRawTransactionRequest) Reset() { *x = SignRawTransactionRequest{} mi := &file_wallet_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignRawTransactionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignRawTransactionRequest) ProtoMessage() {} func (x *SignRawTransactionRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignRawTransactionRequest.ProtoReflect.Descriptor instead. func (*SignRawTransactionRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{13} } func (x *SignRawTransactionRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *SignRawTransactionRequest) GetRawTransaction() string { if x != nil { return x.RawTransaction } return "" } func (x *SignRawTransactionRequest) GetPassword() string { if x != nil { return x.Password } return "" } // Response message contains the transaction ID and signed raw transaction. type SignRawTransactionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The ID of the signed transaction. TransactionId string `protobuf:"bytes,1,opt,name=transaction_id,json=transactionId,proto3" json:"transaction_id,omitempty"` // The signed raw transaction data. SignedRawTransaction string `protobuf:"bytes,2,opt,name=signed_raw_transaction,json=signedRawTransaction,proto3" json:"signed_raw_transaction,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignRawTransactionResponse) Reset() { *x = SignRawTransactionResponse{} mi := &file_wallet_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignRawTransactionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignRawTransactionResponse) ProtoMessage() {} func (x *SignRawTransactionResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignRawTransactionResponse.ProtoReflect.Descriptor instead. func (*SignRawTransactionResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{14} } func (x *SignRawTransactionResponse) GetTransactionId() string { if x != nil { return x.TransactionId } return "" } func (x *SignRawTransactionResponse) GetSignedRawTransaction() string { if x != nil { return x.SignedRawTransaction } return "" } // Request message for obtaining the total available balance of a wallet. type GetTotalBalanceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to get the total balance. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTotalBalanceRequest) Reset() { *x = GetTotalBalanceRequest{} mi := &file_wallet_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTotalBalanceRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTotalBalanceRequest) ProtoMessage() {} func (x *GetTotalBalanceRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTotalBalanceRequest.ProtoReflect.Descriptor instead. func (*GetTotalBalanceRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{15} } func (x *GetTotalBalanceRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Response message contains the total available balance of the wallet. type GetTotalBalanceResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the queried wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The total balance of the wallet in NanoPAC. TotalBalance int64 `protobuf:"varint,2,opt,name=total_balance,json=totalBalance,proto3" json:"total_balance,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTotalBalanceResponse) Reset() { *x = GetTotalBalanceResponse{} mi := &file_wallet_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTotalBalanceResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTotalBalanceResponse) ProtoMessage() {} func (x *GetTotalBalanceResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTotalBalanceResponse.ProtoReflect.Descriptor instead. func (*GetTotalBalanceResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{16} } func (x *GetTotalBalanceResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetTotalBalanceResponse) GetTotalBalance() int64 { if x != nil { return x.TotalBalance } return 0 } // Request message to sign an arbitrary message. type SignMessageRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to sign with. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Wallet password required for signing. Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` // The address whose private key should be used for signing the message. Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` // The arbitrary message to be signed. Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignMessageRequest) Reset() { *x = SignMessageRequest{} mi := &file_wallet_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignMessageRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignMessageRequest) ProtoMessage() {} func (x *SignMessageRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignMessageRequest.ProtoReflect.Descriptor instead. func (*SignMessageRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{17} } func (x *SignMessageRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *SignMessageRequest) GetPassword() string { if x != nil { return x.Password } return "" } func (x *SignMessageRequest) GetAddress() string { if x != nil { return x.Address } return "" } func (x *SignMessageRequest) GetMessage() string { if x != nil { return x.Message } return "" } // Response message contains message signature. type SignMessageResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The signature in hexadecimal format. Signature string `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SignMessageResponse) Reset() { *x = SignMessageResponse{} mi := &file_wallet_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SignMessageResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*SignMessageResponse) ProtoMessage() {} func (x *SignMessageResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SignMessageResponse.ProtoReflect.Descriptor instead. func (*SignMessageResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{18} } func (x *SignMessageResponse) GetSignature() string { if x != nil { return x.Signature } return "" } // Request message for obtaining the total stake of a wallet. type GetTotalStakeRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to get the total stake. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTotalStakeRequest) Reset() { *x = GetTotalStakeRequest{} mi := &file_wallet_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTotalStakeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTotalStakeRequest) ProtoMessage() {} func (x *GetTotalStakeRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTotalStakeRequest.ProtoReflect.Descriptor instead. func (*GetTotalStakeRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{19} } func (x *GetTotalStakeRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Response message contains the total stake of the wallet. type GetTotalStakeResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the queried wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The total stake amount in NanoPAC. TotalStake int64 `protobuf:"varint,2,opt,name=total_stake,json=totalStake,proto3" json:"total_stake,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetTotalStakeResponse) Reset() { *x = GetTotalStakeResponse{} mi := &file_wallet_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetTotalStakeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTotalStakeResponse) ProtoMessage() {} func (x *GetTotalStakeResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTotalStakeResponse.ProtoReflect.Descriptor instead. func (*GetTotalStakeResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{20} } func (x *GetTotalStakeResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetTotalStakeResponse) GetTotalStake() int64 { if x != nil { return x.TotalStake } return 0 } // Request message for getting address information. type GetAddressInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet containing the address. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The address to query. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetAddressInfoRequest) Reset() { *x = GetAddressInfoRequest{} mi := &file_wallet_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetAddressInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetAddressInfoRequest) ProtoMessage() {} func (x *GetAddressInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetAddressInfoRequest.ProtoReflect.Descriptor instead. func (*GetAddressInfoRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{21} } func (x *GetAddressInfoRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetAddressInfoRequest) GetAddress() string { if x != nil { return x.Address } return "" } // Response message contains address details. type GetAddressInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet containing the address. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Detailed information about the address. Addr *AddressInfo `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetAddressInfoResponse) Reset() { *x = GetAddressInfoResponse{} mi := &file_wallet_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetAddressInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetAddressInfoResponse) ProtoMessage() {} func (x *GetAddressInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetAddressInfoResponse.ProtoReflect.Descriptor instead. func (*GetAddressInfoResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{22} } func (x *GetAddressInfoResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetAddressInfoResponse) GetAddr() *AddressInfo { if x != nil { return x.Addr } return nil } // Request message for setting address label. type SetAddressLabelRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet containing the address. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Wallet password required for modification. Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` // The address to label. Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` // The new label for the address. Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SetAddressLabelRequest) Reset() { *x = SetAddressLabelRequest{} mi := &file_wallet_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SetAddressLabelRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SetAddressLabelRequest) ProtoMessage() {} func (x *SetAddressLabelRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SetAddressLabelRequest.ProtoReflect.Descriptor instead. func (*SetAddressLabelRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{23} } func (x *SetAddressLabelRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *SetAddressLabelRequest) GetPassword() string { if x != nil { return x.Password } return "" } func (x *SetAddressLabelRequest) GetAddress() string { if x != nil { return x.Address } return "" } func (x *SetAddressLabelRequest) GetLabel() string { if x != nil { return x.Label } return "" } // Response message for updated address label. type SetAddressLabelResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet where the address label was updated. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The address where the label was updated. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` // The new label for the address. Label string `protobuf:"bytes,3,opt,name=label,proto3" json:"label,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SetAddressLabelResponse) Reset() { *x = SetAddressLabelResponse{} mi := &file_wallet_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SetAddressLabelResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*SetAddressLabelResponse) ProtoMessage() {} func (x *SetAddressLabelResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SetAddressLabelResponse.ProtoReflect.Descriptor instead. func (*SetAddressLabelResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{24} } func (x *SetAddressLabelResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *SetAddressLabelResponse) GetAddress() string { if x != nil { return x.Address } return "" } func (x *SetAddressLabelResponse) GetLabel() string { if x != nil { return x.Label } return "" } // Request message for listing wallets. type ListWalletsRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListWalletsRequest) Reset() { *x = ListWalletsRequest{} mi := &file_wallet_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListWalletsRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListWalletsRequest) ProtoMessage() {} func (x *ListWalletsRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListWalletsRequest.ProtoReflect.Descriptor instead. func (*ListWalletsRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{25} } // Response message contains wallet names. type ListWalletsResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Array of wallet names. Wallets []string `protobuf:"bytes,1,rep,name=wallets,proto3" json:"wallets,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListWalletsResponse) Reset() { *x = ListWalletsResponse{} mi := &file_wallet_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListWalletsResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListWalletsResponse) ProtoMessage() {} func (x *ListWalletsResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListWalletsResponse.ProtoReflect.Descriptor instead. func (*ListWalletsResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{26} } func (x *ListWalletsResponse) GetWallets() []string { if x != nil { return x.Wallets } return nil } // Request message for getting wallet information. type GetWalletInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to query. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetWalletInfoRequest) Reset() { *x = GetWalletInfoRequest{} mi := &file_wallet_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetWalletInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWalletInfoRequest) ProtoMessage() {} func (x *GetWalletInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWalletInfoRequest.ProtoReflect.Descriptor instead. func (*GetWalletInfoRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{27} } func (x *GetWalletInfoRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Response message contains wallet details. type GetWalletInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The wallet format version. Version int32 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // The network the wallet is connected to (e.g., mainnet, testnet). Network string `protobuf:"bytes,3,opt,name=network,proto3" json:"network,omitempty"` // Indicates if the wallet is encrypted. Encrypted bool `protobuf:"varint,4,opt,name=encrypted,proto3" json:"encrypted,omitempty"` // A unique identifier of the wallet. Uuid string `protobuf:"bytes,5,opt,name=uuid,proto3" json:"uuid,omitempty"` // Unix timestamp of wallet creation. CreatedAt int64 `protobuf:"varint,6,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` // The default fee of the wallet. DefaultFee int64 `protobuf:"varint,7,opt,name=default_fee,json=defaultFee,proto3" json:"default_fee,omitempty"` // The storage driver used by the wallet (e.g., SQLite, Legacy JSON ). Driver string `protobuf:"bytes,8,opt,name=driver,proto3" json:"driver,omitempty"` // Path to the wallet file or storage location. Path string `protobuf:"bytes,9,opt,name=path,proto3" json:"path,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetWalletInfoResponse) Reset() { *x = GetWalletInfoResponse{} mi := &file_wallet_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetWalletInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWalletInfoResponse) ProtoMessage() {} func (x *GetWalletInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWalletInfoResponse.ProtoReflect.Descriptor instead. func (*GetWalletInfoResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{28} } func (x *GetWalletInfoResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetWalletInfoResponse) GetVersion() int32 { if x != nil { return x.Version } return 0 } func (x *GetWalletInfoResponse) GetNetwork() string { if x != nil { return x.Network } return "" } func (x *GetWalletInfoResponse) GetEncrypted() bool { if x != nil { return x.Encrypted } return false } func (x *GetWalletInfoResponse) GetUuid() string { if x != nil { return x.Uuid } return "" } func (x *GetWalletInfoResponse) GetCreatedAt() int64 { if x != nil { return x.CreatedAt } return 0 } func (x *GetWalletInfoResponse) GetDefaultFee() int64 { if x != nil { return x.DefaultFee } return 0 } func (x *GetWalletInfoResponse) GetDriver() string { if x != nil { return x.Driver } return "" } func (x *GetWalletInfoResponse) GetPath() string { if x != nil { return x.Path } return "" } // Request message for listing wallet addresses. type ListAddressesRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the queried wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Filter addresses by their types. If empty, all address types are included. AddressTypes []AddressType `protobuf:"varint,2,rep,packed,name=address_types,json=addressTypes,proto3,enum=pactus.AddressType" json:"address_types,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListAddressesRequest) Reset() { *x = ListAddressesRequest{} mi := &file_wallet_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListAddressesRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListAddressesRequest) ProtoMessage() {} func (x *ListAddressesRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListAddressesRequest.ProtoReflect.Descriptor instead. func (*ListAddressesRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{29} } func (x *ListAddressesRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *ListAddressesRequest) GetAddressTypes() []AddressType { if x != nil { return x.AddressTypes } return nil } // Response message contains wallet addresses. type ListAddressesResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the queried wallet. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // List of all addresses in the wallet with their details. Addrs []*AddressInfo `protobuf:"bytes,2,rep,name=addrs,proto3" json:"addrs,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListAddressesResponse) Reset() { *x = ListAddressesResponse{} mi := &file_wallet_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListAddressesResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListAddressesResponse) ProtoMessage() {} func (x *ListAddressesResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListAddressesResponse.ProtoReflect.Descriptor instead. func (*ListAddressesResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{30} } func (x *ListAddressesResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *ListAddressesResponse) GetAddrs() []*AddressInfo { if x != nil { return x.Addrs } return nil } // Request message for updating wallet password. type UpdatePasswordRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet whose password will be updated. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The current wallet password. OldPassword string `protobuf:"bytes,2,opt,name=old_password,json=oldPassword,proto3" json:"old_password,omitempty"` // The new wallet password. NewPassword string `protobuf:"bytes,3,opt,name=new_password,json=newPassword,proto3" json:"new_password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *UpdatePasswordRequest) Reset() { *x = UpdatePasswordRequest{} mi := &file_wallet_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *UpdatePasswordRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdatePasswordRequest) ProtoMessage() {} func (x *UpdatePasswordRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UpdatePasswordRequest.ProtoReflect.Descriptor instead. func (*UpdatePasswordRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{31} } func (x *UpdatePasswordRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *UpdatePasswordRequest) GetOldPassword() string { if x != nil { return x.OldPassword } return "" } func (x *UpdatePasswordRequest) GetNewPassword() string { if x != nil { return x.NewPassword } return "" } // Response message confirming wallet password update. type UpdatePasswordResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet whose password was updated. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *UpdatePasswordResponse) Reset() { *x = UpdatePasswordResponse{} mi := &file_wallet_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *UpdatePasswordResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdatePasswordResponse) ProtoMessage() {} func (x *UpdatePasswordResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UpdatePasswordResponse.ProtoReflect.Descriptor instead. func (*UpdatePasswordResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{32} } func (x *UpdatePasswordResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } // WalletTransactionInfo contains information about a transaction in a wallet. type WalletTransactionInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // A sequence number for the transaction in the wallet. No int64 `protobuf:"varint,1,opt,name=no,proto3" json:"no,omitempty"` // The unique ID of the transaction. TxId string `protobuf:"bytes,2,opt,name=tx_id,json=txId,proto3" json:"tx_id,omitempty"` // The sender's address. Sender string `protobuf:"bytes,3,opt,name=sender,proto3" json:"sender,omitempty"` // The receiver's address. Receiver string `protobuf:"bytes,4,opt,name=receiver,proto3" json:"receiver,omitempty"` // The direction of the transaction relative to the wallet. Direction TxDirection `protobuf:"varint,5,opt,name=direction,proto3,enum=pactus.TxDirection" json:"direction,omitempty"` // The amount involved in the transaction in NanoPAC. Amount int64 `protobuf:"varint,6,opt,name=amount,proto3" json:"amount,omitempty"` // The transaction fee in NanoPAC. Fee int64 `protobuf:"varint,7,opt,name=fee,proto3" json:"fee,omitempty"` // A memo string for the transaction. Memo string `protobuf:"bytes,8,opt,name=memo,proto3" json:"memo,omitempty"` // The current status of the transaction. Status TransactionStatus `protobuf:"varint,9,opt,name=status,proto3,enum=pactus.TransactionStatus" json:"status,omitempty"` // The block height containing the transaction. BlockHeight uint32 `protobuf:"varint,10,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` // The type of transaction payload. PayloadType PayloadType `protobuf:"varint,11,opt,name=payload_type,json=payloadType,proto3,enum=pactus.PayloadType" json:"payload_type,omitempty"` // The raw transaction data. Data []byte `protobuf:"bytes,12,opt,name=data,proto3" json:"data,omitempty"` // A comment associated with the transaction in the wallet. Comment string `protobuf:"bytes,13,opt,name=comment,proto3" json:"comment,omitempty"` // Unix timestamp of when the transaction was created. CreatedAt int64 `protobuf:"varint,14,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` // Unix timestamp of when the transaction was last updated. UpdatedAt int64 `protobuf:"varint,15,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *WalletTransactionInfo) Reset() { *x = WalletTransactionInfo{} mi := &file_wallet_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *WalletTransactionInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*WalletTransactionInfo) ProtoMessage() {} func (x *WalletTransactionInfo) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WalletTransactionInfo.ProtoReflect.Descriptor instead. func (*WalletTransactionInfo) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{33} } func (x *WalletTransactionInfo) GetNo() int64 { if x != nil { return x.No } return 0 } func (x *WalletTransactionInfo) GetTxId() string { if x != nil { return x.TxId } return "" } func (x *WalletTransactionInfo) GetSender() string { if x != nil { return x.Sender } return "" } func (x *WalletTransactionInfo) GetReceiver() string { if x != nil { return x.Receiver } return "" } func (x *WalletTransactionInfo) GetDirection() TxDirection { if x != nil { return x.Direction } return TxDirection_TX_DIRECTION_ANY } func (x *WalletTransactionInfo) GetAmount() int64 { if x != nil { return x.Amount } return 0 } func (x *WalletTransactionInfo) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *WalletTransactionInfo) GetMemo() string { if x != nil { return x.Memo } return "" } func (x *WalletTransactionInfo) GetStatus() TransactionStatus { if x != nil { return x.Status } return TransactionStatus_TRANSACTION_STATUS_PENDING } func (x *WalletTransactionInfo) GetBlockHeight() uint32 { if x != nil { return x.BlockHeight } return 0 } func (x *WalletTransactionInfo) GetPayloadType() PayloadType { if x != nil { return x.PayloadType } return PayloadType_PAYLOAD_TYPE_UNSPECIFIED } func (x *WalletTransactionInfo) GetData() []byte { if x != nil { return x.Data } return nil } func (x *WalletTransactionInfo) GetComment() string { if x != nil { return x.Comment } return "" } func (x *WalletTransactionInfo) GetCreatedAt() int64 { if x != nil { return x.CreatedAt } return 0 } func (x *WalletTransactionInfo) GetUpdatedAt() int64 { if x != nil { return x.UpdatedAt } return 0 } // Request message for listing transactions of a wallet, optionally filtered by a specific address. type ListTransactionsRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to query transactions for. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Optional: The address to filter transactions. // If empty or set to '*', transactions for all addresses in the wallet are included. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` // Filter transactions by direction relative to the wallet. // Defaults to any direction if not set. Direction TxDirection `protobuf:"varint,3,opt,name=direction,proto3,enum=pactus.TxDirection" json:"direction,omitempty"` // Optional: The maximum number of transactions to return. // Defaults to 10 if not set. Count int32 `protobuf:"varint,4,opt,name=count,proto3" json:"count,omitempty"` // Optional: The number of transactions to skip (for pagination). // Defaults to 0 if not set. Skip int32 `protobuf:"varint,5,opt,name=skip,proto3" json:"skip,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListTransactionsRequest) Reset() { *x = ListTransactionsRequest{} mi := &file_wallet_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListTransactionsRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListTransactionsRequest) ProtoMessage() {} func (x *ListTransactionsRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListTransactionsRequest.ProtoReflect.Descriptor instead. func (*ListTransactionsRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{34} } func (x *ListTransactionsRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *ListTransactionsRequest) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ListTransactionsRequest) GetDirection() TxDirection { if x != nil { return x.Direction } return TxDirection_TX_DIRECTION_ANY } func (x *ListTransactionsRequest) GetCount() int32 { if x != nil { return x.Count } return 0 } func (x *ListTransactionsRequest) GetSkip() int32 { if x != nil { return x.Skip } return 0 } // Response message containing a list of transactions. type ListTransactionsResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet queried. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // List of transactions for the wallet, filtered by the specified address if provided. Txs []*WalletTransactionInfo `protobuf:"bytes,2,rep,name=txs,proto3" json:"txs,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ListTransactionsResponse) Reset() { *x = ListTransactionsResponse{} mi := &file_wallet_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ListTransactionsResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListTransactionsResponse) ProtoMessage() {} func (x *ListTransactionsResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListTransactionsResponse.ProtoReflect.Descriptor instead. func (*ListTransactionsResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{35} } func (x *ListTransactionsResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *ListTransactionsResponse) GetTxs() []*WalletTransactionInfo { if x != nil { return x.Txs } return nil } // Request message for setting default fee. type SetDefaultFeeRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to set the default fee. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // The default fee amount in NanoPAC. Amount int64 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SetDefaultFeeRequest) Reset() { *x = SetDefaultFeeRequest{} mi := &file_wallet_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SetDefaultFeeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SetDefaultFeeRequest) ProtoMessage() {} func (x *SetDefaultFeeRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SetDefaultFeeRequest.ProtoReflect.Descriptor instead. func (*SetDefaultFeeRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{36} } func (x *SetDefaultFeeRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *SetDefaultFeeRequest) GetAmount() int64 { if x != nil { return x.Amount } return 0 } // Response message for updated default fee. type SetDefaultFeeResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet where the default fee was updated. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SetDefaultFeeResponse) Reset() { *x = SetDefaultFeeResponse{} mi := &file_wallet_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SetDefaultFeeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*SetDefaultFeeResponse) ProtoMessage() {} func (x *SetDefaultFeeResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SetDefaultFeeResponse.ProtoReflect.Descriptor instead. func (*SetDefaultFeeResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{37} } func (x *SetDefaultFeeResponse) GetWalletName() string { if x != nil { return x.WalletName } return "" } // Request message for getting mnemonic. type GetMnemonicRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet to get the mnemonic. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Wallet password. Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetMnemonicRequest) Reset() { *x = GetMnemonicRequest{} mi := &file_wallet_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetMnemonicRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetMnemonicRequest) ProtoMessage() {} func (x *GetMnemonicRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetMnemonicRequest.ProtoReflect.Descriptor instead. func (*GetMnemonicRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{38} } func (x *GetMnemonicRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetMnemonicRequest) GetPassword() string { if x != nil { return x.Password } return "" } // Response message contains mnemonic. type GetMnemonicResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The mnemonic (seed phrase). Mnemonic string `protobuf:"bytes,1,opt,name=mnemonic,proto3" json:"mnemonic,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetMnemonicResponse) Reset() { *x = GetMnemonicResponse{} mi := &file_wallet_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetMnemonicResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetMnemonicResponse) ProtoMessage() {} func (x *GetMnemonicResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetMnemonicResponse.ProtoReflect.Descriptor instead. func (*GetMnemonicResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{39} } func (x *GetMnemonicResponse) GetMnemonic() string { if x != nil { return x.Mnemonic } return "" } // Request message for getting private key. type GetPrivateKeyRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The name of the wallet containing the address. WalletName string `protobuf:"bytes,1,opt,name=wallet_name,json=walletName,proto3" json:"wallet_name,omitempty"` // Wallet password. Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` // The address to get the private key. Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetPrivateKeyRequest) Reset() { *x = GetPrivateKeyRequest{} mi := &file_wallet_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetPrivateKeyRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetPrivateKeyRequest) ProtoMessage() {} func (x *GetPrivateKeyRequest) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[40] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetPrivateKeyRequest.ProtoReflect.Descriptor instead. func (*GetPrivateKeyRequest) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{40} } func (x *GetPrivateKeyRequest) GetWalletName() string { if x != nil { return x.WalletName } return "" } func (x *GetPrivateKeyRequest) GetPassword() string { if x != nil { return x.Password } return "" } func (x *GetPrivateKeyRequest) GetAddress() string { if x != nil { return x.Address } return "" } // Response message contains private key. type GetPrivateKeyResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The private key in hexadecimal format. PrivateKey string `protobuf:"bytes,1,opt,name=private_key,json=privateKey,proto3" json:"private_key,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetPrivateKeyResponse) Reset() { *x = GetPrivateKeyResponse{} mi := &file_wallet_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetPrivateKeyResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetPrivateKeyResponse) ProtoMessage() {} func (x *GetPrivateKeyResponse) ProtoReflect() protoreflect.Message { mi := &file_wallet_proto_msgTypes[41] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetPrivateKeyResponse.ProtoReflect.Descriptor instead. func (*GetPrivateKeyResponse) Descriptor() ([]byte, []int) { return file_wallet_proto_rawDescGZIP(), []int{41} } func (x *GetPrivateKeyResponse) GetPrivateKey() string { if x != nil { return x.PrivateKey } return "" } var File_wallet_proto protoreflect.FileDescriptor const file_wallet_proto_rawDesc = "" + "\n" + "\fwallet.proto\x12\x06pactus\x1a\x11transaction.proto\"p\n" + "\vAddressInfo\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\x12\x1d\n" + "\n" + "public_key\x18\x02 \x01(\tR\tpublicKey\x12\x14\n" + "\x05label\x18\x03 \x01(\tR\x05label\x12\x12\n" + "\x04path\x18\x04 \x01(\tR\x04path\"\xa1\x01\n" + "\x14GetNewAddressRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x126\n" + "\faddress_type\x18\x02 \x01(\x0e2\x13.pactus.AddressTypeR\vaddressType\x12\x14\n" + "\x05label\x18\x03 \x01(\tR\x05label\x12\x1a\n" + "\bpassword\x18\x04 \x01(\tR\bpassword\"a\n" + "\x15GetNewAddressResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12'\n" + "\x04addr\x18\x02 \x01(\v2\x13.pactus.AddressInfoR\x04addr\"o\n" + "\x14RestoreWalletRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bmnemonic\x18\x02 \x01(\tR\bmnemonic\x12\x1a\n" + "\bpassword\x18\x03 \x01(\tR\bpassword\"8\n" + "\x15RestoreWalletResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"R\n" + "\x13CreateWalletRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bpassword\x18\x02 \x01(\tR\bpassword\"S\n" + "\x14CreateWalletResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bmnemonic\x18\x02 \x01(\tR\bmnemonic\"4\n" + "\x11LoadWalletRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"5\n" + "\x12LoadWalletResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"6\n" + "\x13UnloadWalletRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"7\n" + "\x14UnloadWalletResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\";\n" + "\x1aGetValidatorAddressRequest\x12\x1d\n" + "\n" + "public_key\x18\x01 \x01(\tR\tpublicKey\"7\n" + "\x1bGetValidatorAddressResponse\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\"\x81\x01\n" + "\x19SignRawTransactionRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12'\n" + "\x0fraw_transaction\x18\x02 \x01(\tR\x0erawTransaction\x12\x1a\n" + "\bpassword\x18\x03 \x01(\tR\bpassword\"y\n" + "\x1aSignRawTransactionResponse\x12%\n" + "\x0etransaction_id\x18\x01 \x01(\tR\rtransactionId\x124\n" + "\x16signed_raw_transaction\x18\x02 \x01(\tR\x14signedRawTransaction\"9\n" + "\x16GetTotalBalanceRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"_\n" + "\x17GetTotalBalanceResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12#\n" + "\rtotal_balance\x18\x02 \x01(\x03R\ftotalBalance\"\x85\x01\n" + "\x12SignMessageRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bpassword\x18\x02 \x01(\tR\bpassword\x12\x18\n" + "\aaddress\x18\x03 \x01(\tR\aaddress\x12\x18\n" + "\amessage\x18\x04 \x01(\tR\amessage\"3\n" + "\x13SignMessageResponse\x12\x1c\n" + "\tsignature\x18\x01 \x01(\tR\tsignature\"7\n" + "\x14GetTotalStakeRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"Y\n" + "\x15GetTotalStakeResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1f\n" + "\vtotal_stake\x18\x02 \x01(\x03R\n" + "totalStake\"R\n" + "\x15GetAddressInfoRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x18\n" + "\aaddress\x18\x02 \x01(\tR\aaddress\"b\n" + "\x16GetAddressInfoResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12'\n" + "\x04addr\x18\x02 \x01(\v2\x13.pactus.AddressInfoR\x04addr\"\x85\x01\n" + "\x16SetAddressLabelRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bpassword\x18\x02 \x01(\tR\bpassword\x12\x18\n" + "\aaddress\x18\x03 \x01(\tR\aaddress\x12\x14\n" + "\x05label\x18\x04 \x01(\tR\x05label\"j\n" + "\x17SetAddressLabelResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x18\n" + "\aaddress\x18\x02 \x01(\tR\aaddress\x12\x14\n" + "\x05label\x18\x03 \x01(\tR\x05label\"\x14\n" + "\x12ListWalletsRequest\"/\n" + "\x13ListWalletsResponse\x12\x18\n" + "\awallets\x18\x01 \x03(\tR\awallets\"7\n" + "\x14GetWalletInfoRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"\x8a\x02\n" + "\x15GetWalletInfoResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x18\n" + "\aversion\x18\x02 \x01(\x05R\aversion\x12\x18\n" + "\anetwork\x18\x03 \x01(\tR\anetwork\x12\x1c\n" + "\tencrypted\x18\x04 \x01(\bR\tencrypted\x12\x12\n" + "\x04uuid\x18\x05 \x01(\tR\x04uuid\x12\x1d\n" + "\n" + "created_at\x18\x06 \x01(\x03R\tcreatedAt\x12\x1f\n" + "\vdefault_fee\x18\a \x01(\x03R\n" + "defaultFee\x12\x16\n" + "\x06driver\x18\b \x01(\tR\x06driver\x12\x12\n" + "\x04path\x18\t \x01(\tR\x04path\"q\n" + "\x14ListAddressesRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x128\n" + "\raddress_types\x18\x02 \x03(\x0e2\x13.pactus.AddressTypeR\faddressTypes\"c\n" + "\x15ListAddressesResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12)\n" + "\x05addrs\x18\x02 \x03(\v2\x13.pactus.AddressInfoR\x05addrs\"~\n" + "\x15UpdatePasswordRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12!\n" + "\fold_password\x18\x02 \x01(\tR\voldPassword\x12!\n" + "\fnew_password\x18\x03 \x01(\tR\vnewPassword\"9\n" + "\x16UpdatePasswordResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"\xdb\x03\n" + "\x15WalletTransactionInfo\x12\x0e\n" + "\x02no\x18\x01 \x01(\x03R\x02no\x12\x13\n" + "\x05tx_id\x18\x02 \x01(\tR\x04txId\x12\x16\n" + "\x06sender\x18\x03 \x01(\tR\x06sender\x12\x1a\n" + "\breceiver\x18\x04 \x01(\tR\breceiver\x121\n" + "\tdirection\x18\x05 \x01(\x0e2\x13.pactus.TxDirectionR\tdirection\x12\x16\n" + "\x06amount\x18\x06 \x01(\x03R\x06amount\x12\x10\n" + "\x03fee\x18\a \x01(\x03R\x03fee\x12\x12\n" + "\x04memo\x18\b \x01(\tR\x04memo\x121\n" + "\x06status\x18\t \x01(\x0e2\x19.pactus.TransactionStatusR\x06status\x12!\n" + "\fblock_height\x18\n" + " \x01(\rR\vblockHeight\x126\n" + "\fpayload_type\x18\v \x01(\x0e2\x13.pactus.PayloadTypeR\vpayloadType\x12\x12\n" + "\x04data\x18\f \x01(\fR\x04data\x12\x18\n" + "\acomment\x18\r \x01(\tR\acomment\x12\x1d\n" + "\n" + "created_at\x18\x0e \x01(\x03R\tcreatedAt\x12\x1d\n" + "\n" + "updated_at\x18\x0f \x01(\x03R\tupdatedAt\"\xb1\x01\n" + "\x17ListTransactionsRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x18\n" + "\aaddress\x18\x02 \x01(\tR\aaddress\x121\n" + "\tdirection\x18\x03 \x01(\x0e2\x13.pactus.TxDirectionR\tdirection\x12\x14\n" + "\x05count\x18\x04 \x01(\x05R\x05count\x12\x12\n" + "\x04skip\x18\x05 \x01(\x05R\x04skip\"l\n" + "\x18ListTransactionsResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12/\n" + "\x03txs\x18\x02 \x03(\v2\x1d.pactus.WalletTransactionInfoR\x03txs\"O\n" + "\x14SetDefaultFeeRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x16\n" + "\x06amount\x18\x02 \x01(\x03R\x06amount\"8\n" + "\x15SetDefaultFeeResponse\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\"Q\n" + "\x12GetMnemonicRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bpassword\x18\x02 \x01(\tR\bpassword\"1\n" + "\x13GetMnemonicResponse\x12\x1a\n" + "\bmnemonic\x18\x01 \x01(\tR\bmnemonic\"m\n" + "\x14GetPrivateKeyRequest\x12\x1f\n" + "\vwallet_name\x18\x01 \x01(\tR\n" + "walletName\x12\x1a\n" + "\bpassword\x18\x02 \x01(\tR\bpassword\x12\x18\n" + "\aaddress\x18\x03 \x01(\tR\aaddress\"8\n" + "\x15GetPrivateKeyResponse\x12\x1f\n" + "\vprivate_key\x18\x01 \x01(\tR\n" + "privateKey*\x84\x01\n" + "\vAddressType\x12\x19\n" + "\x15ADDRESS_TYPE_TREASURY\x10\x00\x12\x1a\n" + "\x16ADDRESS_TYPE_VALIDATOR\x10\x01\x12\x1c\n" + "\x18ADDRESS_TYPE_BLS_ACCOUNT\x10\x02\x12 \n" + "\x1cADDRESS_TYPE_ED25519_ACCOUNT\x10\x03*Y\n" + "\vTxDirection\x12\x14\n" + "\x10TX_DIRECTION_ANY\x10\x00\x12\x19\n" + "\x15TX_DIRECTION_INCOMING\x10\x01\x12\x19\n" + "\x15TX_DIRECTION_OUTGOING\x10\x02*}\n" + "\x11TransactionStatus\x12\x1e\n" + "\x1aTRANSACTION_STATUS_PENDING\x10\x00\x12 \n" + "\x1cTRANSACTION_STATUS_CONFIRMED\x10\x01\x12&\n" + "\x19TRANSACTION_STATUS_FAILED\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\x012\xbb\f\n" + "\x06Wallet\x12I\n" + "\fCreateWallet\x12\x1b.pactus.CreateWalletRequest\x1a\x1c.pactus.CreateWalletResponse\x12L\n" + "\rRestoreWallet\x12\x1c.pactus.RestoreWalletRequest\x1a\x1d.pactus.RestoreWalletResponse\x12C\n" + "\n" + "LoadWallet\x12\x19.pactus.LoadWalletRequest\x1a\x1a.pactus.LoadWalletResponse\x12I\n" + "\fUnloadWallet\x12\x1b.pactus.UnloadWalletRequest\x1a\x1c.pactus.UnloadWalletResponse\x12F\n" + "\vListWallets\x12\x1a.pactus.ListWalletsRequest\x1a\x1b.pactus.ListWalletsResponse\x12L\n" + "\rGetWalletInfo\x12\x1c.pactus.GetWalletInfoRequest\x1a\x1d.pactus.GetWalletInfoResponse\x12O\n" + "\x0eUpdatePassword\x12\x1d.pactus.UpdatePasswordRequest\x1a\x1e.pactus.UpdatePasswordResponse\x12R\n" + "\x0fGetTotalBalance\x12\x1e.pactus.GetTotalBalanceRequest\x1a\x1f.pactus.GetTotalBalanceResponse\x12L\n" + "\rGetTotalStake\x12\x1c.pactus.GetTotalStakeRequest\x1a\x1d.pactus.GetTotalStakeResponse\x12^\n" + "\x13GetValidatorAddress\x12\".pactus.GetValidatorAddressRequest\x1a#.pactus.GetValidatorAddressResponse\x12O\n" + "\x0eGetAddressInfo\x12\x1d.pactus.GetAddressInfoRequest\x1a\x1e.pactus.GetAddressInfoResponse\x12R\n" + "\x0fSetAddressLabel\x12\x1e.pactus.SetAddressLabelRequest\x1a\x1f.pactus.SetAddressLabelResponse\x12L\n" + "\rGetNewAddress\x12\x1c.pactus.GetNewAddressRequest\x1a\x1d.pactus.GetNewAddressResponse\x12L\n" + "\rListAddresses\x12\x1c.pactus.ListAddressesRequest\x1a\x1d.pactus.ListAddressesResponse\x12F\n" + "\vSignMessage\x12\x1a.pactus.SignMessageRequest\x1a\x1b.pactus.SignMessageResponse\x12[\n" + "\x12SignRawTransaction\x12!.pactus.SignRawTransactionRequest\x1a\".pactus.SignRawTransactionResponse\x12U\n" + "\x10ListTransactions\x12\x1f.pactus.ListTransactionsRequest\x1a .pactus.ListTransactionsResponse\x12L\n" + "\rSetDefaultFee\x12\x1c.pactus.SetDefaultFeeRequest\x1a\x1d.pactus.SetDefaultFeeResponse\x12F\n" + "\vGetMnemonic\x12\x1a.pactus.GetMnemonicRequest\x1a\x1b.pactus.GetMnemonicResponse\x12L\n" + "\rGetPrivateKey\x12\x1c.pactus.GetPrivateKeyRequest\x1a\x1d.pactus.GetPrivateKeyResponseB:\n" + "\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3" var ( file_wallet_proto_rawDescOnce sync.Once file_wallet_proto_rawDescData []byte ) func file_wallet_proto_rawDescGZIP() []byte { file_wallet_proto_rawDescOnce.Do(func() { file_wallet_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_wallet_proto_rawDesc), len(file_wallet_proto_rawDesc))) }) return file_wallet_proto_rawDescData } var file_wallet_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_wallet_proto_msgTypes = make([]protoimpl.MessageInfo, 42) var file_wallet_proto_goTypes = []any{ (AddressType)(0), // 0: pactus.AddressType (TxDirection)(0), // 1: pactus.TxDirection (TransactionStatus)(0), // 2: pactus.TransactionStatus (*AddressInfo)(nil), // 3: pactus.AddressInfo (*GetNewAddressRequest)(nil), // 4: pactus.GetNewAddressRequest (*GetNewAddressResponse)(nil), // 5: pactus.GetNewAddressResponse (*RestoreWalletRequest)(nil), // 6: pactus.RestoreWalletRequest (*RestoreWalletResponse)(nil), // 7: pactus.RestoreWalletResponse (*CreateWalletRequest)(nil), // 8: pactus.CreateWalletRequest (*CreateWalletResponse)(nil), // 9: pactus.CreateWalletResponse (*LoadWalletRequest)(nil), // 10: pactus.LoadWalletRequest (*LoadWalletResponse)(nil), // 11: pactus.LoadWalletResponse (*UnloadWalletRequest)(nil), // 12: pactus.UnloadWalletRequest (*UnloadWalletResponse)(nil), // 13: pactus.UnloadWalletResponse (*GetValidatorAddressRequest)(nil), // 14: pactus.GetValidatorAddressRequest (*GetValidatorAddressResponse)(nil), // 15: pactus.GetValidatorAddressResponse (*SignRawTransactionRequest)(nil), // 16: pactus.SignRawTransactionRequest (*SignRawTransactionResponse)(nil), // 17: pactus.SignRawTransactionResponse (*GetTotalBalanceRequest)(nil), // 18: pactus.GetTotalBalanceRequest (*GetTotalBalanceResponse)(nil), // 19: pactus.GetTotalBalanceResponse (*SignMessageRequest)(nil), // 20: pactus.SignMessageRequest (*SignMessageResponse)(nil), // 21: pactus.SignMessageResponse (*GetTotalStakeRequest)(nil), // 22: pactus.GetTotalStakeRequest (*GetTotalStakeResponse)(nil), // 23: pactus.GetTotalStakeResponse (*GetAddressInfoRequest)(nil), // 24: pactus.GetAddressInfoRequest (*GetAddressInfoResponse)(nil), // 25: pactus.GetAddressInfoResponse (*SetAddressLabelRequest)(nil), // 26: pactus.SetAddressLabelRequest (*SetAddressLabelResponse)(nil), // 27: pactus.SetAddressLabelResponse (*ListWalletsRequest)(nil), // 28: pactus.ListWalletsRequest (*ListWalletsResponse)(nil), // 29: pactus.ListWalletsResponse (*GetWalletInfoRequest)(nil), // 30: pactus.GetWalletInfoRequest (*GetWalletInfoResponse)(nil), // 31: pactus.GetWalletInfoResponse (*ListAddressesRequest)(nil), // 32: pactus.ListAddressesRequest (*ListAddressesResponse)(nil), // 33: pactus.ListAddressesResponse (*UpdatePasswordRequest)(nil), // 34: pactus.UpdatePasswordRequest (*UpdatePasswordResponse)(nil), // 35: pactus.UpdatePasswordResponse (*WalletTransactionInfo)(nil), // 36: pactus.WalletTransactionInfo (*ListTransactionsRequest)(nil), // 37: pactus.ListTransactionsRequest (*ListTransactionsResponse)(nil), // 38: pactus.ListTransactionsResponse (*SetDefaultFeeRequest)(nil), // 39: pactus.SetDefaultFeeRequest (*SetDefaultFeeResponse)(nil), // 40: pactus.SetDefaultFeeResponse (*GetMnemonicRequest)(nil), // 41: pactus.GetMnemonicRequest (*GetMnemonicResponse)(nil), // 42: pactus.GetMnemonicResponse (*GetPrivateKeyRequest)(nil), // 43: pactus.GetPrivateKeyRequest (*GetPrivateKeyResponse)(nil), // 44: pactus.GetPrivateKeyResponse (PayloadType)(0), // 45: pactus.PayloadType } var file_wallet_proto_depIdxs = []int32{ 0, // 0: pactus.GetNewAddressRequest.address_type:type_name -> pactus.AddressType 3, // 1: pactus.GetNewAddressResponse.addr:type_name -> pactus.AddressInfo 3, // 2: pactus.GetAddressInfoResponse.addr:type_name -> pactus.AddressInfo 0, // 3: pactus.ListAddressesRequest.address_types:type_name -> pactus.AddressType 3, // 4: pactus.ListAddressesResponse.addrs:type_name -> pactus.AddressInfo 1, // 5: pactus.WalletTransactionInfo.direction:type_name -> pactus.TxDirection 2, // 6: pactus.WalletTransactionInfo.status:type_name -> pactus.TransactionStatus 45, // 7: pactus.WalletTransactionInfo.payload_type:type_name -> pactus.PayloadType 1, // 8: pactus.ListTransactionsRequest.direction:type_name -> pactus.TxDirection 36, // 9: pactus.ListTransactionsResponse.txs:type_name -> pactus.WalletTransactionInfo 8, // 10: pactus.Wallet.CreateWallet:input_type -> pactus.CreateWalletRequest 6, // 11: pactus.Wallet.RestoreWallet:input_type -> pactus.RestoreWalletRequest 10, // 12: pactus.Wallet.LoadWallet:input_type -> pactus.LoadWalletRequest 12, // 13: pactus.Wallet.UnloadWallet:input_type -> pactus.UnloadWalletRequest 28, // 14: pactus.Wallet.ListWallets:input_type -> pactus.ListWalletsRequest 30, // 15: pactus.Wallet.GetWalletInfo:input_type -> pactus.GetWalletInfoRequest 34, // 16: pactus.Wallet.UpdatePassword:input_type -> pactus.UpdatePasswordRequest 18, // 17: pactus.Wallet.GetTotalBalance:input_type -> pactus.GetTotalBalanceRequest 22, // 18: pactus.Wallet.GetTotalStake:input_type -> pactus.GetTotalStakeRequest 14, // 19: pactus.Wallet.GetValidatorAddress:input_type -> pactus.GetValidatorAddressRequest 24, // 20: pactus.Wallet.GetAddressInfo:input_type -> pactus.GetAddressInfoRequest 26, // 21: pactus.Wallet.SetAddressLabel:input_type -> pactus.SetAddressLabelRequest 4, // 22: pactus.Wallet.GetNewAddress:input_type -> pactus.GetNewAddressRequest 32, // 23: pactus.Wallet.ListAddresses:input_type -> pactus.ListAddressesRequest 20, // 24: pactus.Wallet.SignMessage:input_type -> pactus.SignMessageRequest 16, // 25: pactus.Wallet.SignRawTransaction:input_type -> pactus.SignRawTransactionRequest 37, // 26: pactus.Wallet.ListTransactions:input_type -> pactus.ListTransactionsRequest 39, // 27: pactus.Wallet.SetDefaultFee:input_type -> pactus.SetDefaultFeeRequest 41, // 28: pactus.Wallet.GetMnemonic:input_type -> pactus.GetMnemonicRequest 43, // 29: pactus.Wallet.GetPrivateKey:input_type -> pactus.GetPrivateKeyRequest 9, // 30: pactus.Wallet.CreateWallet:output_type -> pactus.CreateWalletResponse 7, // 31: pactus.Wallet.RestoreWallet:output_type -> pactus.RestoreWalletResponse 11, // 32: pactus.Wallet.LoadWallet:output_type -> pactus.LoadWalletResponse 13, // 33: pactus.Wallet.UnloadWallet:output_type -> pactus.UnloadWalletResponse 29, // 34: pactus.Wallet.ListWallets:output_type -> pactus.ListWalletsResponse 31, // 35: pactus.Wallet.GetWalletInfo:output_type -> pactus.GetWalletInfoResponse 35, // 36: pactus.Wallet.UpdatePassword:output_type -> pactus.UpdatePasswordResponse 19, // 37: pactus.Wallet.GetTotalBalance:output_type -> pactus.GetTotalBalanceResponse 23, // 38: pactus.Wallet.GetTotalStake:output_type -> pactus.GetTotalStakeResponse 15, // 39: pactus.Wallet.GetValidatorAddress:output_type -> pactus.GetValidatorAddressResponse 25, // 40: pactus.Wallet.GetAddressInfo:output_type -> pactus.GetAddressInfoResponse 27, // 41: pactus.Wallet.SetAddressLabel:output_type -> pactus.SetAddressLabelResponse 5, // 42: pactus.Wallet.GetNewAddress:output_type -> pactus.GetNewAddressResponse 33, // 43: pactus.Wallet.ListAddresses:output_type -> pactus.ListAddressesResponse 21, // 44: pactus.Wallet.SignMessage:output_type -> pactus.SignMessageResponse 17, // 45: pactus.Wallet.SignRawTransaction:output_type -> pactus.SignRawTransactionResponse 38, // 46: pactus.Wallet.ListTransactions:output_type -> pactus.ListTransactionsResponse 40, // 47: pactus.Wallet.SetDefaultFee:output_type -> pactus.SetDefaultFeeResponse 42, // 48: pactus.Wallet.GetMnemonic:output_type -> pactus.GetMnemonicResponse 44, // 49: pactus.Wallet.GetPrivateKey:output_type -> pactus.GetPrivateKeyResponse 30, // [30:50] is the sub-list for method output_type 10, // [10:30] is the sub-list for method input_type 10, // [10:10] is the sub-list for extension type_name 10, // [10:10] is the sub-list for extension extendee 0, // [0:10] is the sub-list for field type_name } func init() { file_wallet_proto_init() } func file_wallet_proto_init() { if File_wallet_proto != nil { return } file_transaction_proto_init() type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_wallet_proto_rawDesc), len(file_wallet_proto_rawDesc)), NumEnums: 3, NumMessages: 42, NumExtensions: 0, NumServices: 1, }, GoTypes: file_wallet_proto_goTypes, DependencyIndexes: file_wallet_proto_depIdxs, EnumInfos: file_wallet_proto_enumTypes, MessageInfos: file_wallet_proto_msgTypes, }.Build() File_wallet_proto = out.File file_wallet_proto_goTypes = nil file_wallet_proto_depIdxs = nil } ================================================ FILE: www/grpc/gen/go/wallet.pb.gw.go ================================================ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: wallet.proto /* Package pactus is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package pactus import ( "context" "errors" "io" "net/http" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors var ( _ codes.Code _ io.Reader _ status.Status _ = errors.New _ = runtime.String _ = utilities.NewDoubleArray _ = metadata.Join ) func request_Wallet_CreateWallet_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq CreateWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.CreateWallet(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_CreateWallet_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq CreateWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateWallet(ctx, &protoReq) return msg, metadata, err } func request_Wallet_RestoreWallet_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq RestoreWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.RestoreWallet(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_RestoreWallet_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq RestoreWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RestoreWallet(ctx, &protoReq) return msg, metadata, err } func request_Wallet_LoadWallet_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq LoadWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.LoadWallet(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_LoadWallet_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq LoadWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.LoadWallet(ctx, &protoReq) return msg, metadata, err } func request_Wallet_UnloadWallet_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq UnloadWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.UnloadWallet(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_UnloadWallet_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq UnloadWalletRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.UnloadWallet(ctx, &protoReq) return msg, metadata, err } func request_Wallet_ListWallets_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListWalletsRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.ListWallets(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_ListWallets_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListWalletsRequest metadata runtime.ServerMetadata ) msg, err := server.ListWallets(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_GetWalletInfo_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_GetWalletInfo_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetWalletInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetWalletInfo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetWalletInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_GetWalletInfo_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetWalletInfoRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetWalletInfo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetWalletInfo(ctx, &protoReq) return msg, metadata, err } func request_Wallet_UpdatePassword_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq UpdatePasswordRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.UpdatePassword(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_UpdatePassword_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq UpdatePasswordRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.UpdatePassword(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_GetTotalBalance_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_GetTotalBalance_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTotalBalanceRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetTotalBalance_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetTotalBalance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_GetTotalBalance_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTotalBalanceRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetTotalBalance_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetTotalBalance(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_GetTotalStake_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_GetTotalStake_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTotalStakeRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetTotalStake_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetTotalStake(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_GetTotalStake_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetTotalStakeRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetTotalStake_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetTotalStake(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_GetValidatorAddress_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_GetValidatorAddress_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorAddressRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetValidatorAddress_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetValidatorAddress(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_GetValidatorAddress_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetValidatorAddressRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetValidatorAddress_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetValidatorAddress(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_GetAddressInfo_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_GetAddressInfo_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetAddressInfoRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetAddressInfo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetAddressInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_GetAddressInfo_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetAddressInfoRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_GetAddressInfo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetAddressInfo(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_SetAddressLabel_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_SetAddressLabel_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SetAddressLabelRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_SetAddressLabel_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SetAddressLabel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_SetAddressLabel_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SetAddressLabelRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_SetAddressLabel_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SetAddressLabel(ctx, &protoReq) return msg, metadata, err } func request_Wallet_GetNewAddress_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetNewAddressRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.GetNewAddress(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_GetNewAddress_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetNewAddressRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetNewAddress(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_ListAddresses_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_ListAddresses_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListAddressesRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_ListAddresses_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.ListAddresses(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_ListAddresses_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListAddressesRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_ListAddresses_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.ListAddresses(ctx, &protoReq) return msg, metadata, err } func request_Wallet_SignMessage_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignMessageRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.SignMessage(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_SignMessage_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignMessageRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SignMessage(ctx, &protoReq) return msg, metadata, err } func request_Wallet_SignRawTransaction_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignRawTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } msg, err := client.SignRawTransaction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_SignRawTransaction_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SignRawTransactionRequest metadata runtime.ServerMetadata ) if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SignRawTransaction(ctx, &protoReq) return msg, metadata, err } var filter_Wallet_ListTransactions_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_Wallet_ListTransactions_0(ctx context.Context, marshaler runtime.Marshaler, client WalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListTransactionsRequest metadata runtime.ServerMetadata ) if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_ListTransactions_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.ListTransactions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Wallet_ListTransactions_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListTransactionsRequest metadata runtime.ServerMetadata ) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Wallet_ListTransactions_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.ListTransactions(ctx, &protoReq) return msg, metadata, err } // RegisterWalletHandlerServer registers the http handlers for service Wallet to "mux". // UnaryRPC :call WalletServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterWalletHandlerFromEndpoint instead. // GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux, server WalletServer) error { mux.Handle(http.MethodPost, pattern_Wallet_CreateWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/CreateWallet", runtime.WithHTTPPathPattern("/pactus/wallet/create_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_CreateWallet_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_CreateWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_RestoreWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/RestoreWallet", runtime.WithHTTPPathPattern("/pactus/wallet/restore_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_RestoreWallet_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_RestoreWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_LoadWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/LoadWallet", runtime.WithHTTPPathPattern("/pactus/wallet/load_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_LoadWallet_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_LoadWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_UnloadWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/UnloadWallet", runtime.WithHTTPPathPattern("/pactus/wallet/unload_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_UnloadWallet_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_UnloadWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_ListWallets_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/ListWallets", runtime.WithHTTPPathPattern("/pactus/wallet/list_wallets")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_ListWallets_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_ListWallets_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetWalletInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/GetWalletInfo", runtime.WithHTTPPathPattern("/pactus/wallet/get_wallet_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_GetWalletInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetWalletInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_UpdatePassword_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/UpdatePassword", runtime.WithHTTPPathPattern("/pactus/wallet/update_password")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_UpdatePassword_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_UpdatePassword_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetTotalBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/GetTotalBalance", runtime.WithHTTPPathPattern("/pactus/wallet/get_total_balance")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_GetTotalBalance_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetTotalBalance_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetTotalStake_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/GetTotalStake", runtime.WithHTTPPathPattern("/pactus/wallet/get_total_stake")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_GetTotalStake_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetTotalStake_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetValidatorAddress_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/GetValidatorAddress", runtime.WithHTTPPathPattern("/pactus/wallet/get_validator_address")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_GetValidatorAddress_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetValidatorAddress_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetAddressInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/GetAddressInfo", runtime.WithHTTPPathPattern("/pactus/wallet/get_address_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_GetAddressInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetAddressInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPatch, pattern_Wallet_SetAddressLabel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/SetAddressLabel", runtime.WithHTTPPathPattern("/pactus/wallet/set_address_label")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_SetAddressLabel_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_SetAddressLabel_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_GetNewAddress_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/GetNewAddress", runtime.WithHTTPPathPattern("/pactus/wallet/get_new_address")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_GetNewAddress_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetNewAddress_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_ListAddresses_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/ListAddresses", runtime.WithHTTPPathPattern("/pactus/wallet/list_addresses")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_ListAddresses_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_ListAddresses_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_SignMessage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/SignMessage", runtime.WithHTTPPathPattern("/pactus/wallet/sign_message")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_SignMessage_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_SignMessage_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_SignRawTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/SignRawTransaction", runtime.WithHTTPPathPattern("/pactus/wallet/sign_raw_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_SignRawTransaction_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_SignRawTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_ListTransactions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pactus.Wallet/ListTransactions", runtime.WithHTTPPathPattern("/pactus/wallet/list_transactions")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Wallet_ListTransactions_0(annotatedContext, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_ListTransactions_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterWalletHandlerFromEndpoint is same as RegisterWalletHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterWalletHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterWalletHandler(ctx, mux, conn) } // RegisterWalletHandler registers the http handlers for service Wallet to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterWalletHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterWalletHandlerClient(ctx, mux, NewWalletClient(conn)) } // RegisterWalletHandlerClient registers the http handlers for service Wallet // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "WalletClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "WalletClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "WalletClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux, client WalletClient) error { mux.Handle(http.MethodPost, pattern_Wallet_CreateWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/CreateWallet", runtime.WithHTTPPathPattern("/pactus/wallet/create_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_CreateWallet_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_CreateWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_RestoreWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/RestoreWallet", runtime.WithHTTPPathPattern("/pactus/wallet/restore_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_RestoreWallet_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_RestoreWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_LoadWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/LoadWallet", runtime.WithHTTPPathPattern("/pactus/wallet/load_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_LoadWallet_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_LoadWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_UnloadWallet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/UnloadWallet", runtime.WithHTTPPathPattern("/pactus/wallet/unload_wallet")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_UnloadWallet_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_UnloadWallet_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_ListWallets_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/ListWallets", runtime.WithHTTPPathPattern("/pactus/wallet/list_wallets")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_ListWallets_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_ListWallets_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetWalletInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/GetWalletInfo", runtime.WithHTTPPathPattern("/pactus/wallet/get_wallet_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_GetWalletInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetWalletInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_UpdatePassword_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/UpdatePassword", runtime.WithHTTPPathPattern("/pactus/wallet/update_password")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_UpdatePassword_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_UpdatePassword_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetTotalBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/GetTotalBalance", runtime.WithHTTPPathPattern("/pactus/wallet/get_total_balance")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_GetTotalBalance_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetTotalBalance_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetTotalStake_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/GetTotalStake", runtime.WithHTTPPathPattern("/pactus/wallet/get_total_stake")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_GetTotalStake_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetTotalStake_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetValidatorAddress_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/GetValidatorAddress", runtime.WithHTTPPathPattern("/pactus/wallet/get_validator_address")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_GetValidatorAddress_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetValidatorAddress_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_GetAddressInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/GetAddressInfo", runtime.WithHTTPPathPattern("/pactus/wallet/get_address_info")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_GetAddressInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetAddressInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPatch, pattern_Wallet_SetAddressLabel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/SetAddressLabel", runtime.WithHTTPPathPattern("/pactus/wallet/set_address_label")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_SetAddressLabel_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_SetAddressLabel_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_GetNewAddress_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/GetNewAddress", runtime.WithHTTPPathPattern("/pactus/wallet/get_new_address")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_GetNewAddress_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_GetNewAddress_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_ListAddresses_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/ListAddresses", runtime.WithHTTPPathPattern("/pactus/wallet/list_addresses")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_ListAddresses_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_ListAddresses_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_SignMessage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/SignMessage", runtime.WithHTTPPathPattern("/pactus/wallet/sign_message")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_SignMessage_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_SignMessage_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodPost, pattern_Wallet_SignRawTransaction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/SignRawTransaction", runtime.WithHTTPPathPattern("/pactus/wallet/sign_raw_transaction")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_SignRawTransaction_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_SignRawTransaction_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle(http.MethodGet, pattern_Wallet_ListTransactions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/pactus.Wallet/ListTransactions", runtime.WithHTTPPathPattern("/pactus/wallet/list_transactions")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Wallet_ListTransactions_0(annotatedContext, inboundMarshaler, client, req, pathParams) annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) if err != nil { runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } forward_Wallet_ListTransactions_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_Wallet_CreateWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "create_wallet"}, "")) pattern_Wallet_RestoreWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "restore_wallet"}, "")) pattern_Wallet_LoadWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "load_wallet"}, "")) pattern_Wallet_UnloadWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "unload_wallet"}, "")) pattern_Wallet_ListWallets_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "list_wallets"}, "")) pattern_Wallet_GetWalletInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "get_wallet_info"}, "")) pattern_Wallet_UpdatePassword_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "update_password"}, "")) pattern_Wallet_GetTotalBalance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "get_total_balance"}, "")) pattern_Wallet_GetTotalStake_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "get_total_stake"}, "")) pattern_Wallet_GetValidatorAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "get_validator_address"}, "")) pattern_Wallet_GetAddressInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "get_address_info"}, "")) pattern_Wallet_SetAddressLabel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "set_address_label"}, "")) pattern_Wallet_GetNewAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "get_new_address"}, "")) pattern_Wallet_ListAddresses_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "list_addresses"}, "")) pattern_Wallet_SignMessage_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "sign_message"}, "")) pattern_Wallet_SignRawTransaction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "sign_raw_transaction"}, "")) pattern_Wallet_ListTransactions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"pactus", "wallet", "list_transactions"}, "")) ) var ( forward_Wallet_CreateWallet_0 = runtime.ForwardResponseMessage forward_Wallet_RestoreWallet_0 = runtime.ForwardResponseMessage forward_Wallet_LoadWallet_0 = runtime.ForwardResponseMessage forward_Wallet_UnloadWallet_0 = runtime.ForwardResponseMessage forward_Wallet_ListWallets_0 = runtime.ForwardResponseMessage forward_Wallet_GetWalletInfo_0 = runtime.ForwardResponseMessage forward_Wallet_UpdatePassword_0 = runtime.ForwardResponseMessage forward_Wallet_GetTotalBalance_0 = runtime.ForwardResponseMessage forward_Wallet_GetTotalStake_0 = runtime.ForwardResponseMessage forward_Wallet_GetValidatorAddress_0 = runtime.ForwardResponseMessage forward_Wallet_GetAddressInfo_0 = runtime.ForwardResponseMessage forward_Wallet_SetAddressLabel_0 = runtime.ForwardResponseMessage forward_Wallet_GetNewAddress_0 = runtime.ForwardResponseMessage forward_Wallet_ListAddresses_0 = runtime.ForwardResponseMessage forward_Wallet_SignMessage_0 = runtime.ForwardResponseMessage forward_Wallet_SignRawTransaction_0 = runtime.ForwardResponseMessage forward_Wallet_ListTransactions_0 = runtime.ForwardResponseMessage ) ================================================ FILE: www/grpc/gen/go/wallet_grpc.pb.go ================================================ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.6.0 // - protoc (unknown) // source: wallet.proto package pactus import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( Wallet_CreateWallet_FullMethodName = "/pactus.Wallet/CreateWallet" Wallet_RestoreWallet_FullMethodName = "/pactus.Wallet/RestoreWallet" Wallet_LoadWallet_FullMethodName = "/pactus.Wallet/LoadWallet" Wallet_UnloadWallet_FullMethodName = "/pactus.Wallet/UnloadWallet" Wallet_ListWallets_FullMethodName = "/pactus.Wallet/ListWallets" Wallet_GetWalletInfo_FullMethodName = "/pactus.Wallet/GetWalletInfo" Wallet_UpdatePassword_FullMethodName = "/pactus.Wallet/UpdatePassword" Wallet_GetTotalBalance_FullMethodName = "/pactus.Wallet/GetTotalBalance" Wallet_GetTotalStake_FullMethodName = "/pactus.Wallet/GetTotalStake" Wallet_GetValidatorAddress_FullMethodName = "/pactus.Wallet/GetValidatorAddress" Wallet_GetAddressInfo_FullMethodName = "/pactus.Wallet/GetAddressInfo" Wallet_SetAddressLabel_FullMethodName = "/pactus.Wallet/SetAddressLabel" Wallet_GetNewAddress_FullMethodName = "/pactus.Wallet/GetNewAddress" Wallet_ListAddresses_FullMethodName = "/pactus.Wallet/ListAddresses" Wallet_SignMessage_FullMethodName = "/pactus.Wallet/SignMessage" Wallet_SignRawTransaction_FullMethodName = "/pactus.Wallet/SignRawTransaction" Wallet_ListTransactions_FullMethodName = "/pactus.Wallet/ListTransactions" Wallet_SetDefaultFee_FullMethodName = "/pactus.Wallet/SetDefaultFee" Wallet_GetMnemonic_FullMethodName = "/pactus.Wallet/GetMnemonic" Wallet_GetPrivateKey_FullMethodName = "/pactus.Wallet/GetPrivateKey" ) // WalletClient is the client API for Wallet service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. // // Wallet service provides RPC methods for wallet management operations. type WalletClient interface { // CreateWallet creates a new wallet with the specified parameters. CreateWallet(ctx context.Context, in *CreateWalletRequest, opts ...grpc.CallOption) (*CreateWalletResponse, error) // RestoreWallet restores an existing wallet with the given mnemonic. RestoreWallet(ctx context.Context, in *RestoreWalletRequest, opts ...grpc.CallOption) (*RestoreWalletResponse, error) // LoadWallet loads an existing wallet with the given name. // deprecated: It will be removed in a future version. LoadWallet(ctx context.Context, in *LoadWalletRequest, opts ...grpc.CallOption) (*LoadWalletResponse, error) // UnloadWallet unloads a currently loaded wallet with the specified name. // deprecated: It will be removed in a future version. UnloadWallet(ctx context.Context, in *UnloadWalletRequest, opts ...grpc.CallOption) (*UnloadWalletResponse, error) // ListWallets returns a list of all available wallets. ListWallets(ctx context.Context, in *ListWalletsRequest, opts ...grpc.CallOption) (*ListWalletsResponse, error) // GetWalletInfo returns detailed information about a specific wallet. GetWalletInfo(ctx context.Context, in *GetWalletInfoRequest, opts ...grpc.CallOption) (*GetWalletInfoResponse, error) // UpdatePassword updates the password of an existing wallet. UpdatePassword(ctx context.Context, in *UpdatePasswordRequest, opts ...grpc.CallOption) (*UpdatePasswordResponse, error) // GetTotalBalance returns the total available balance of the wallet. GetTotalBalance(ctx context.Context, in *GetTotalBalanceRequest, opts ...grpc.CallOption) (*GetTotalBalanceResponse, error) // GetTotalStake returns the total stake amount in the wallet. GetTotalStake(ctx context.Context, in *GetTotalStakeRequest, opts ...grpc.CallOption) (*GetTotalStakeResponse, error) // GetValidatorAddress retrieves the validator address associated with a public key. // Deprecated: Will move into utils. GetValidatorAddress(ctx context.Context, in *GetValidatorAddressRequest, opts ...grpc.CallOption) (*GetValidatorAddressResponse, error) // GetAddressInfo returns detailed information about a specific address. GetAddressInfo(ctx context.Context, in *GetAddressInfoRequest, opts ...grpc.CallOption) (*GetAddressInfoResponse, error) // SetAddressLabel sets or updates the label for a given address. SetAddressLabel(ctx context.Context, in *SetAddressLabelRequest, opts ...grpc.CallOption) (*SetAddressLabelResponse, error) // GetNewAddress generates a new address for the specified wallet. GetNewAddress(ctx context.Context, in *GetNewAddressRequest, opts ...grpc.CallOption) (*GetNewAddressResponse, error) // ListAddresses returns all addresses in the specified wallet. ListAddresses(ctx context.Context, in *ListAddressesRequest, opts ...grpc.CallOption) (*ListAddressesResponse, error) // SignMessage signs an arbitrary message using a wallet's private key. SignMessage(ctx context.Context, in *SignMessageRequest, opts ...grpc.CallOption) (*SignMessageResponse, error) // SignRawTransaction signs a raw transaction for a specified wallet. SignRawTransaction(ctx context.Context, in *SignRawTransactionRequest, opts ...grpc.CallOption) (*SignRawTransactionResponse, error) // ListTransactions returns a list of transactions for a wallet, // optionally filtered by a specific address, with pagination support. ListTransactions(ctx context.Context, in *ListTransactionsRequest, opts ...grpc.CallOption) (*ListTransactionsResponse, error) // SetDefaultFee sets the default fee for the wallet. SetDefaultFee(ctx context.Context, in *SetDefaultFeeRequest, opts ...grpc.CallOption) (*SetDefaultFeeResponse, error) // GetMnemonic returns the mnemonic (seed phrase) for the wallet. GetMnemonic(ctx context.Context, in *GetMnemonicRequest, opts ...grpc.CallOption) (*GetMnemonicResponse, error) // GetPrivateKey returns the private key for a given address. GetPrivateKey(ctx context.Context, in *GetPrivateKeyRequest, opts ...grpc.CallOption) (*GetPrivateKeyResponse, error) } type walletClient struct { cc grpc.ClientConnInterface } func NewWalletClient(cc grpc.ClientConnInterface) WalletClient { return &walletClient{cc} } func (c *walletClient) CreateWallet(ctx context.Context, in *CreateWalletRequest, opts ...grpc.CallOption) (*CreateWalletResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(CreateWalletResponse) err := c.cc.Invoke(ctx, Wallet_CreateWallet_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) RestoreWallet(ctx context.Context, in *RestoreWalletRequest, opts ...grpc.CallOption) (*RestoreWalletResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(RestoreWalletResponse) err := c.cc.Invoke(ctx, Wallet_RestoreWallet_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) LoadWallet(ctx context.Context, in *LoadWalletRequest, opts ...grpc.CallOption) (*LoadWalletResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(LoadWalletResponse) err := c.cc.Invoke(ctx, Wallet_LoadWallet_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) UnloadWallet(ctx context.Context, in *UnloadWalletRequest, opts ...grpc.CallOption) (*UnloadWalletResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(UnloadWalletResponse) err := c.cc.Invoke(ctx, Wallet_UnloadWallet_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) ListWallets(ctx context.Context, in *ListWalletsRequest, opts ...grpc.CallOption) (*ListWalletsResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListWalletsResponse) err := c.cc.Invoke(ctx, Wallet_ListWallets_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetWalletInfo(ctx context.Context, in *GetWalletInfoRequest, opts ...grpc.CallOption) (*GetWalletInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetWalletInfoResponse) err := c.cc.Invoke(ctx, Wallet_GetWalletInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) UpdatePassword(ctx context.Context, in *UpdatePasswordRequest, opts ...grpc.CallOption) (*UpdatePasswordResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(UpdatePasswordResponse) err := c.cc.Invoke(ctx, Wallet_UpdatePassword_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetTotalBalance(ctx context.Context, in *GetTotalBalanceRequest, opts ...grpc.CallOption) (*GetTotalBalanceResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetTotalBalanceResponse) err := c.cc.Invoke(ctx, Wallet_GetTotalBalance_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetTotalStake(ctx context.Context, in *GetTotalStakeRequest, opts ...grpc.CallOption) (*GetTotalStakeResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetTotalStakeResponse) err := c.cc.Invoke(ctx, Wallet_GetTotalStake_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetValidatorAddress(ctx context.Context, in *GetValidatorAddressRequest, opts ...grpc.CallOption) (*GetValidatorAddressResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetValidatorAddressResponse) err := c.cc.Invoke(ctx, Wallet_GetValidatorAddress_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetAddressInfo(ctx context.Context, in *GetAddressInfoRequest, opts ...grpc.CallOption) (*GetAddressInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetAddressInfoResponse) err := c.cc.Invoke(ctx, Wallet_GetAddressInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) SetAddressLabel(ctx context.Context, in *SetAddressLabelRequest, opts ...grpc.CallOption) (*SetAddressLabelResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SetAddressLabelResponse) err := c.cc.Invoke(ctx, Wallet_SetAddressLabel_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetNewAddress(ctx context.Context, in *GetNewAddressRequest, opts ...grpc.CallOption) (*GetNewAddressResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetNewAddressResponse) err := c.cc.Invoke(ctx, Wallet_GetNewAddress_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) ListAddresses(ctx context.Context, in *ListAddressesRequest, opts ...grpc.CallOption) (*ListAddressesResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListAddressesResponse) err := c.cc.Invoke(ctx, Wallet_ListAddresses_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) SignMessage(ctx context.Context, in *SignMessageRequest, opts ...grpc.CallOption) (*SignMessageResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SignMessageResponse) err := c.cc.Invoke(ctx, Wallet_SignMessage_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) SignRawTransaction(ctx context.Context, in *SignRawTransactionRequest, opts ...grpc.CallOption) (*SignRawTransactionResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SignRawTransactionResponse) err := c.cc.Invoke(ctx, Wallet_SignRawTransaction_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) ListTransactions(ctx context.Context, in *ListTransactionsRequest, opts ...grpc.CallOption) (*ListTransactionsResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListTransactionsResponse) err := c.cc.Invoke(ctx, Wallet_ListTransactions_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) SetDefaultFee(ctx context.Context, in *SetDefaultFeeRequest, opts ...grpc.CallOption) (*SetDefaultFeeResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SetDefaultFeeResponse) err := c.cc.Invoke(ctx, Wallet_SetDefaultFee_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetMnemonic(ctx context.Context, in *GetMnemonicRequest, opts ...grpc.CallOption) (*GetMnemonicResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetMnemonicResponse) err := c.cc.Invoke(ctx, Wallet_GetMnemonic_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *walletClient) GetPrivateKey(ctx context.Context, in *GetPrivateKeyRequest, opts ...grpc.CallOption) (*GetPrivateKeyResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetPrivateKeyResponse) err := c.cc.Invoke(ctx, Wallet_GetPrivateKey_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // WalletServer is the server API for Wallet service. // All implementations should embed UnimplementedWalletServer // for forward compatibility. // // Wallet service provides RPC methods for wallet management operations. type WalletServer interface { // CreateWallet creates a new wallet with the specified parameters. CreateWallet(context.Context, *CreateWalletRequest) (*CreateWalletResponse, error) // RestoreWallet restores an existing wallet with the given mnemonic. RestoreWallet(context.Context, *RestoreWalletRequest) (*RestoreWalletResponse, error) // LoadWallet loads an existing wallet with the given name. // deprecated: It will be removed in a future version. LoadWallet(context.Context, *LoadWalletRequest) (*LoadWalletResponse, error) // UnloadWallet unloads a currently loaded wallet with the specified name. // deprecated: It will be removed in a future version. UnloadWallet(context.Context, *UnloadWalletRequest) (*UnloadWalletResponse, error) // ListWallets returns a list of all available wallets. ListWallets(context.Context, *ListWalletsRequest) (*ListWalletsResponse, error) // GetWalletInfo returns detailed information about a specific wallet. GetWalletInfo(context.Context, *GetWalletInfoRequest) (*GetWalletInfoResponse, error) // UpdatePassword updates the password of an existing wallet. UpdatePassword(context.Context, *UpdatePasswordRequest) (*UpdatePasswordResponse, error) // GetTotalBalance returns the total available balance of the wallet. GetTotalBalance(context.Context, *GetTotalBalanceRequest) (*GetTotalBalanceResponse, error) // GetTotalStake returns the total stake amount in the wallet. GetTotalStake(context.Context, *GetTotalStakeRequest) (*GetTotalStakeResponse, error) // GetValidatorAddress retrieves the validator address associated with a public key. // Deprecated: Will move into utils. GetValidatorAddress(context.Context, *GetValidatorAddressRequest) (*GetValidatorAddressResponse, error) // GetAddressInfo returns detailed information about a specific address. GetAddressInfo(context.Context, *GetAddressInfoRequest) (*GetAddressInfoResponse, error) // SetAddressLabel sets or updates the label for a given address. SetAddressLabel(context.Context, *SetAddressLabelRequest) (*SetAddressLabelResponse, error) // GetNewAddress generates a new address for the specified wallet. GetNewAddress(context.Context, *GetNewAddressRequest) (*GetNewAddressResponse, error) // ListAddresses returns all addresses in the specified wallet. ListAddresses(context.Context, *ListAddressesRequest) (*ListAddressesResponse, error) // SignMessage signs an arbitrary message using a wallet's private key. SignMessage(context.Context, *SignMessageRequest) (*SignMessageResponse, error) // SignRawTransaction signs a raw transaction for a specified wallet. SignRawTransaction(context.Context, *SignRawTransactionRequest) (*SignRawTransactionResponse, error) // ListTransactions returns a list of transactions for a wallet, // optionally filtered by a specific address, with pagination support. ListTransactions(context.Context, *ListTransactionsRequest) (*ListTransactionsResponse, error) // SetDefaultFee sets the default fee for the wallet. SetDefaultFee(context.Context, *SetDefaultFeeRequest) (*SetDefaultFeeResponse, error) // GetMnemonic returns the mnemonic (seed phrase) for the wallet. GetMnemonic(context.Context, *GetMnemonicRequest) (*GetMnemonicResponse, error) // GetPrivateKey returns the private key for a given address. GetPrivateKey(context.Context, *GetPrivateKeyRequest) (*GetPrivateKeyResponse, error) } // UnimplementedWalletServer should be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedWalletServer struct{} func (UnimplementedWalletServer) CreateWallet(context.Context, *CreateWalletRequest) (*CreateWalletResponse, error) { return nil, status.Error(codes.Unimplemented, "method CreateWallet not implemented") } func (UnimplementedWalletServer) RestoreWallet(context.Context, *RestoreWalletRequest) (*RestoreWalletResponse, error) { return nil, status.Error(codes.Unimplemented, "method RestoreWallet not implemented") } func (UnimplementedWalletServer) LoadWallet(context.Context, *LoadWalletRequest) (*LoadWalletResponse, error) { return nil, status.Error(codes.Unimplemented, "method LoadWallet not implemented") } func (UnimplementedWalletServer) UnloadWallet(context.Context, *UnloadWalletRequest) (*UnloadWalletResponse, error) { return nil, status.Error(codes.Unimplemented, "method UnloadWallet not implemented") } func (UnimplementedWalletServer) ListWallets(context.Context, *ListWalletsRequest) (*ListWalletsResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListWallets not implemented") } func (UnimplementedWalletServer) GetWalletInfo(context.Context, *GetWalletInfoRequest) (*GetWalletInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetWalletInfo not implemented") } func (UnimplementedWalletServer) UpdatePassword(context.Context, *UpdatePasswordRequest) (*UpdatePasswordResponse, error) { return nil, status.Error(codes.Unimplemented, "method UpdatePassword not implemented") } func (UnimplementedWalletServer) GetTotalBalance(context.Context, *GetTotalBalanceRequest) (*GetTotalBalanceResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetTotalBalance not implemented") } func (UnimplementedWalletServer) GetTotalStake(context.Context, *GetTotalStakeRequest) (*GetTotalStakeResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetTotalStake not implemented") } func (UnimplementedWalletServer) GetValidatorAddress(context.Context, *GetValidatorAddressRequest) (*GetValidatorAddressResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetValidatorAddress not implemented") } func (UnimplementedWalletServer) GetAddressInfo(context.Context, *GetAddressInfoRequest) (*GetAddressInfoResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetAddressInfo not implemented") } func (UnimplementedWalletServer) SetAddressLabel(context.Context, *SetAddressLabelRequest) (*SetAddressLabelResponse, error) { return nil, status.Error(codes.Unimplemented, "method SetAddressLabel not implemented") } func (UnimplementedWalletServer) GetNewAddress(context.Context, *GetNewAddressRequest) (*GetNewAddressResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetNewAddress not implemented") } func (UnimplementedWalletServer) ListAddresses(context.Context, *ListAddressesRequest) (*ListAddressesResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListAddresses not implemented") } func (UnimplementedWalletServer) SignMessage(context.Context, *SignMessageRequest) (*SignMessageResponse, error) { return nil, status.Error(codes.Unimplemented, "method SignMessage not implemented") } func (UnimplementedWalletServer) SignRawTransaction(context.Context, *SignRawTransactionRequest) (*SignRawTransactionResponse, error) { return nil, status.Error(codes.Unimplemented, "method SignRawTransaction not implemented") } func (UnimplementedWalletServer) ListTransactions(context.Context, *ListTransactionsRequest) (*ListTransactionsResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListTransactions not implemented") } func (UnimplementedWalletServer) SetDefaultFee(context.Context, *SetDefaultFeeRequest) (*SetDefaultFeeResponse, error) { return nil, status.Error(codes.Unimplemented, "method SetDefaultFee not implemented") } func (UnimplementedWalletServer) GetMnemonic(context.Context, *GetMnemonicRequest) (*GetMnemonicResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetMnemonic not implemented") } func (UnimplementedWalletServer) GetPrivateKey(context.Context, *GetPrivateKeyRequest) (*GetPrivateKeyResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetPrivateKey not implemented") } func (UnimplementedWalletServer) testEmbeddedByValue() {} // UnsafeWalletServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to WalletServer will // result in compilation errors. type UnsafeWalletServer interface { mustEmbedUnimplementedWalletServer() } func RegisterWalletServer(s grpc.ServiceRegistrar, srv WalletServer) { // If the following call panics, it indicates UnimplementedWalletServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&Wallet_ServiceDesc, srv) } func _Wallet_CreateWallet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CreateWalletRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).CreateWallet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_CreateWallet_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).CreateWallet(ctx, req.(*CreateWalletRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_RestoreWallet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RestoreWalletRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).RestoreWallet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_RestoreWallet_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).RestoreWallet(ctx, req.(*RestoreWalletRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_LoadWallet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(LoadWalletRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).LoadWallet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_LoadWallet_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).LoadWallet(ctx, req.(*LoadWalletRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_UnloadWallet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UnloadWalletRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).UnloadWallet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_UnloadWallet_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).UnloadWallet(ctx, req.(*UnloadWalletRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_ListWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListWalletsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).ListWallets(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_ListWallets_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).ListWallets(ctx, req.(*ListWalletsRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetWalletInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetWalletInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetWalletInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetWalletInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetWalletInfo(ctx, req.(*GetWalletInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_UpdatePassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UpdatePasswordRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).UpdatePassword(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_UpdatePassword_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).UpdatePassword(ctx, req.(*UpdatePasswordRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetTotalBalance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetTotalBalanceRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetTotalBalance(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetTotalBalance_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetTotalBalance(ctx, req.(*GetTotalBalanceRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetTotalStake_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetTotalStakeRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetTotalStake(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetTotalStake_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetTotalStake(ctx, req.(*GetTotalStakeRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetValidatorAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetValidatorAddressRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetValidatorAddress(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetValidatorAddress_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetValidatorAddress(ctx, req.(*GetValidatorAddressRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetAddressInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetAddressInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetAddressInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetAddressInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetAddressInfo(ctx, req.(*GetAddressInfoRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_SetAddressLabel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SetAddressLabelRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).SetAddressLabel(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_SetAddressLabel_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).SetAddressLabel(ctx, req.(*SetAddressLabelRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetNewAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetNewAddressRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetNewAddress(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetNewAddress_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetNewAddress(ctx, req.(*GetNewAddressRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_ListAddresses_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListAddressesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).ListAddresses(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_ListAddresses_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).ListAddresses(ctx, req.(*ListAddressesRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_SignMessage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SignMessageRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).SignMessage(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_SignMessage_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).SignMessage(ctx, req.(*SignMessageRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_SignRawTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SignRawTransactionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).SignRawTransaction(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_SignRawTransaction_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).SignRawTransaction(ctx, req.(*SignRawTransactionRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_ListTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListTransactionsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).ListTransactions(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_ListTransactions_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).ListTransactions(ctx, req.(*ListTransactionsRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_SetDefaultFee_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SetDefaultFeeRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).SetDefaultFee(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_SetDefaultFee_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).SetDefaultFee(ctx, req.(*SetDefaultFeeRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetMnemonic_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetMnemonicRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetMnemonic(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetMnemonic_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetMnemonic(ctx, req.(*GetMnemonicRequest)) } return interceptor(ctx, in, info, handler) } func _Wallet_GetPrivateKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetPrivateKeyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WalletServer).GetPrivateKey(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: Wallet_GetPrivateKey_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WalletServer).GetPrivateKey(ctx, req.(*GetPrivateKeyRequest)) } return interceptor(ctx, in, info, handler) } // Wallet_ServiceDesc is the grpc.ServiceDesc for Wallet service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var Wallet_ServiceDesc = grpc.ServiceDesc{ ServiceName: "pactus.Wallet", HandlerType: (*WalletServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "CreateWallet", Handler: _Wallet_CreateWallet_Handler, }, { MethodName: "RestoreWallet", Handler: _Wallet_RestoreWallet_Handler, }, { MethodName: "LoadWallet", Handler: _Wallet_LoadWallet_Handler, }, { MethodName: "UnloadWallet", Handler: _Wallet_UnloadWallet_Handler, }, { MethodName: "ListWallets", Handler: _Wallet_ListWallets_Handler, }, { MethodName: "GetWalletInfo", Handler: _Wallet_GetWalletInfo_Handler, }, { MethodName: "UpdatePassword", Handler: _Wallet_UpdatePassword_Handler, }, { MethodName: "GetTotalBalance", Handler: _Wallet_GetTotalBalance_Handler, }, { MethodName: "GetTotalStake", Handler: _Wallet_GetTotalStake_Handler, }, { MethodName: "GetValidatorAddress", Handler: _Wallet_GetValidatorAddress_Handler, }, { MethodName: "GetAddressInfo", Handler: _Wallet_GetAddressInfo_Handler, }, { MethodName: "SetAddressLabel", Handler: _Wallet_SetAddressLabel_Handler, }, { MethodName: "GetNewAddress", Handler: _Wallet_GetNewAddress_Handler, }, { MethodName: "ListAddresses", Handler: _Wallet_ListAddresses_Handler, }, { MethodName: "SignMessage", Handler: _Wallet_SignMessage_Handler, }, { MethodName: "SignRawTransaction", Handler: _Wallet_SignRawTransaction_Handler, }, { MethodName: "ListTransactions", Handler: _Wallet_ListTransactions_Handler, }, { MethodName: "SetDefaultFee", Handler: _Wallet_SetDefaultFee_Handler, }, { MethodName: "GetMnemonic", Handler: _Wallet_GetMnemonic_Handler, }, { MethodName: "GetPrivateKey", Handler: _Wallet_GetPrivateKey_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "wallet.proto", } ================================================ FILE: www/grpc/gen/go/wallet_jgw.pb.go ================================================ // Code generated by protoc-gen-jrpc-gateway. DO NOT EDIT. // source: wallet.proto /* Package pactus is a reverse proxy. It translates gRPC into JSON-RPC 2.0 */ package pactus import ( "context" "encoding/json" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" ) type WalletJsonRPC struct { client WalletClient } type paramsAndHeadersWallet struct { Headers metadata.MD `json:"headers,omitempty"` Params json.RawMessage `json:"params"` } // RegisterWalletJsonRPC register the grpc client Wallet for json-rpc. // The handlers forward requests to the grpc endpoint over "conn". func RegisterWalletJsonRPC(conn *grpc.ClientConn) *WalletJsonRPC { return &WalletJsonRPC{ client: NewWalletClient(conn), } } func (s *WalletJsonRPC) Methods() map[string]func(ctx context.Context, message json.RawMessage) (any, error) { return map[string]func(ctx context.Context, params json.RawMessage) (any, error){ "pactus.wallet.create_wallet": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(CreateWalletRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.CreateWallet(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.restore_wallet": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(RestoreWalletRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.RestoreWallet(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.load_wallet": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(LoadWalletRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.LoadWallet(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.unload_wallet": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(UnloadWalletRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.UnloadWallet(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.list_wallets": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(ListWalletsRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.ListWallets(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_wallet_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetWalletInfoRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetWalletInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.update_password": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(UpdatePasswordRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.UpdatePassword(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_total_balance": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetTotalBalanceRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetTotalBalance(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_total_stake": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetTotalStakeRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetTotalStake(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_validator_address": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetValidatorAddressRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetValidatorAddress(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_address_info": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetAddressInfoRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetAddressInfo(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.set_address_label": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(SetAddressLabelRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.SetAddressLabel(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_new_address": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetNewAddressRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetNewAddress(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.list_addresses": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(ListAddressesRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.ListAddresses(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.sign_message": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(SignMessageRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.SignMessage(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.sign_raw_transaction": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(SignRawTransactionRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.SignRawTransaction(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.list_transactions": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(ListTransactionsRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.ListTransactions(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.set_default_fee": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(SetDefaultFeeRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.SetDefaultFee(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_mnemonic": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetMnemonicRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetMnemonic(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, "pactus.wallet.get_private_key": func(ctx context.Context, data json.RawMessage) (any, error) { req := new(GetPrivateKeyRequest) var jrpcData paramsAndHeadersWallet if err := json.Unmarshal(data, &jrpcData); err != nil { return nil, err } err := protojson.Unmarshal(jrpcData.Params, req) if err != nil { return nil, err } return s.client.GetPrivateKey(metadata.NewOutgoingContext(ctx, jrpcData.Headers), req) }, } } ================================================ FILE: www/grpc/gen/java/pactus/BlockchainGrpc.java ================================================ package pactus; import static io.grpc.MethodDescriptor.generateFullMethodName; /** *
 * Blockchain service defines RPC methods for interacting with the blockchain.
 * 
*/ @io.grpc.stub.annotations.GrpcGenerated public final class BlockchainGrpc { private BlockchainGrpc() {} public static final java.lang.String SERVICE_NAME = "pactus.Blockchain"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor getGetBlockMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetBlock", requestType = pactus.BlockchainOuterClass.GetBlockRequest.class, responseType = pactus.BlockchainOuterClass.GetBlockResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetBlockMethod() { io.grpc.MethodDescriptor getGetBlockMethod; if ((getGetBlockMethod = BlockchainGrpc.getGetBlockMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetBlockMethod = BlockchainGrpc.getGetBlockMethod) == null) { BlockchainGrpc.getGetBlockMethod = getGetBlockMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetBlock")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetBlock")) .build(); } } } return getGetBlockMethod; } private static volatile io.grpc.MethodDescriptor getGetBlockHashMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetBlockHash", requestType = pactus.BlockchainOuterClass.GetBlockHashRequest.class, responseType = pactus.BlockchainOuterClass.GetBlockHashResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetBlockHashMethod() { io.grpc.MethodDescriptor getGetBlockHashMethod; if ((getGetBlockHashMethod = BlockchainGrpc.getGetBlockHashMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetBlockHashMethod = BlockchainGrpc.getGetBlockHashMethod) == null) { BlockchainGrpc.getGetBlockHashMethod = getGetBlockHashMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetBlockHash")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockHashRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockHashResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetBlockHash")) .build(); } } } return getGetBlockHashMethod; } private static volatile io.grpc.MethodDescriptor getGetBlockHeightMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetBlockHeight", requestType = pactus.BlockchainOuterClass.GetBlockHeightRequest.class, responseType = pactus.BlockchainOuterClass.GetBlockHeightResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetBlockHeightMethod() { io.grpc.MethodDescriptor getGetBlockHeightMethod; if ((getGetBlockHeightMethod = BlockchainGrpc.getGetBlockHeightMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetBlockHeightMethod = BlockchainGrpc.getGetBlockHeightMethod) == null) { BlockchainGrpc.getGetBlockHeightMethod = getGetBlockHeightMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetBlockHeight")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockHeightRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockHeightResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetBlockHeight")) .build(); } } } return getGetBlockHeightMethod; } private static volatile io.grpc.MethodDescriptor getGetBlockchainInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetBlockchainInfo", requestType = pactus.BlockchainOuterClass.GetBlockchainInfoRequest.class, responseType = pactus.BlockchainOuterClass.GetBlockchainInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetBlockchainInfoMethod() { io.grpc.MethodDescriptor getGetBlockchainInfoMethod; if ((getGetBlockchainInfoMethod = BlockchainGrpc.getGetBlockchainInfoMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetBlockchainInfoMethod = BlockchainGrpc.getGetBlockchainInfoMethod) == null) { BlockchainGrpc.getGetBlockchainInfoMethod = getGetBlockchainInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetBlockchainInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockchainInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetBlockchainInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetBlockchainInfo")) .build(); } } } return getGetBlockchainInfoMethod; } private static volatile io.grpc.MethodDescriptor getGetCommitteeInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetCommitteeInfo", requestType = pactus.BlockchainOuterClass.GetCommitteeInfoRequest.class, responseType = pactus.BlockchainOuterClass.GetCommitteeInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetCommitteeInfoMethod() { io.grpc.MethodDescriptor getGetCommitteeInfoMethod; if ((getGetCommitteeInfoMethod = BlockchainGrpc.getGetCommitteeInfoMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetCommitteeInfoMethod = BlockchainGrpc.getGetCommitteeInfoMethod) == null) { BlockchainGrpc.getGetCommitteeInfoMethod = getGetCommitteeInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetCommitteeInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetCommitteeInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetCommitteeInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetCommitteeInfo")) .build(); } } } return getGetCommitteeInfoMethod; } private static volatile io.grpc.MethodDescriptor getGetConsensusInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetConsensusInfo", requestType = pactus.BlockchainOuterClass.GetConsensusInfoRequest.class, responseType = pactus.BlockchainOuterClass.GetConsensusInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetConsensusInfoMethod() { io.grpc.MethodDescriptor getGetConsensusInfoMethod; if ((getGetConsensusInfoMethod = BlockchainGrpc.getGetConsensusInfoMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetConsensusInfoMethod = BlockchainGrpc.getGetConsensusInfoMethod) == null) { BlockchainGrpc.getGetConsensusInfoMethod = getGetConsensusInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetConsensusInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetConsensusInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetConsensusInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetConsensusInfo")) .build(); } } } return getGetConsensusInfoMethod; } private static volatile io.grpc.MethodDescriptor getGetAccountMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetAccount", requestType = pactus.BlockchainOuterClass.GetAccountRequest.class, responseType = pactus.BlockchainOuterClass.GetAccountResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetAccountMethod() { io.grpc.MethodDescriptor getGetAccountMethod; if ((getGetAccountMethod = BlockchainGrpc.getGetAccountMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetAccountMethod = BlockchainGrpc.getGetAccountMethod) == null) { BlockchainGrpc.getGetAccountMethod = getGetAccountMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetAccount")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetAccountRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetAccountResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetAccount")) .build(); } } } return getGetAccountMethod; } private static volatile io.grpc.MethodDescriptor getGetValidatorMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetValidator", requestType = pactus.BlockchainOuterClass.GetValidatorRequest.class, responseType = pactus.BlockchainOuterClass.GetValidatorResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetValidatorMethod() { io.grpc.MethodDescriptor getGetValidatorMethod; if ((getGetValidatorMethod = BlockchainGrpc.getGetValidatorMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetValidatorMethod = BlockchainGrpc.getGetValidatorMethod) == null) { BlockchainGrpc.getGetValidatorMethod = getGetValidatorMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetValidator")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetValidatorRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetValidatorResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetValidator")) .build(); } } } return getGetValidatorMethod; } private static volatile io.grpc.MethodDescriptor getGetValidatorByNumberMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetValidatorByNumber", requestType = pactus.BlockchainOuterClass.GetValidatorByNumberRequest.class, responseType = pactus.BlockchainOuterClass.GetValidatorResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetValidatorByNumberMethod() { io.grpc.MethodDescriptor getGetValidatorByNumberMethod; if ((getGetValidatorByNumberMethod = BlockchainGrpc.getGetValidatorByNumberMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetValidatorByNumberMethod = BlockchainGrpc.getGetValidatorByNumberMethod) == null) { BlockchainGrpc.getGetValidatorByNumberMethod = getGetValidatorByNumberMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetValidatorByNumber")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetValidatorByNumberRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetValidatorResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetValidatorByNumber")) .build(); } } } return getGetValidatorByNumberMethod; } private static volatile io.grpc.MethodDescriptor getGetValidatorAddressesMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetValidatorAddresses", requestType = pactus.BlockchainOuterClass.GetValidatorAddressesRequest.class, responseType = pactus.BlockchainOuterClass.GetValidatorAddressesResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetValidatorAddressesMethod() { io.grpc.MethodDescriptor getGetValidatorAddressesMethod; if ((getGetValidatorAddressesMethod = BlockchainGrpc.getGetValidatorAddressesMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetValidatorAddressesMethod = BlockchainGrpc.getGetValidatorAddressesMethod) == null) { BlockchainGrpc.getGetValidatorAddressesMethod = getGetValidatorAddressesMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetValidatorAddresses")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetValidatorAddressesRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetValidatorAddressesResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetValidatorAddresses")) .build(); } } } return getGetValidatorAddressesMethod; } private static volatile io.grpc.MethodDescriptor getGetPublicKeyMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetPublicKey", requestType = pactus.BlockchainOuterClass.GetPublicKeyRequest.class, responseType = pactus.BlockchainOuterClass.GetPublicKeyResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetPublicKeyMethod() { io.grpc.MethodDescriptor getGetPublicKeyMethod; if ((getGetPublicKeyMethod = BlockchainGrpc.getGetPublicKeyMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetPublicKeyMethod = BlockchainGrpc.getGetPublicKeyMethod) == null) { BlockchainGrpc.getGetPublicKeyMethod = getGetPublicKeyMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetPublicKey")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetPublicKeyRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetPublicKeyResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetPublicKey")) .build(); } } } return getGetPublicKeyMethod; } private static volatile io.grpc.MethodDescriptor getGetTxPoolContentMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetTxPoolContent", requestType = pactus.BlockchainOuterClass.GetTxPoolContentRequest.class, responseType = pactus.BlockchainOuterClass.GetTxPoolContentResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetTxPoolContentMethod() { io.grpc.MethodDescriptor getGetTxPoolContentMethod; if ((getGetTxPoolContentMethod = BlockchainGrpc.getGetTxPoolContentMethod) == null) { synchronized (BlockchainGrpc.class) { if ((getGetTxPoolContentMethod = BlockchainGrpc.getGetTxPoolContentMethod) == null) { BlockchainGrpc.getGetTxPoolContentMethod = getGetTxPoolContentMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetTxPoolContent")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetTxPoolContentRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.BlockchainOuterClass.GetTxPoolContentResponse.getDefaultInstance())) .setSchemaDescriptor(new BlockchainMethodDescriptorSupplier("GetTxPoolContent")) .build(); } } } return getGetTxPoolContentMethod; } /** * Creates a new async stub that supports all call types for the service */ public static BlockchainStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public BlockchainStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainStub(channel, callOptions); } }; return BlockchainStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static BlockchainBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public BlockchainBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainBlockingV2Stub(channel, callOptions); } }; return BlockchainBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static BlockchainBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public BlockchainBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainBlockingStub(channel, callOptions); } }; return BlockchainBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static BlockchainFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public BlockchainFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainFutureStub(channel, callOptions); } }; return BlockchainFutureStub.newStub(factory, channel); } /** *
   * Blockchain service defines RPC methods for interacting with the blockchain.
   * 
*/ public interface AsyncService { /** *
     * GetBlock retrieves information about a block based on the provided request parameters.
     * 
*/ default void getBlock(pactus.BlockchainOuterClass.GetBlockRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetBlockMethod(), responseObserver); } /** *
     * GetBlockHash retrieves the hash of a block at the specified height.
     * 
*/ default void getBlockHash(pactus.BlockchainOuterClass.GetBlockHashRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetBlockHashMethod(), responseObserver); } /** *
     * GetBlockHeight retrieves the height of a block with the specified hash.
     * 
*/ default void getBlockHeight(pactus.BlockchainOuterClass.GetBlockHeightRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetBlockHeightMethod(), responseObserver); } /** *
     * GetBlockchainInfo retrieves general information about the blockchain.
     * 
*/ default void getBlockchainInfo(pactus.BlockchainOuterClass.GetBlockchainInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetBlockchainInfoMethod(), responseObserver); } /** *
     * GetCommitteeInfo retrieves information about the current committee.
     * 
*/ default void getCommitteeInfo(pactus.BlockchainOuterClass.GetCommitteeInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetCommitteeInfoMethod(), responseObserver); } /** *
     * GetConsensusInfo retrieves information about the consensus instances.
     * 
*/ default void getConsensusInfo(pactus.BlockchainOuterClass.GetConsensusInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetConsensusInfoMethod(), responseObserver); } /** *
     * GetAccount retrieves information about an account based on the provided address.
     * 
*/ default void getAccount(pactus.BlockchainOuterClass.GetAccountRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetAccountMethod(), responseObserver); } /** *
     * GetValidator retrieves information about a validator based on the provided address.
     * 
*/ default void getValidator(pactus.BlockchainOuterClass.GetValidatorRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetValidatorMethod(), responseObserver); } /** *
     * GetValidatorByNumber retrieves information about a validator based on the provided number.
     * 
*/ default void getValidatorByNumber(pactus.BlockchainOuterClass.GetValidatorByNumberRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetValidatorByNumberMethod(), responseObserver); } /** *
     * GetValidatorAddresses retrieves a list of all validator addresses.
     * 
*/ default void getValidatorAddresses(pactus.BlockchainOuterClass.GetValidatorAddressesRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetValidatorAddressesMethod(), responseObserver); } /** *
     * GetPublicKey retrieves the public key of an account based on the provided address.
     * 
*/ default void getPublicKey(pactus.BlockchainOuterClass.GetPublicKeyRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetPublicKeyMethod(), responseObserver); } /** *
     * GetTxPoolContent retrieves current transactions in the transaction pool.
     * 
*/ default void getTxPoolContent(pactus.BlockchainOuterClass.GetTxPoolContentRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetTxPoolContentMethod(), responseObserver); } } /** * Base class for the server implementation of the service Blockchain. *
   * Blockchain service defines RPC methods for interacting with the blockchain.
   * 
*/ public static abstract class BlockchainImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return BlockchainGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service Blockchain. *
   * Blockchain service defines RPC methods for interacting with the blockchain.
   * 
*/ public static final class BlockchainStub extends io.grpc.stub.AbstractAsyncStub { private BlockchainStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected BlockchainStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainStub(channel, callOptions); } /** *
     * GetBlock retrieves information about a block based on the provided request parameters.
     * 
*/ public void getBlock(pactus.BlockchainOuterClass.GetBlockRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetBlockMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetBlockHash retrieves the hash of a block at the specified height.
     * 
*/ public void getBlockHash(pactus.BlockchainOuterClass.GetBlockHashRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetBlockHashMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetBlockHeight retrieves the height of a block with the specified hash.
     * 
*/ public void getBlockHeight(pactus.BlockchainOuterClass.GetBlockHeightRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetBlockHeightMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetBlockchainInfo retrieves general information about the blockchain.
     * 
*/ public void getBlockchainInfo(pactus.BlockchainOuterClass.GetBlockchainInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetBlockchainInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetCommitteeInfo retrieves information about the current committee.
     * 
*/ public void getCommitteeInfo(pactus.BlockchainOuterClass.GetCommitteeInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetCommitteeInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetConsensusInfo retrieves information about the consensus instances.
     * 
*/ public void getConsensusInfo(pactus.BlockchainOuterClass.GetConsensusInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetConsensusInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetAccount retrieves information about an account based on the provided address.
     * 
*/ public void getAccount(pactus.BlockchainOuterClass.GetAccountRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetAccountMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetValidator retrieves information about a validator based on the provided address.
     * 
*/ public void getValidator(pactus.BlockchainOuterClass.GetValidatorRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetValidatorMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetValidatorByNumber retrieves information about a validator based on the provided number.
     * 
*/ public void getValidatorByNumber(pactus.BlockchainOuterClass.GetValidatorByNumberRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetValidatorByNumberMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetValidatorAddresses retrieves a list of all validator addresses.
     * 
*/ public void getValidatorAddresses(pactus.BlockchainOuterClass.GetValidatorAddressesRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetValidatorAddressesMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetPublicKey retrieves the public key of an account based on the provided address.
     * 
*/ public void getPublicKey(pactus.BlockchainOuterClass.GetPublicKeyRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetPublicKeyMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetTxPoolContent retrieves current transactions in the transaction pool.
     * 
*/ public void getTxPoolContent(pactus.BlockchainOuterClass.GetTxPoolContentRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetTxPoolContentMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Blockchain. *
   * Blockchain service defines RPC methods for interacting with the blockchain.
   * 
*/ public static final class BlockchainBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub { private BlockchainBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected BlockchainBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainBlockingV2Stub(channel, callOptions); } /** *
     * GetBlock retrieves information about a block based on the provided request parameters.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockResponse getBlock(pactus.BlockchainOuterClass.GetBlockRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetBlockMethod(), getCallOptions(), request); } /** *
     * GetBlockHash retrieves the hash of a block at the specified height.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockHashResponse getBlockHash(pactus.BlockchainOuterClass.GetBlockHashRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetBlockHashMethod(), getCallOptions(), request); } /** *
     * GetBlockHeight retrieves the height of a block with the specified hash.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockHeightResponse getBlockHeight(pactus.BlockchainOuterClass.GetBlockHeightRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetBlockHeightMethod(), getCallOptions(), request); } /** *
     * GetBlockchainInfo retrieves general information about the blockchain.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockchainInfoResponse getBlockchainInfo(pactus.BlockchainOuterClass.GetBlockchainInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetBlockchainInfoMethod(), getCallOptions(), request); } /** *
     * GetCommitteeInfo retrieves information about the current committee.
     * 
*/ public pactus.BlockchainOuterClass.GetCommitteeInfoResponse getCommitteeInfo(pactus.BlockchainOuterClass.GetCommitteeInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetCommitteeInfoMethod(), getCallOptions(), request); } /** *
     * GetConsensusInfo retrieves information about the consensus instances.
     * 
*/ public pactus.BlockchainOuterClass.GetConsensusInfoResponse getConsensusInfo(pactus.BlockchainOuterClass.GetConsensusInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetConsensusInfoMethod(), getCallOptions(), request); } /** *
     * GetAccount retrieves information about an account based on the provided address.
     * 
*/ public pactus.BlockchainOuterClass.GetAccountResponse getAccount(pactus.BlockchainOuterClass.GetAccountRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetAccountMethod(), getCallOptions(), request); } /** *
     * GetValidator retrieves information about a validator based on the provided address.
     * 
*/ public pactus.BlockchainOuterClass.GetValidatorResponse getValidator(pactus.BlockchainOuterClass.GetValidatorRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetValidatorMethod(), getCallOptions(), request); } /** *
     * GetValidatorByNumber retrieves information about a validator based on the provided number.
     * 
*/ public pactus.BlockchainOuterClass.GetValidatorResponse getValidatorByNumber(pactus.BlockchainOuterClass.GetValidatorByNumberRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetValidatorByNumberMethod(), getCallOptions(), request); } /** *
     * GetValidatorAddresses retrieves a list of all validator addresses.
     * 
*/ public pactus.BlockchainOuterClass.GetValidatorAddressesResponse getValidatorAddresses(pactus.BlockchainOuterClass.GetValidatorAddressesRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetValidatorAddressesMethod(), getCallOptions(), request); } /** *
     * GetPublicKey retrieves the public key of an account based on the provided address.
     * 
*/ public pactus.BlockchainOuterClass.GetPublicKeyResponse getPublicKey(pactus.BlockchainOuterClass.GetPublicKeyRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetPublicKeyMethod(), getCallOptions(), request); } /** *
     * GetTxPoolContent retrieves current transactions in the transaction pool.
     * 
*/ public pactus.BlockchainOuterClass.GetTxPoolContentResponse getTxPoolContent(pactus.BlockchainOuterClass.GetTxPoolContentRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetTxPoolContentMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Blockchain. *
   * Blockchain service defines RPC methods for interacting with the blockchain.
   * 
*/ public static final class BlockchainBlockingStub extends io.grpc.stub.AbstractBlockingStub { private BlockchainBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected BlockchainBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainBlockingStub(channel, callOptions); } /** *
     * GetBlock retrieves information about a block based on the provided request parameters.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockResponse getBlock(pactus.BlockchainOuterClass.GetBlockRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetBlockMethod(), getCallOptions(), request); } /** *
     * GetBlockHash retrieves the hash of a block at the specified height.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockHashResponse getBlockHash(pactus.BlockchainOuterClass.GetBlockHashRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetBlockHashMethod(), getCallOptions(), request); } /** *
     * GetBlockHeight retrieves the height of a block with the specified hash.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockHeightResponse getBlockHeight(pactus.BlockchainOuterClass.GetBlockHeightRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetBlockHeightMethod(), getCallOptions(), request); } /** *
     * GetBlockchainInfo retrieves general information about the blockchain.
     * 
*/ public pactus.BlockchainOuterClass.GetBlockchainInfoResponse getBlockchainInfo(pactus.BlockchainOuterClass.GetBlockchainInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetBlockchainInfoMethod(), getCallOptions(), request); } /** *
     * GetCommitteeInfo retrieves information about the current committee.
     * 
*/ public pactus.BlockchainOuterClass.GetCommitteeInfoResponse getCommitteeInfo(pactus.BlockchainOuterClass.GetCommitteeInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetCommitteeInfoMethod(), getCallOptions(), request); } /** *
     * GetConsensusInfo retrieves information about the consensus instances.
     * 
*/ public pactus.BlockchainOuterClass.GetConsensusInfoResponse getConsensusInfo(pactus.BlockchainOuterClass.GetConsensusInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetConsensusInfoMethod(), getCallOptions(), request); } /** *
     * GetAccount retrieves information about an account based on the provided address.
     * 
*/ public pactus.BlockchainOuterClass.GetAccountResponse getAccount(pactus.BlockchainOuterClass.GetAccountRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetAccountMethod(), getCallOptions(), request); } /** *
     * GetValidator retrieves information about a validator based on the provided address.
     * 
*/ public pactus.BlockchainOuterClass.GetValidatorResponse getValidator(pactus.BlockchainOuterClass.GetValidatorRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetValidatorMethod(), getCallOptions(), request); } /** *
     * GetValidatorByNumber retrieves information about a validator based on the provided number.
     * 
*/ public pactus.BlockchainOuterClass.GetValidatorResponse getValidatorByNumber(pactus.BlockchainOuterClass.GetValidatorByNumberRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetValidatorByNumberMethod(), getCallOptions(), request); } /** *
     * GetValidatorAddresses retrieves a list of all validator addresses.
     * 
*/ public pactus.BlockchainOuterClass.GetValidatorAddressesResponse getValidatorAddresses(pactus.BlockchainOuterClass.GetValidatorAddressesRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetValidatorAddressesMethod(), getCallOptions(), request); } /** *
     * GetPublicKey retrieves the public key of an account based on the provided address.
     * 
*/ public pactus.BlockchainOuterClass.GetPublicKeyResponse getPublicKey(pactus.BlockchainOuterClass.GetPublicKeyRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetPublicKeyMethod(), getCallOptions(), request); } /** *
     * GetTxPoolContent retrieves current transactions in the transaction pool.
     * 
*/ public pactus.BlockchainOuterClass.GetTxPoolContentResponse getTxPoolContent(pactus.BlockchainOuterClass.GetTxPoolContentRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetTxPoolContentMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service Blockchain. *
   * Blockchain service defines RPC methods for interacting with the blockchain.
   * 
*/ public static final class BlockchainFutureStub extends io.grpc.stub.AbstractFutureStub { private BlockchainFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected BlockchainFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new BlockchainFutureStub(channel, callOptions); } /** *
     * GetBlock retrieves information about a block based on the provided request parameters.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getBlock( pactus.BlockchainOuterClass.GetBlockRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetBlockMethod(), getCallOptions()), request); } /** *
     * GetBlockHash retrieves the hash of a block at the specified height.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getBlockHash( pactus.BlockchainOuterClass.GetBlockHashRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetBlockHashMethod(), getCallOptions()), request); } /** *
     * GetBlockHeight retrieves the height of a block with the specified hash.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getBlockHeight( pactus.BlockchainOuterClass.GetBlockHeightRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetBlockHeightMethod(), getCallOptions()), request); } /** *
     * GetBlockchainInfo retrieves general information about the blockchain.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getBlockchainInfo( pactus.BlockchainOuterClass.GetBlockchainInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetBlockchainInfoMethod(), getCallOptions()), request); } /** *
     * GetCommitteeInfo retrieves information about the current committee.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getCommitteeInfo( pactus.BlockchainOuterClass.GetCommitteeInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetCommitteeInfoMethod(), getCallOptions()), request); } /** *
     * GetConsensusInfo retrieves information about the consensus instances.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getConsensusInfo( pactus.BlockchainOuterClass.GetConsensusInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetConsensusInfoMethod(), getCallOptions()), request); } /** *
     * GetAccount retrieves information about an account based on the provided address.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getAccount( pactus.BlockchainOuterClass.GetAccountRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetAccountMethod(), getCallOptions()), request); } /** *
     * GetValidator retrieves information about a validator based on the provided address.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getValidator( pactus.BlockchainOuterClass.GetValidatorRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetValidatorMethod(), getCallOptions()), request); } /** *
     * GetValidatorByNumber retrieves information about a validator based on the provided number.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getValidatorByNumber( pactus.BlockchainOuterClass.GetValidatorByNumberRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetValidatorByNumberMethod(), getCallOptions()), request); } /** *
     * GetValidatorAddresses retrieves a list of all validator addresses.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getValidatorAddresses( pactus.BlockchainOuterClass.GetValidatorAddressesRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetValidatorAddressesMethod(), getCallOptions()), request); } /** *
     * GetPublicKey retrieves the public key of an account based on the provided address.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getPublicKey( pactus.BlockchainOuterClass.GetPublicKeyRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetPublicKeyMethod(), getCallOptions()), request); } /** *
     * GetTxPoolContent retrieves current transactions in the transaction pool.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getTxPoolContent( pactus.BlockchainOuterClass.GetTxPoolContentRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetTxPoolContentMethod(), getCallOptions()), request); } } private static final int METHODID_GET_BLOCK = 0; private static final int METHODID_GET_BLOCK_HASH = 1; private static final int METHODID_GET_BLOCK_HEIGHT = 2; private static final int METHODID_GET_BLOCKCHAIN_INFO = 3; private static final int METHODID_GET_COMMITTEE_INFO = 4; private static final int METHODID_GET_CONSENSUS_INFO = 5; private static final int METHODID_GET_ACCOUNT = 6; private static final int METHODID_GET_VALIDATOR = 7; private static final int METHODID_GET_VALIDATOR_BY_NUMBER = 8; private static final int METHODID_GET_VALIDATOR_ADDRESSES = 9; private static final int METHODID_GET_PUBLIC_KEY = 10; private static final int METHODID_GET_TX_POOL_CONTENT = 11; private static final class MethodHandlers implements io.grpc.stub.ServerCalls.UnaryMethod, io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_GET_BLOCK: serviceImpl.getBlock((pactus.BlockchainOuterClass.GetBlockRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_BLOCK_HASH: serviceImpl.getBlockHash((pactus.BlockchainOuterClass.GetBlockHashRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_BLOCK_HEIGHT: serviceImpl.getBlockHeight((pactus.BlockchainOuterClass.GetBlockHeightRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_BLOCKCHAIN_INFO: serviceImpl.getBlockchainInfo((pactus.BlockchainOuterClass.GetBlockchainInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_COMMITTEE_INFO: serviceImpl.getCommitteeInfo((pactus.BlockchainOuterClass.GetCommitteeInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_CONSENSUS_INFO: serviceImpl.getConsensusInfo((pactus.BlockchainOuterClass.GetConsensusInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_ACCOUNT: serviceImpl.getAccount((pactus.BlockchainOuterClass.GetAccountRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_VALIDATOR: serviceImpl.getValidator((pactus.BlockchainOuterClass.GetValidatorRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_VALIDATOR_BY_NUMBER: serviceImpl.getValidatorByNumber((pactus.BlockchainOuterClass.GetValidatorByNumberRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_VALIDATOR_ADDRESSES: serviceImpl.getValidatorAddresses((pactus.BlockchainOuterClass.GetValidatorAddressesRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_PUBLIC_KEY: serviceImpl.getPublicKey((pactus.BlockchainOuterClass.GetPublicKeyRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_TX_POOL_CONTENT: serviceImpl.getTxPoolContent((pactus.BlockchainOuterClass.GetTxPoolContentRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver invoke( io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetBlockMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetBlockRequest, pactus.BlockchainOuterClass.GetBlockResponse>( service, METHODID_GET_BLOCK))) .addMethod( getGetBlockHashMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetBlockHashRequest, pactus.BlockchainOuterClass.GetBlockHashResponse>( service, METHODID_GET_BLOCK_HASH))) .addMethod( getGetBlockHeightMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetBlockHeightRequest, pactus.BlockchainOuterClass.GetBlockHeightResponse>( service, METHODID_GET_BLOCK_HEIGHT))) .addMethod( getGetBlockchainInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetBlockchainInfoRequest, pactus.BlockchainOuterClass.GetBlockchainInfoResponse>( service, METHODID_GET_BLOCKCHAIN_INFO))) .addMethod( getGetCommitteeInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetCommitteeInfoRequest, pactus.BlockchainOuterClass.GetCommitteeInfoResponse>( service, METHODID_GET_COMMITTEE_INFO))) .addMethod( getGetConsensusInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetConsensusInfoRequest, pactus.BlockchainOuterClass.GetConsensusInfoResponse>( service, METHODID_GET_CONSENSUS_INFO))) .addMethod( getGetAccountMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetAccountRequest, pactus.BlockchainOuterClass.GetAccountResponse>( service, METHODID_GET_ACCOUNT))) .addMethod( getGetValidatorMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetValidatorRequest, pactus.BlockchainOuterClass.GetValidatorResponse>( service, METHODID_GET_VALIDATOR))) .addMethod( getGetValidatorByNumberMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetValidatorByNumberRequest, pactus.BlockchainOuterClass.GetValidatorResponse>( service, METHODID_GET_VALIDATOR_BY_NUMBER))) .addMethod( getGetValidatorAddressesMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetValidatorAddressesRequest, pactus.BlockchainOuterClass.GetValidatorAddressesResponse>( service, METHODID_GET_VALIDATOR_ADDRESSES))) .addMethod( getGetPublicKeyMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetPublicKeyRequest, pactus.BlockchainOuterClass.GetPublicKeyResponse>( service, METHODID_GET_PUBLIC_KEY))) .addMethod( getGetTxPoolContentMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.BlockchainOuterClass.GetTxPoolContentRequest, pactus.BlockchainOuterClass.GetTxPoolContentResponse>( service, METHODID_GET_TX_POOL_CONTENT))) .build(); } private static abstract class BlockchainBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { BlockchainBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return pactus.BlockchainOuterClass.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Blockchain"); } } private static final class BlockchainFileDescriptorSupplier extends BlockchainBaseDescriptorSupplier { BlockchainFileDescriptorSupplier() {} } private static final class BlockchainMethodDescriptorSupplier extends BlockchainBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; BlockchainMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (BlockchainGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new BlockchainFileDescriptorSupplier()) .addMethod(getGetBlockMethod()) .addMethod(getGetBlockHashMethod()) .addMethod(getGetBlockHeightMethod()) .addMethod(getGetBlockchainInfoMethod()) .addMethod(getGetCommitteeInfoMethod()) .addMethod(getGetConsensusInfoMethod()) .addMethod(getGetAccountMethod()) .addMethod(getGetValidatorMethod()) .addMethod(getGetValidatorByNumberMethod()) .addMethod(getGetValidatorAddressesMethod()) .addMethod(getGetPublicKeyMethod()) .addMethod(getGetTxPoolContentMethod()) .build(); } } } return result; } } ================================================ FILE: www/grpc/gen/java/pactus/BlockchainOuterClass.java ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: blockchain.proto // Protobuf Java Version: 4.33.2 package pactus; @com.google.protobuf.Generated public final class BlockchainOuterClass extends com.google.protobuf.GeneratedFile { private BlockchainOuterClass() {} static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "BlockchainOuterClass"); } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** *
   * Enumeration for verbosity levels when requesting block information.
   * 
* * Protobuf enum {@code pactus.BlockVerbosity} */ public enum BlockVerbosity implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Request only block data.
     * 
* * BLOCK_VERBOSITY_DATA = 0; */ BLOCK_VERBOSITY_DATA(0), /** *
     * Request block information and transaction IDs.
     * 
* * BLOCK_VERBOSITY_INFO = 1; */ BLOCK_VERBOSITY_INFO(1), /** *
     * Request block information and detailed transaction data.
     * 
* * BLOCK_VERBOSITY_TRANSACTIONS = 2; */ BLOCK_VERBOSITY_TRANSACTIONS(2), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "BlockVerbosity"); } /** *
     * Request only block data.
     * 
* * BLOCK_VERBOSITY_DATA = 0; */ public static final int BLOCK_VERBOSITY_DATA_VALUE = 0; /** *
     * Request block information and transaction IDs.
     * 
* * BLOCK_VERBOSITY_INFO = 1; */ public static final int BLOCK_VERBOSITY_INFO_VALUE = 1; /** *
     * Request block information and detailed transaction data.
     * 
* * BLOCK_VERBOSITY_TRANSACTIONS = 2; */ public static final int BLOCK_VERBOSITY_TRANSACTIONS_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static BlockVerbosity valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static BlockVerbosity forNumber(int value) { switch (value) { case 0: return BLOCK_VERBOSITY_DATA; case 1: return BLOCK_VERBOSITY_INFO; case 2: return BLOCK_VERBOSITY_TRANSACTIONS; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< BlockVerbosity> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public BlockVerbosity findValueByNumber(int number) { return BlockVerbosity.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.BlockchainOuterClass.getDescriptor().getEnumTypes().get(0); } private static final BlockVerbosity[] VALUES = values(); public static BlockVerbosity valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private BlockVerbosity(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.BlockVerbosity) } /** *
   * Enumeration for types of votes.
   * 
* * Protobuf enum {@code pactus.VoteType} */ public enum VoteType implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Unspecified vote type.
     * 
* * VOTE_TYPE_UNSPECIFIED = 0; */ VOTE_TYPE_UNSPECIFIED(0), /** *
     * Prepare vote type.
     * 
* * VOTE_TYPE_PREPARE = 1; */ VOTE_TYPE_PREPARE(1), /** *
     * Precommit vote type.
     * 
* * VOTE_TYPE_PRECOMMIT = 2; */ VOTE_TYPE_PRECOMMIT(2), /** *
     * Change-proposer:pre-vote vote type.
     * 
* * VOTE_TYPE_CP_PRE_VOTE = 3; */ VOTE_TYPE_CP_PRE_VOTE(3), /** *
     * Change-proposer:main-vote vote type.
     * 
* * VOTE_TYPE_CP_MAIN_VOTE = 4; */ VOTE_TYPE_CP_MAIN_VOTE(4), /** *
     * Change-proposer:decided vote type.
     * 
* * VOTE_TYPE_CP_DECIDED = 5; */ VOTE_TYPE_CP_DECIDED(5), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "VoteType"); } /** *
     * Unspecified vote type.
     * 
* * VOTE_TYPE_UNSPECIFIED = 0; */ public static final int VOTE_TYPE_UNSPECIFIED_VALUE = 0; /** *
     * Prepare vote type.
     * 
* * VOTE_TYPE_PREPARE = 1; */ public static final int VOTE_TYPE_PREPARE_VALUE = 1; /** *
     * Precommit vote type.
     * 
* * VOTE_TYPE_PRECOMMIT = 2; */ public static final int VOTE_TYPE_PRECOMMIT_VALUE = 2; /** *
     * Change-proposer:pre-vote vote type.
     * 
* * VOTE_TYPE_CP_PRE_VOTE = 3; */ public static final int VOTE_TYPE_CP_PRE_VOTE_VALUE = 3; /** *
     * Change-proposer:main-vote vote type.
     * 
* * VOTE_TYPE_CP_MAIN_VOTE = 4; */ public static final int VOTE_TYPE_CP_MAIN_VOTE_VALUE = 4; /** *
     * Change-proposer:decided vote type.
     * 
* * VOTE_TYPE_CP_DECIDED = 5; */ public static final int VOTE_TYPE_CP_DECIDED_VALUE = 5; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static VoteType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static VoteType forNumber(int value) { switch (value) { case 0: return VOTE_TYPE_UNSPECIFIED; case 1: return VOTE_TYPE_PREPARE; case 2: return VOTE_TYPE_PRECOMMIT; case 3: return VOTE_TYPE_CP_PRE_VOTE; case 4: return VOTE_TYPE_CP_MAIN_VOTE; case 5: return VOTE_TYPE_CP_DECIDED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< VoteType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public VoteType findValueByNumber(int number) { return VoteType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.BlockchainOuterClass.getDescriptor().getEnumTypes().get(1); } private static final VoteType[] VALUES = values(); public static VoteType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private VoteType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.VoteType) } public interface GetAccountRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetAccountRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The address of the account to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address of the account to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Request message for retrieving account information.
   * 
* * Protobuf type {@code pactus.GetAccountRequest} */ public static final class GetAccountRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetAccountRequest) GetAccountRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetAccountRequest"); } // Use GetAccountRequest.newBuilder() to construct. private GetAccountRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetAccountRequest() { address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetAccountRequest.class, pactus.BlockchainOuterClass.GetAccountRequest.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address of the account to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address of the account to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetAccountRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetAccountRequest other = (pactus.BlockchainOuterClass.GetAccountRequest) obj; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetAccountRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetAccountRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetAccountRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving account information.
     * 
* * Protobuf type {@code pactus.GetAccountRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetAccountRequest) pactus.BlockchainOuterClass.GetAccountRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetAccountRequest.class, pactus.BlockchainOuterClass.GetAccountRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetAccountRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetAccountRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountRequest build() { pactus.BlockchainOuterClass.GetAccountRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountRequest buildPartial() { pactus.BlockchainOuterClass.GetAccountRequest result = new pactus.BlockchainOuterClass.GetAccountRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetAccountRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetAccountRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetAccountRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetAccountRequest other) { if (other == pactus.BlockchainOuterClass.GetAccountRequest.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The address of the account to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the account to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the account to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address of the account to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address of the account to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetAccountRequest) } // @@protoc_insertion_point(class_scope:pactus.GetAccountRequest) private static final pactus.BlockchainOuterClass.GetAccountRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetAccountRequest(); } public static pactus.BlockchainOuterClass.GetAccountRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetAccountRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetAccountResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetAccountResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Detailed information about the account.
     * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; * @return Whether the account field is set. */ boolean hasAccount(); /** *
     * Detailed information about the account.
     * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; * @return The account. */ pactus.BlockchainOuterClass.AccountInfo getAccount(); /** *
     * Detailed information about the account.
     * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ pactus.BlockchainOuterClass.AccountInfoOrBuilder getAccountOrBuilder(); } /** *
   * Response message contains account information.
   * 
* * Protobuf type {@code pactus.GetAccountResponse} */ public static final class GetAccountResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetAccountResponse) GetAccountResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetAccountResponse"); } // Use GetAccountResponse.newBuilder() to construct. private GetAccountResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetAccountResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetAccountResponse.class, pactus.BlockchainOuterClass.GetAccountResponse.Builder.class); } private int bitField0_; public static final int ACCOUNT_FIELD_NUMBER = 1; private pactus.BlockchainOuterClass.AccountInfo account_; /** *
     * Detailed information about the account.
     * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; * @return Whether the account field is set. */ @java.lang.Override public boolean hasAccount() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Detailed information about the account.
     * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; * @return The account. */ @java.lang.Override public pactus.BlockchainOuterClass.AccountInfo getAccount() { return account_ == null ? pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance() : account_; } /** *
     * Detailed information about the account.
     * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ @java.lang.Override public pactus.BlockchainOuterClass.AccountInfoOrBuilder getAccountOrBuilder() { return account_ == null ? pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance() : account_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getAccount()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getAccount()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetAccountResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetAccountResponse other = (pactus.BlockchainOuterClass.GetAccountResponse) obj; if (hasAccount() != other.hasAccount()) return false; if (hasAccount()) { if (!getAccount() .equals(other.getAccount())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasAccount()) { hash = (37 * hash) + ACCOUNT_FIELD_NUMBER; hash = (53 * hash) + getAccount().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetAccountResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetAccountResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetAccountResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains account information.
     * 
* * Protobuf type {@code pactus.GetAccountResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetAccountResponse) pactus.BlockchainOuterClass.GetAccountResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetAccountResponse.class, pactus.BlockchainOuterClass.GetAccountResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetAccountResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetAccountFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; account_ = null; if (accountBuilder_ != null) { accountBuilder_.dispose(); accountBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetAccountResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetAccountResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountResponse build() { pactus.BlockchainOuterClass.GetAccountResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountResponse buildPartial() { pactus.BlockchainOuterClass.GetAccountResponse result = new pactus.BlockchainOuterClass.GetAccountResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetAccountResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.account_ = accountBuilder_ == null ? account_ : accountBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetAccountResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetAccountResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetAccountResponse other) { if (other == pactus.BlockchainOuterClass.GetAccountResponse.getDefaultInstance()) return this; if (other.hasAccount()) { mergeAccount(other.getAccount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( internalGetAccountFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private pactus.BlockchainOuterClass.AccountInfo account_; private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.AccountInfo, pactus.BlockchainOuterClass.AccountInfo.Builder, pactus.BlockchainOuterClass.AccountInfoOrBuilder> accountBuilder_; /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; * @return Whether the account field is set. */ public boolean hasAccount() { return ((bitField0_ & 0x00000001) != 0); } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; * @return The account. */ public pactus.BlockchainOuterClass.AccountInfo getAccount() { if (accountBuilder_ == null) { return account_ == null ? pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance() : account_; } else { return accountBuilder_.getMessage(); } } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ public Builder setAccount(pactus.BlockchainOuterClass.AccountInfo value) { if (accountBuilder_ == null) { if (value == null) { throw new NullPointerException(); } account_ = value; } else { accountBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ public Builder setAccount( pactus.BlockchainOuterClass.AccountInfo.Builder builderForValue) { if (accountBuilder_ == null) { account_ = builderForValue.build(); } else { accountBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ public Builder mergeAccount(pactus.BlockchainOuterClass.AccountInfo value) { if (accountBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && account_ != null && account_ != pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance()) { getAccountBuilder().mergeFrom(value); } else { account_ = value; } } else { accountBuilder_.mergeFrom(value); } if (account_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ public Builder clearAccount() { bitField0_ = (bitField0_ & ~0x00000001); account_ = null; if (accountBuilder_ != null) { accountBuilder_.dispose(); accountBuilder_ = null; } onChanged(); return this; } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ public pactus.BlockchainOuterClass.AccountInfo.Builder getAccountBuilder() { bitField0_ |= 0x00000001; onChanged(); return internalGetAccountFieldBuilder().getBuilder(); } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ public pactus.BlockchainOuterClass.AccountInfoOrBuilder getAccountOrBuilder() { if (accountBuilder_ != null) { return accountBuilder_.getMessageOrBuilder(); } else { return account_ == null ? pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance() : account_; } } /** *
       * Detailed information about the account.
       * 
* * .pactus.AccountInfo account = 1 [json_name = "account"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.AccountInfo, pactus.BlockchainOuterClass.AccountInfo.Builder, pactus.BlockchainOuterClass.AccountInfoOrBuilder> internalGetAccountFieldBuilder() { if (accountBuilder_ == null) { accountBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.AccountInfo, pactus.BlockchainOuterClass.AccountInfo.Builder, pactus.BlockchainOuterClass.AccountInfoOrBuilder>( getAccount(), getParentForChildren(), isClean()); account_ = null; } return accountBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetAccountResponse) } // @@protoc_insertion_point(class_scope:pactus.GetAccountResponse) private static final pactus.BlockchainOuterClass.GetAccountResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetAccountResponse(); } public static pactus.BlockchainOuterClass.GetAccountResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetAccountResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetAccountResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorAddressesRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorAddressesRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for retrieving validator addresses.
   * 
* * Protobuf type {@code pactus.GetValidatorAddressesRequest} */ public static final class GetValidatorAddressesRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorAddressesRequest) GetValidatorAddressesRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorAddressesRequest"); } // Use GetValidatorAddressesRequest.newBuilder() to construct. private GetValidatorAddressesRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorAddressesRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorAddressesRequest.class, pactus.BlockchainOuterClass.GetValidatorAddressesRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetValidatorAddressesRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetValidatorAddressesRequest other = (pactus.BlockchainOuterClass.GetValidatorAddressesRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetValidatorAddressesRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving validator addresses.
     * 
* * Protobuf type {@code pactus.GetValidatorAddressesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorAddressesRequest) pactus.BlockchainOuterClass.GetValidatorAddressesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorAddressesRequest.class, pactus.BlockchainOuterClass.GetValidatorAddressesRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetValidatorAddressesRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetValidatorAddressesRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesRequest build() { pactus.BlockchainOuterClass.GetValidatorAddressesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesRequest buildPartial() { pactus.BlockchainOuterClass.GetValidatorAddressesRequest result = new pactus.BlockchainOuterClass.GetValidatorAddressesRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetValidatorAddressesRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetValidatorAddressesRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetValidatorAddressesRequest other) { if (other == pactus.BlockchainOuterClass.GetValidatorAddressesRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorAddressesRequest) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorAddressesRequest) private static final pactus.BlockchainOuterClass.GetValidatorAddressesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetValidatorAddressesRequest(); } public static pactus.BlockchainOuterClass.GetValidatorAddressesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorAddressesRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorAddressesResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorAddressesResponse) com.google.protobuf.MessageOrBuilder { /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return A list containing the addresses. */ java.util.List getAddressesList(); /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return The count of addresses. */ int getAddressesCount(); /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index of the element to return. * @return The addresses at the given index. */ java.lang.String getAddresses(int index); /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index of the value to return. * @return The bytes of the addresses at the given index. */ com.google.protobuf.ByteString getAddressesBytes(int index); } /** *
   * Response message contains list of validator addresses.
   * 
* * Protobuf type {@code pactus.GetValidatorAddressesResponse} */ public static final class GetValidatorAddressesResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorAddressesResponse) GetValidatorAddressesResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorAddressesResponse"); } // Use GetValidatorAddressesResponse.newBuilder() to construct. private GetValidatorAddressesResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorAddressesResponse() { addresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorAddressesResponse.class, pactus.BlockchainOuterClass.GetValidatorAddressesResponse.Builder.class); } public static final int ADDRESSES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList addresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return A list containing the addresses. */ public com.google.protobuf.ProtocolStringList getAddressesList() { return addresses_; } /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return The count of addresses. */ public int getAddressesCount() { return addresses_.size(); } /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index of the element to return. * @return The addresses at the given index. */ public java.lang.String getAddresses(int index) { return addresses_.get(index); } /** *
     * List of validator addresses.
     * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index of the value to return. * @return The bytes of the addresses at the given index. */ public com.google.protobuf.ByteString getAddressesBytes(int index) { return addresses_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < addresses_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 1, addresses_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < addresses_.size(); i++) { dataSize += computeStringSizeNoTag(addresses_.getRaw(i)); } size += dataSize; size += 1 * getAddressesList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetValidatorAddressesResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetValidatorAddressesResponse other = (pactus.BlockchainOuterClass.GetValidatorAddressesResponse) obj; if (!getAddressesList() .equals(other.getAddressesList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAddressesCount() > 0) { hash = (37 * hash) + ADDRESSES_FIELD_NUMBER; hash = (53 * hash) + getAddressesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetValidatorAddressesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains list of validator addresses.
     * 
* * Protobuf type {@code pactus.GetValidatorAddressesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorAddressesResponse) pactus.BlockchainOuterClass.GetValidatorAddressesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorAddressesResponse.class, pactus.BlockchainOuterClass.GetValidatorAddressesResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetValidatorAddressesResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; addresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorAddressesResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetValidatorAddressesResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesResponse build() { pactus.BlockchainOuterClass.GetValidatorAddressesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesResponse buildPartial() { pactus.BlockchainOuterClass.GetValidatorAddressesResponse result = new pactus.BlockchainOuterClass.GetValidatorAddressesResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetValidatorAddressesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { addresses_.makeImmutable(); result.addresses_ = addresses_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetValidatorAddressesResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetValidatorAddressesResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetValidatorAddressesResponse other) { if (other == pactus.BlockchainOuterClass.GetValidatorAddressesResponse.getDefaultInstance()) return this; if (!other.addresses_.isEmpty()) { if (addresses_.isEmpty()) { addresses_ = other.addresses_; bitField0_ |= 0x00000001; } else { ensureAddressesIsMutable(); addresses_.addAll(other.addresses_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); ensureAddressesIsMutable(); addresses_.add(s); break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.LazyStringArrayList addresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureAddressesIsMutable() { if (!addresses_.isModifiable()) { addresses_ = new com.google.protobuf.LazyStringArrayList(addresses_); } bitField0_ |= 0x00000001; } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return A list containing the addresses. */ public com.google.protobuf.ProtocolStringList getAddressesList() { addresses_.makeImmutable(); return addresses_; } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return The count of addresses. */ public int getAddressesCount() { return addresses_.size(); } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index of the element to return. * @return The addresses at the given index. */ public java.lang.String getAddresses(int index) { return addresses_.get(index); } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index of the value to return. * @return The bytes of the addresses at the given index. */ public com.google.protobuf.ByteString getAddressesBytes(int index) { return addresses_.getByteString(index); } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param index The index to set the value at. * @param value The addresses to set. * @return This builder for chaining. */ public Builder setAddresses( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureAddressesIsMutable(); addresses_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param value The addresses to add. * @return This builder for chaining. */ public Builder addAddresses( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureAddressesIsMutable(); addresses_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param values The addresses to add. * @return This builder for chaining. */ public Builder addAllAddresses( java.lang.Iterable values) { ensureAddressesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, addresses_); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @return This builder for chaining. */ public Builder clearAddresses() { addresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001);; onChanged(); return this; } /** *
       * List of validator addresses.
       * 
* * repeated string addresses = 1 [json_name = "addresses"]; * @param value The bytes of the addresses to add. * @return This builder for chaining. */ public Builder addAddressesBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureAddressesIsMutable(); addresses_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorAddressesResponse) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorAddressesResponse) private static final pactus.BlockchainOuterClass.GetValidatorAddressesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetValidatorAddressesResponse(); } public static pactus.BlockchainOuterClass.GetValidatorAddressesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorAddressesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorAddressesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The address of the validator to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address of the validator to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Request message for retrieving validator information by address.
   * 
* * Protobuf type {@code pactus.GetValidatorRequest} */ public static final class GetValidatorRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorRequest) GetValidatorRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorRequest"); } // Use GetValidatorRequest.newBuilder() to construct. private GetValidatorRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorRequest() { address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorRequest.class, pactus.BlockchainOuterClass.GetValidatorRequest.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address of the validator to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address of the validator to retrieve information for.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetValidatorRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetValidatorRequest other = (pactus.BlockchainOuterClass.GetValidatorRequest) obj; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetValidatorRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving validator information by address.
     * 
* * Protobuf type {@code pactus.GetValidatorRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorRequest) pactus.BlockchainOuterClass.GetValidatorRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorRequest.class, pactus.BlockchainOuterClass.GetValidatorRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetValidatorRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetValidatorRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorRequest build() { pactus.BlockchainOuterClass.GetValidatorRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorRequest buildPartial() { pactus.BlockchainOuterClass.GetValidatorRequest result = new pactus.BlockchainOuterClass.GetValidatorRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetValidatorRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetValidatorRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetValidatorRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetValidatorRequest other) { if (other == pactus.BlockchainOuterClass.GetValidatorRequest.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The address of the validator to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the validator to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the validator to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address of the validator to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address of the validator to retrieve information for.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorRequest) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorRequest) private static final pactus.BlockchainOuterClass.GetValidatorRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetValidatorRequest(); } public static pactus.BlockchainOuterClass.GetValidatorRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorByNumberRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorByNumberRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The unique number of the validator to retrieve information for.
     * 
* * int32 number = 1 [json_name = "number"]; * @return The number. */ int getNumber(); } /** *
   * Request message for retrieving validator information by number.
   * 
* * Protobuf type {@code pactus.GetValidatorByNumberRequest} */ public static final class GetValidatorByNumberRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorByNumberRequest) GetValidatorByNumberRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorByNumberRequest"); } // Use GetValidatorByNumberRequest.newBuilder() to construct. private GetValidatorByNumberRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorByNumberRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorByNumberRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorByNumberRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorByNumberRequest.class, pactus.BlockchainOuterClass.GetValidatorByNumberRequest.Builder.class); } public static final int NUMBER_FIELD_NUMBER = 1; private int number_ = 0; /** *
     * The unique number of the validator to retrieve information for.
     * 
* * int32 number = 1 [json_name = "number"]; * @return The number. */ @java.lang.Override public int getNumber() { return number_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (number_ != 0) { output.writeInt32(1, number_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (number_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, number_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetValidatorByNumberRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetValidatorByNumberRequest other = (pactus.BlockchainOuterClass.GetValidatorByNumberRequest) obj; if (getNumber() != other.getNumber()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NUMBER_FIELD_NUMBER; hash = (53 * hash) + getNumber(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetValidatorByNumberRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving validator information by number.
     * 
* * Protobuf type {@code pactus.GetValidatorByNumberRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorByNumberRequest) pactus.BlockchainOuterClass.GetValidatorByNumberRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorByNumberRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorByNumberRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorByNumberRequest.class, pactus.BlockchainOuterClass.GetValidatorByNumberRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetValidatorByNumberRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; number_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorByNumberRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorByNumberRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetValidatorByNumberRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorByNumberRequest build() { pactus.BlockchainOuterClass.GetValidatorByNumberRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorByNumberRequest buildPartial() { pactus.BlockchainOuterClass.GetValidatorByNumberRequest result = new pactus.BlockchainOuterClass.GetValidatorByNumberRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetValidatorByNumberRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.number_ = number_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetValidatorByNumberRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetValidatorByNumberRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetValidatorByNumberRequest other) { if (other == pactus.BlockchainOuterClass.GetValidatorByNumberRequest.getDefaultInstance()) return this; if (other.getNumber() != 0) { setNumber(other.getNumber()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { number_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case 8 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int number_ ; /** *
       * The unique number of the validator to retrieve information for.
       * 
* * int32 number = 1 [json_name = "number"]; * @return The number. */ @java.lang.Override public int getNumber() { return number_; } /** *
       * The unique number of the validator to retrieve information for.
       * 
* * int32 number = 1 [json_name = "number"]; * @param value The number to set. * @return This builder for chaining. */ public Builder setNumber(int value) { number_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The unique number of the validator to retrieve information for.
       * 
* * int32 number = 1 [json_name = "number"]; * @return This builder for chaining. */ public Builder clearNumber() { bitField0_ = (bitField0_ & ~0x00000001); number_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorByNumberRequest) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorByNumberRequest) private static final pactus.BlockchainOuterClass.GetValidatorByNumberRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetValidatorByNumberRequest(); } public static pactus.BlockchainOuterClass.GetValidatorByNumberRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorByNumberRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorByNumberRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Detailed information about the validator.
     * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; * @return Whether the validator field is set. */ boolean hasValidator(); /** *
     * Detailed information about the validator.
     * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; * @return The validator. */ pactus.BlockchainOuterClass.ValidatorInfo getValidator(); /** *
     * Detailed information about the validator.
     * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ pactus.BlockchainOuterClass.ValidatorInfoOrBuilder getValidatorOrBuilder(); } /** *
   * Response message contains validator information.
   * 
* * Protobuf type {@code pactus.GetValidatorResponse} */ public static final class GetValidatorResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorResponse) GetValidatorResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorResponse"); } // Use GetValidatorResponse.newBuilder() to construct. private GetValidatorResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorResponse.class, pactus.BlockchainOuterClass.GetValidatorResponse.Builder.class); } private int bitField0_; public static final int VALIDATOR_FIELD_NUMBER = 1; private pactus.BlockchainOuterClass.ValidatorInfo validator_; /** *
     * Detailed information about the validator.
     * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; * @return Whether the validator field is set. */ @java.lang.Override public boolean hasValidator() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Detailed information about the validator.
     * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; * @return The validator. */ @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfo getValidator() { return validator_ == null ? pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance() : validator_; } /** *
     * Detailed information about the validator.
     * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfoOrBuilder getValidatorOrBuilder() { return validator_ == null ? pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance() : validator_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getValidator()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getValidator()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetValidatorResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetValidatorResponse other = (pactus.BlockchainOuterClass.GetValidatorResponse) obj; if (hasValidator() != other.hasValidator()) return false; if (hasValidator()) { if (!getValidator() .equals(other.getValidator())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasValidator()) { hash = (37 * hash) + VALIDATOR_FIELD_NUMBER; hash = (53 * hash) + getValidator().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetValidatorResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetValidatorResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains validator information.
     * 
* * Protobuf type {@code pactus.GetValidatorResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorResponse) pactus.BlockchainOuterClass.GetValidatorResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetValidatorResponse.class, pactus.BlockchainOuterClass.GetValidatorResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetValidatorResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetValidatorFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; validator_ = null; if (validatorBuilder_ != null) { validatorBuilder_.dispose(); validatorBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetValidatorResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetValidatorResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorResponse build() { pactus.BlockchainOuterClass.GetValidatorResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorResponse buildPartial() { pactus.BlockchainOuterClass.GetValidatorResponse result = new pactus.BlockchainOuterClass.GetValidatorResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetValidatorResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.validator_ = validatorBuilder_ == null ? validator_ : validatorBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetValidatorResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetValidatorResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetValidatorResponse other) { if (other == pactus.BlockchainOuterClass.GetValidatorResponse.getDefaultInstance()) return this; if (other.hasValidator()) { mergeValidator(other.getValidator()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( internalGetValidatorFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private pactus.BlockchainOuterClass.ValidatorInfo validator_; private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.ValidatorInfo, pactus.BlockchainOuterClass.ValidatorInfo.Builder, pactus.BlockchainOuterClass.ValidatorInfoOrBuilder> validatorBuilder_; /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; * @return Whether the validator field is set. */ public boolean hasValidator() { return ((bitField0_ & 0x00000001) != 0); } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; * @return The validator. */ public pactus.BlockchainOuterClass.ValidatorInfo getValidator() { if (validatorBuilder_ == null) { return validator_ == null ? pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance() : validator_; } else { return validatorBuilder_.getMessage(); } } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ public Builder setValidator(pactus.BlockchainOuterClass.ValidatorInfo value) { if (validatorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } validator_ = value; } else { validatorBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ public Builder setValidator( pactus.BlockchainOuterClass.ValidatorInfo.Builder builderForValue) { if (validatorBuilder_ == null) { validator_ = builderForValue.build(); } else { validatorBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ public Builder mergeValidator(pactus.BlockchainOuterClass.ValidatorInfo value) { if (validatorBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && validator_ != null && validator_ != pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance()) { getValidatorBuilder().mergeFrom(value); } else { validator_ = value; } } else { validatorBuilder_.mergeFrom(value); } if (validator_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ public Builder clearValidator() { bitField0_ = (bitField0_ & ~0x00000001); validator_ = null; if (validatorBuilder_ != null) { validatorBuilder_.dispose(); validatorBuilder_ = null; } onChanged(); return this; } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ public pactus.BlockchainOuterClass.ValidatorInfo.Builder getValidatorBuilder() { bitField0_ |= 0x00000001; onChanged(); return internalGetValidatorFieldBuilder().getBuilder(); } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ public pactus.BlockchainOuterClass.ValidatorInfoOrBuilder getValidatorOrBuilder() { if (validatorBuilder_ != null) { return validatorBuilder_.getMessageOrBuilder(); } else { return validator_ == null ? pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance() : validator_; } } /** *
       * Detailed information about the validator.
       * 
* * .pactus.ValidatorInfo validator = 1 [json_name = "validator"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.ValidatorInfo, pactus.BlockchainOuterClass.ValidatorInfo.Builder, pactus.BlockchainOuterClass.ValidatorInfoOrBuilder> internalGetValidatorFieldBuilder() { if (validatorBuilder_ == null) { validatorBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.ValidatorInfo, pactus.BlockchainOuterClass.ValidatorInfo.Builder, pactus.BlockchainOuterClass.ValidatorInfoOrBuilder>( getValidator(), getParentForChildren(), isClean()); validator_ = null; } return validatorBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorResponse) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorResponse) private static final pactus.BlockchainOuterClass.GetValidatorResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetValidatorResponse(); } public static pactus.BlockchainOuterClass.GetValidatorResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetValidatorResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetPublicKeyRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetPublicKeyRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The address for which to retrieve the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address for which to retrieve the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Request message for retrieving public key by address.
   * 
* * Protobuf type {@code pactus.GetPublicKeyRequest} */ public static final class GetPublicKeyRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetPublicKeyRequest) GetPublicKeyRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetPublicKeyRequest"); } // Use GetPublicKeyRequest.newBuilder() to construct. private GetPublicKeyRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetPublicKeyRequest() { address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetPublicKeyRequest.class, pactus.BlockchainOuterClass.GetPublicKeyRequest.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address for which to retrieve the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address for which to retrieve the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetPublicKeyRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetPublicKeyRequest other = (pactus.BlockchainOuterClass.GetPublicKeyRequest) obj; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetPublicKeyRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving public key by address.
     * 
* * Protobuf type {@code pactus.GetPublicKeyRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetPublicKeyRequest) pactus.BlockchainOuterClass.GetPublicKeyRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetPublicKeyRequest.class, pactus.BlockchainOuterClass.GetPublicKeyRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetPublicKeyRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetPublicKeyRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyRequest build() { pactus.BlockchainOuterClass.GetPublicKeyRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyRequest buildPartial() { pactus.BlockchainOuterClass.GetPublicKeyRequest result = new pactus.BlockchainOuterClass.GetPublicKeyRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetPublicKeyRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetPublicKeyRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetPublicKeyRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetPublicKeyRequest other) { if (other == pactus.BlockchainOuterClass.GetPublicKeyRequest.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The address for which to retrieve the public key.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address for which to retrieve the public key.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address for which to retrieve the public key.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address for which to retrieve the public key.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address for which to retrieve the public key.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetPublicKeyRequest) } // @@protoc_insertion_point(class_scope:pactus.GetPublicKeyRequest) private static final pactus.BlockchainOuterClass.GetPublicKeyRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetPublicKeyRequest(); } public static pactus.BlockchainOuterClass.GetPublicKeyRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetPublicKeyRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetPublicKeyResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetPublicKeyResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The public key associated with the provided address.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key associated with the provided address.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); } /** *
   * Response message contains public key information.
   * 
* * Protobuf type {@code pactus.GetPublicKeyResponse} */ public static final class GetPublicKeyResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetPublicKeyResponse) GetPublicKeyResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetPublicKeyResponse"); } // Use GetPublicKeyResponse.newBuilder() to construct. private GetPublicKeyResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetPublicKeyResponse() { publicKey_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetPublicKeyResponse.class, pactus.BlockchainOuterClass.GetPublicKeyResponse.Builder.class); } public static final int PUBLIC_KEY_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key associated with the provided address.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key associated with the provided address.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, publicKey_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, publicKey_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetPublicKeyResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetPublicKeyResponse other = (pactus.BlockchainOuterClass.GetPublicKeyResponse) obj; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetPublicKeyResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains public key information.
     * 
* * Protobuf type {@code pactus.GetPublicKeyResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetPublicKeyResponse) pactus.BlockchainOuterClass.GetPublicKeyResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetPublicKeyResponse.class, pactus.BlockchainOuterClass.GetPublicKeyResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetPublicKeyResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; publicKey_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetPublicKeyResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetPublicKeyResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyResponse build() { pactus.BlockchainOuterClass.GetPublicKeyResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyResponse buildPartial() { pactus.BlockchainOuterClass.GetPublicKeyResponse result = new pactus.BlockchainOuterClass.GetPublicKeyResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetPublicKeyResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.publicKey_ = publicKey_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetPublicKeyResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetPublicKeyResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetPublicKeyResponse other) { if (other == pactus.BlockchainOuterClass.GetPublicKeyResponse.getDefaultInstance()) return this; if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object publicKey_ = ""; /** *
       * The public key associated with the provided address.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key associated with the provided address.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key associated with the provided address.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The public key associated with the provided address.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The public key associated with the provided address.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetPublicKeyResponse) } // @@protoc_insertion_point(class_scope:pactus.GetPublicKeyResponse) private static final pactus.BlockchainOuterClass.GetPublicKeyResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetPublicKeyResponse(); } public static pactus.BlockchainOuterClass.GetPublicKeyResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetPublicKeyResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetPublicKeyResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the block to retrieve.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ int getHeight(); /** *
     * The verbosity level for block information.
     * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The enum numeric value on the wire for verbosity. */ int getVerbosityValue(); /** *
     * The verbosity level for block information.
     * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The verbosity. */ pactus.BlockchainOuterClass.BlockVerbosity getVerbosity(); } /** *
   * Request message for retrieving block information based on height and verbosity level.
   * 
* * Protobuf type {@code pactus.GetBlockRequest} */ public static final class GetBlockRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockRequest) GetBlockRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockRequest"); } // Use GetBlockRequest.newBuilder() to construct. private GetBlockRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockRequest() { verbosity_ = 0; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockRequest.class, pactus.BlockchainOuterClass.GetBlockRequest.Builder.class); } public static final int HEIGHT_FIELD_NUMBER = 1; private int height_ = 0; /** *
     * The height of the block to retrieve.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } public static final int VERBOSITY_FIELD_NUMBER = 2; private int verbosity_ = 0; /** *
     * The verbosity level for block information.
     * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The enum numeric value on the wire for verbosity. */ @java.lang.Override public int getVerbosityValue() { return verbosity_; } /** *
     * The verbosity level for block information.
     * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The verbosity. */ @java.lang.Override public pactus.BlockchainOuterClass.BlockVerbosity getVerbosity() { pactus.BlockchainOuterClass.BlockVerbosity result = pactus.BlockchainOuterClass.BlockVerbosity.forNumber(verbosity_); return result == null ? pactus.BlockchainOuterClass.BlockVerbosity.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (height_ != 0) { output.writeUInt32(1, height_); } if (verbosity_ != pactus.BlockchainOuterClass.BlockVerbosity.BLOCK_VERBOSITY_DATA.getNumber()) { output.writeEnum(2, verbosity_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, height_); } if (verbosity_ != pactus.BlockchainOuterClass.BlockVerbosity.BLOCK_VERBOSITY_DATA.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, verbosity_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockRequest other = (pactus.BlockchainOuterClass.GetBlockRequest) obj; if (getHeight() != other.getHeight()) return false; if (verbosity_ != other.verbosity_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (37 * hash) + VERBOSITY_FIELD_NUMBER; hash = (53 * hash) + verbosity_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving block information based on height and verbosity level.
     * 
* * Protobuf type {@code pactus.GetBlockRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockRequest) pactus.BlockchainOuterClass.GetBlockRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockRequest.class, pactus.BlockchainOuterClass.GetBlockRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; height_ = 0; verbosity_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockRequest build() { pactus.BlockchainOuterClass.GetBlockRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockRequest buildPartial() { pactus.BlockchainOuterClass.GetBlockRequest result = new pactus.BlockchainOuterClass.GetBlockRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.height_ = height_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.verbosity_ = verbosity_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockRequest other) { if (other == pactus.BlockchainOuterClass.GetBlockRequest.getDefaultInstance()) return this; if (other.getHeight() != 0) { setHeight(other.getHeight()); } if (other.verbosity_ != 0) { setVerbosityValue(other.getVerbosityValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { height_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { verbosity_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int height_ ; /** *
       * The height of the block to retrieve.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * The height of the block to retrieve.
       * 
* * uint32 height = 1 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the block to retrieve.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000001); height_ = 0; onChanged(); return this; } private int verbosity_ = 0; /** *
       * The verbosity level for block information.
       * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The enum numeric value on the wire for verbosity. */ @java.lang.Override public int getVerbosityValue() { return verbosity_; } /** *
       * The verbosity level for block information.
       * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @param value The enum numeric value on the wire for verbosity to set. * @return This builder for chaining. */ public Builder setVerbosityValue(int value) { verbosity_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The verbosity level for block information.
       * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The verbosity. */ @java.lang.Override public pactus.BlockchainOuterClass.BlockVerbosity getVerbosity() { pactus.BlockchainOuterClass.BlockVerbosity result = pactus.BlockchainOuterClass.BlockVerbosity.forNumber(verbosity_); return result == null ? pactus.BlockchainOuterClass.BlockVerbosity.UNRECOGNIZED : result; } /** *
       * The verbosity level for block information.
       * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @param value The verbosity to set. * @return This builder for chaining. */ public Builder setVerbosity(pactus.BlockchainOuterClass.BlockVerbosity value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; verbosity_ = value.getNumber(); onChanged(); return this; } /** *
       * The verbosity level for block information.
       * 
* * .pactus.BlockVerbosity verbosity = 2 [json_name = "verbosity"]; * @return This builder for chaining. */ public Builder clearVerbosity() { bitField0_ = (bitField0_ & ~0x00000002); verbosity_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockRequest) } // @@protoc_insertion_point(class_scope:pactus.GetBlockRequest) private static final pactus.BlockchainOuterClass.GetBlockRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockRequest(); } public static pactus.BlockchainOuterClass.GetBlockRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the block.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ int getHeight(); /** *
     * The hash of the block.
     * 
* * string hash = 2 [json_name = "hash"]; * @return The hash. */ java.lang.String getHash(); /** *
     * The hash of the block.
     * 
* * string hash = 2 [json_name = "hash"]; * @return The bytes for hash. */ com.google.protobuf.ByteString getHashBytes(); /** *
     * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
     * 
* * string data = 3 [json_name = "data"]; * @return The data. */ java.lang.String getData(); /** *
     * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
     * 
* * string data = 3 [json_name = "data"]; * @return The bytes for data. */ com.google.protobuf.ByteString getDataBytes(); /** *
     * The timestamp of the block.
     * 
* * uint32 block_time = 4 [json_name = "blockTime"]; * @return The blockTime. */ int getBlockTime(); /** *
     * Header information of the block.
     * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; * @return Whether the header field is set. */ boolean hasHeader(); /** *
     * Header information of the block.
     * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; * @return The header. */ pactus.BlockchainOuterClass.BlockHeaderInfo getHeader(); /** *
     * Header information of the block.
     * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder getHeaderOrBuilder(); /** *
     * Certificate information of the previous block.
     * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; * @return Whether the prevCert field is set. */ boolean hasPrevCert(); /** *
     * Certificate information of the previous block.
     * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; * @return The prevCert. */ pactus.BlockchainOuterClass.CertificateInfo getPrevCert(); /** *
     * Certificate information of the previous block.
     * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ pactus.BlockchainOuterClass.CertificateInfoOrBuilder getPrevCertOrBuilder(); /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ java.util.List getTxsList(); /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ pactus.TransactionOuterClass.TransactionInfo getTxs(int index); /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ int getTxsCount(); /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ java.util.List getTxsOrBuilderList(); /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ pactus.TransactionOuterClass.TransactionInfoOrBuilder getTxsOrBuilder( int index); } /** *
   * Response message contains block information.
   * 
* * Protobuf type {@code pactus.GetBlockResponse} */ public static final class GetBlockResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockResponse) GetBlockResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockResponse"); } // Use GetBlockResponse.newBuilder() to construct. private GetBlockResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockResponse() { hash_ = ""; data_ = ""; txs_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockResponse.class, pactus.BlockchainOuterClass.GetBlockResponse.Builder.class); } private int bitField0_; public static final int HEIGHT_FIELD_NUMBER = 1; private int height_ = 0; /** *
     * The height of the block.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } public static final int HASH_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object hash_ = ""; /** *
     * The hash of the block.
     * 
* * string hash = 2 [json_name = "hash"]; * @return The hash. */ @java.lang.Override public java.lang.String getHash() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } } /** *
     * The hash of the block.
     * 
* * string hash = 2 [json_name = "hash"]; * @return The bytes for hash. */ @java.lang.Override public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object data_ = ""; /** *
     * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
     * 
* * string data = 3 [json_name = "data"]; * @return The data. */ @java.lang.Override public java.lang.String getData() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } } /** *
     * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
     * 
* * string data = 3 [json_name = "data"]; * @return The bytes for data. */ @java.lang.Override public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int BLOCK_TIME_FIELD_NUMBER = 4; private int blockTime_ = 0; /** *
     * The timestamp of the block.
     * 
* * uint32 block_time = 4 [json_name = "blockTime"]; * @return The blockTime. */ @java.lang.Override public int getBlockTime() { return blockTime_; } public static final int HEADER_FIELD_NUMBER = 5; private pactus.BlockchainOuterClass.BlockHeaderInfo header_; /** *
     * Header information of the block.
     * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; * @return Whether the header field is set. */ @java.lang.Override public boolean hasHeader() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Header information of the block.
     * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; * @return The header. */ @java.lang.Override public pactus.BlockchainOuterClass.BlockHeaderInfo getHeader() { return header_ == null ? pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance() : header_; } /** *
     * Header information of the block.
     * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ @java.lang.Override public pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder getHeaderOrBuilder() { return header_ == null ? pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance() : header_; } public static final int PREV_CERT_FIELD_NUMBER = 6; private pactus.BlockchainOuterClass.CertificateInfo prevCert_; /** *
     * Certificate information of the previous block.
     * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; * @return Whether the prevCert field is set. */ @java.lang.Override public boolean hasPrevCert() { return ((bitField0_ & 0x00000002) != 0); } /** *
     * Certificate information of the previous block.
     * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; * @return The prevCert. */ @java.lang.Override public pactus.BlockchainOuterClass.CertificateInfo getPrevCert() { return prevCert_ == null ? pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance() : prevCert_; } /** *
     * Certificate information of the previous block.
     * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ @java.lang.Override public pactus.BlockchainOuterClass.CertificateInfoOrBuilder getPrevCertOrBuilder() { return prevCert_ == null ? pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance() : prevCert_; } public static final int TXS_FIELD_NUMBER = 7; @SuppressWarnings("serial") private java.util.List txs_; /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ @java.lang.Override public java.util.List getTxsList() { return txs_; } /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ @java.lang.Override public java.util.List getTxsOrBuilderList() { return txs_; } /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ @java.lang.Override public int getTxsCount() { return txs_.size(); } /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo getTxs(int index) { return txs_.get(index); } /** *
     * List of transactions in the block, available when verbosity level is set to
     * BLOCK_VERBOSITY_TRANSACTIONS.
     * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTxsOrBuilder( int index) { return txs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (height_ != 0) { output.writeUInt32(1, height_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, hash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, data_); } if (blockTime_ != 0) { output.writeUInt32(4, blockTime_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(5, getHeader()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(6, getPrevCert()); } for (int i = 0; i < txs_.size(); i++) { output.writeMessage(7, txs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, height_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, hash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, data_); } if (blockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(4, blockTime_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, getHeader()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, getPrevCert()); } for (int i = 0; i < txs_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, txs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockResponse other = (pactus.BlockchainOuterClass.GetBlockResponse) obj; if (getHeight() != other.getHeight()) return false; if (!getHash() .equals(other.getHash())) return false; if (!getData() .equals(other.getData())) return false; if (getBlockTime() != other.getBlockTime()) return false; if (hasHeader() != other.hasHeader()) return false; if (hasHeader()) { if (!getHeader() .equals(other.getHeader())) return false; } if (hasPrevCert() != other.hasPrevCert()) return false; if (hasPrevCert()) { if (!getPrevCert() .equals(other.getPrevCert())) return false; } if (!getTxsList() .equals(other.getTxsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (37 * hash) + HASH_FIELD_NUMBER; hash = (53 * hash) + getHash().hashCode(); hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); hash = (37 * hash) + BLOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getBlockTime(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } if (hasPrevCert()) { hash = (37 * hash) + PREV_CERT_FIELD_NUMBER; hash = (53 * hash) + getPrevCert().hashCode(); } if (getTxsCount() > 0) { hash = (37 * hash) + TXS_FIELD_NUMBER; hash = (53 * hash) + getTxsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains block information.
     * 
* * Protobuf type {@code pactus.GetBlockResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockResponse) pactus.BlockchainOuterClass.GetBlockResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockResponse.class, pactus.BlockchainOuterClass.GetBlockResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetHeaderFieldBuilder(); internalGetPrevCertFieldBuilder(); internalGetTxsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; height_ = 0; hash_ = ""; data_ = ""; blockTime_ = 0; header_ = null; if (headerBuilder_ != null) { headerBuilder_.dispose(); headerBuilder_ = null; } prevCert_ = null; if (prevCertBuilder_ != null) { prevCertBuilder_.dispose(); prevCertBuilder_ = null; } if (txsBuilder_ == null) { txs_ = java.util.Collections.emptyList(); } else { txs_ = null; txsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000040); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockResponse build() { pactus.BlockchainOuterClass.GetBlockResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockResponse buildPartial() { pactus.BlockchainOuterClass.GetBlockResponse result = new pactus.BlockchainOuterClass.GetBlockResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.BlockchainOuterClass.GetBlockResponse result) { if (txsBuilder_ == null) { if (((bitField0_ & 0x00000040) != 0)) { txs_ = java.util.Collections.unmodifiableList(txs_); bitField0_ = (bitField0_ & ~0x00000040); } result.txs_ = txs_; } else { result.txs_ = txsBuilder_.build(); } } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.height_ = height_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.hash_ = hash_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.data_ = data_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.blockTime_ = blockTime_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000010) != 0)) { result.header_ = headerBuilder_ == null ? header_ : headerBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000020) != 0)) { result.prevCert_ = prevCertBuilder_ == null ? prevCert_ : prevCertBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockResponse other) { if (other == pactus.BlockchainOuterClass.GetBlockResponse.getDefaultInstance()) return this; if (other.getHeight() != 0) { setHeight(other.getHeight()); } if (!other.getHash().isEmpty()) { hash_ = other.hash_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getData().isEmpty()) { data_ = other.data_; bitField0_ |= 0x00000004; onChanged(); } if (other.getBlockTime() != 0) { setBlockTime(other.getBlockTime()); } if (other.hasHeader()) { mergeHeader(other.getHeader()); } if (other.hasPrevCert()) { mergePrevCert(other.getPrevCert()); } if (txsBuilder_ == null) { if (!other.txs_.isEmpty()) { if (txs_.isEmpty()) { txs_ = other.txs_; bitField0_ = (bitField0_ & ~0x00000040); } else { ensureTxsIsMutable(); txs_.addAll(other.txs_); } onChanged(); } } else { if (!other.txs_.isEmpty()) { if (txsBuilder_.isEmpty()) { txsBuilder_.dispose(); txsBuilder_ = null; txs_ = other.txs_; bitField0_ = (bitField0_ & ~0x00000040); txsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetTxsFieldBuilder() : null; } else { txsBuilder_.addAllMessages(other.txs_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { height_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { hash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { data_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { blockTime_ = input.readUInt32(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { input.readMessage( internalGetHeaderFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000010; break; } // case 42 case 50: { input.readMessage( internalGetPrevCertFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000020; break; } // case 50 case 58: { pactus.TransactionOuterClass.TransactionInfo m = input.readMessage( pactus.TransactionOuterClass.TransactionInfo.parser(), extensionRegistry); if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(m); } else { txsBuilder_.addMessage(m); } break; } // case 58 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int height_ ; /** *
       * The height of the block.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * The height of the block.
       * 
* * uint32 height = 1 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the block.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000001); height_ = 0; onChanged(); return this; } private java.lang.Object hash_ = ""; /** *
       * The hash of the block.
       * 
* * string hash = 2 [json_name = "hash"]; * @return The hash. */ public java.lang.String getHash() { java.lang.Object ref = hash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the block.
       * 
* * string hash = 2 [json_name = "hash"]; * @return The bytes for hash. */ public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the block.
       * 
* * string hash = 2 [json_name = "hash"]; * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } hash_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The hash of the block.
       * 
* * string hash = 2 [json_name = "hash"]; * @return This builder for chaining. */ public Builder clearHash() { hash_ = getDefaultInstance().getHash(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The hash of the block.
       * 
* * string hash = 2 [json_name = "hash"]; * @param value The bytes for hash to set. * @return This builder for chaining. */ public Builder setHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); hash_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object data_ = ""; /** *
       * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
       * 
* * string data = 3 [json_name = "data"]; * @return The data. */ public java.lang.String getData() { java.lang.Object ref = data_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
       * 
* * string data = 3 [json_name = "data"]; * @return The bytes for data. */ public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
       * 
* * string data = 3 [json_name = "data"]; * @param value The data to set. * @return This builder for chaining. */ public Builder setData( java.lang.String value) { if (value == null) { throw new NullPointerException(); } data_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
       * 
* * string data = 3 [json_name = "data"]; * @return This builder for chaining. */ public Builder clearData() { data_ = getDefaultInstance().getData(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA.
       * 
* * string data = 3 [json_name = "data"]; * @param value The bytes for data to set. * @return This builder for chaining. */ public Builder setDataBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); data_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int blockTime_ ; /** *
       * The timestamp of the block.
       * 
* * uint32 block_time = 4 [json_name = "blockTime"]; * @return The blockTime. */ @java.lang.Override public int getBlockTime() { return blockTime_; } /** *
       * The timestamp of the block.
       * 
* * uint32 block_time = 4 [json_name = "blockTime"]; * @param value The blockTime to set. * @return This builder for chaining. */ public Builder setBlockTime(int value) { blockTime_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The timestamp of the block.
       * 
* * uint32 block_time = 4 [json_name = "blockTime"]; * @return This builder for chaining. */ public Builder clearBlockTime() { bitField0_ = (bitField0_ & ~0x00000008); blockTime_ = 0; onChanged(); return this; } private pactus.BlockchainOuterClass.BlockHeaderInfo header_; private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.BlockHeaderInfo, pactus.BlockchainOuterClass.BlockHeaderInfo.Builder, pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder> headerBuilder_; /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; * @return Whether the header field is set. */ public boolean hasHeader() { return ((bitField0_ & 0x00000010) != 0); } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; * @return The header. */ public pactus.BlockchainOuterClass.BlockHeaderInfo getHeader() { if (headerBuilder_ == null) { return header_ == null ? pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance() : header_; } else { return headerBuilder_.getMessage(); } } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ public Builder setHeader(pactus.BlockchainOuterClass.BlockHeaderInfo value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ public Builder setHeader( pactus.BlockchainOuterClass.BlockHeaderInfo.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ public Builder mergeHeader(pactus.BlockchainOuterClass.BlockHeaderInfo value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000010) != 0) && header_ != null && header_ != pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance()) { getHeaderBuilder().mergeFrom(value); } else { header_ = value; } } else { headerBuilder_.mergeFrom(value); } if (header_ != null) { bitField0_ |= 0x00000010; onChanged(); } return this; } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ public Builder clearHeader() { bitField0_ = (bitField0_ & ~0x00000010); header_ = null; if (headerBuilder_ != null) { headerBuilder_.dispose(); headerBuilder_ = null; } onChanged(); return this; } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ public pactus.BlockchainOuterClass.BlockHeaderInfo.Builder getHeaderBuilder() { bitField0_ |= 0x00000010; onChanged(); return internalGetHeaderFieldBuilder().getBuilder(); } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ public pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_ == null ? pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance() : header_; } } /** *
       * Header information of the block.
       * 
* * .pactus.BlockHeaderInfo header = 5 [json_name = "header"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.BlockHeaderInfo, pactus.BlockchainOuterClass.BlockHeaderInfo.Builder, pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder> internalGetHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.BlockHeaderInfo, pactus.BlockchainOuterClass.BlockHeaderInfo.Builder, pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder>( getHeader(), getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } private pactus.BlockchainOuterClass.CertificateInfo prevCert_; private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.CertificateInfo, pactus.BlockchainOuterClass.CertificateInfo.Builder, pactus.BlockchainOuterClass.CertificateInfoOrBuilder> prevCertBuilder_; /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; * @return Whether the prevCert field is set. */ public boolean hasPrevCert() { return ((bitField0_ & 0x00000020) != 0); } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; * @return The prevCert. */ public pactus.BlockchainOuterClass.CertificateInfo getPrevCert() { if (prevCertBuilder_ == null) { return prevCert_ == null ? pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance() : prevCert_; } else { return prevCertBuilder_.getMessage(); } } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ public Builder setPrevCert(pactus.BlockchainOuterClass.CertificateInfo value) { if (prevCertBuilder_ == null) { if (value == null) { throw new NullPointerException(); } prevCert_ = value; } else { prevCertBuilder_.setMessage(value); } bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ public Builder setPrevCert( pactus.BlockchainOuterClass.CertificateInfo.Builder builderForValue) { if (prevCertBuilder_ == null) { prevCert_ = builderForValue.build(); } else { prevCertBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ public Builder mergePrevCert(pactus.BlockchainOuterClass.CertificateInfo value) { if (prevCertBuilder_ == null) { if (((bitField0_ & 0x00000020) != 0) && prevCert_ != null && prevCert_ != pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance()) { getPrevCertBuilder().mergeFrom(value); } else { prevCert_ = value; } } else { prevCertBuilder_.mergeFrom(value); } if (prevCert_ != null) { bitField0_ |= 0x00000020; onChanged(); } return this; } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ public Builder clearPrevCert() { bitField0_ = (bitField0_ & ~0x00000020); prevCert_ = null; if (prevCertBuilder_ != null) { prevCertBuilder_.dispose(); prevCertBuilder_ = null; } onChanged(); return this; } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ public pactus.BlockchainOuterClass.CertificateInfo.Builder getPrevCertBuilder() { bitField0_ |= 0x00000020; onChanged(); return internalGetPrevCertFieldBuilder().getBuilder(); } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ public pactus.BlockchainOuterClass.CertificateInfoOrBuilder getPrevCertOrBuilder() { if (prevCertBuilder_ != null) { return prevCertBuilder_.getMessageOrBuilder(); } else { return prevCert_ == null ? pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance() : prevCert_; } } /** *
       * Certificate information of the previous block.
       * 
* * .pactus.CertificateInfo prev_cert = 6 [json_name = "prevCert"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.CertificateInfo, pactus.BlockchainOuterClass.CertificateInfo.Builder, pactus.BlockchainOuterClass.CertificateInfoOrBuilder> internalGetPrevCertFieldBuilder() { if (prevCertBuilder_ == null) { prevCertBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.CertificateInfo, pactus.BlockchainOuterClass.CertificateInfo.Builder, pactus.BlockchainOuterClass.CertificateInfoOrBuilder>( getPrevCert(), getParentForChildren(), isClean()); prevCert_ = null; } return prevCertBuilder_; } private java.util.List txs_ = java.util.Collections.emptyList(); private void ensureTxsIsMutable() { if (!((bitField0_ & 0x00000040) != 0)) { txs_ = new java.util.ArrayList(txs_); bitField0_ |= 0x00000040; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> txsBuilder_; /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public java.util.List getTxsList() { if (txsBuilder_ == null) { return java.util.Collections.unmodifiableList(txs_); } else { return txsBuilder_.getMessageList(); } } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public int getTxsCount() { if (txsBuilder_ == null) { return txs_.size(); } else { return txsBuilder_.getCount(); } } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo getTxs(int index) { if (txsBuilder_ == null) { return txs_.get(index); } else { return txsBuilder_.getMessage(index); } } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder setTxs( int index, pactus.TransactionOuterClass.TransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.set(index, value); onChanged(); } else { txsBuilder_.setMessage(index, value); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder setTxs( int index, pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.set(index, builderForValue.build()); onChanged(); } else { txsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder addTxs(pactus.TransactionOuterClass.TransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.add(value); onChanged(); } else { txsBuilder_.addMessage(value); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder addTxs( int index, pactus.TransactionOuterClass.TransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.add(index, value); onChanged(); } else { txsBuilder_.addMessage(index, value); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder addTxs( pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(builderForValue.build()); onChanged(); } else { txsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder addTxs( int index, pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(index, builderForValue.build()); onChanged(); } else { txsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder addAllTxs( java.lang.Iterable values) { if (txsBuilder_ == null) { ensureTxsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, txs_); onChanged(); } else { txsBuilder_.addAllMessages(values); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder clearTxs() { if (txsBuilder_ == null) { txs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); onChanged(); } else { txsBuilder_.clear(); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public Builder removeTxs(int index) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.remove(index); onChanged(); } else { txsBuilder_.remove(index); } return this; } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder getTxsBuilder( int index) { return internalGetTxsFieldBuilder().getBuilder(index); } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTxsOrBuilder( int index) { if (txsBuilder_ == null) { return txs_.get(index); } else { return txsBuilder_.getMessageOrBuilder(index); } } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public java.util.List getTxsOrBuilderList() { if (txsBuilder_ != null) { return txsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(txs_); } } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder addTxsBuilder() { return internalGetTxsFieldBuilder().addBuilder( pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()); } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder addTxsBuilder( int index) { return internalGetTxsFieldBuilder().addBuilder( index, pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()); } /** *
       * List of transactions in the block, available when verbosity level is set to
       * BLOCK_VERBOSITY_TRANSACTIONS.
       * 
* * repeated .pactus.TransactionInfo txs = 7 [json_name = "txs"]; */ public java.util.List getTxsBuilderList() { return internalGetTxsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> internalGetTxsFieldBuilder() { if (txsBuilder_ == null) { txsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder>( txs_, ((bitField0_ & 0x00000040) != 0), getParentForChildren(), isClean()); txs_ = null; } return txsBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockResponse) } // @@protoc_insertion_point(class_scope:pactus.GetBlockResponse) private static final pactus.BlockchainOuterClass.GetBlockResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockResponse(); } public static pactus.BlockchainOuterClass.GetBlockResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockHashRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockHashRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the block to retrieve the hash for.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ int getHeight(); } /** *
   * Request message for retrieving block hash by height.
   * 
* * Protobuf type {@code pactus.GetBlockHashRequest} */ public static final class GetBlockHashRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockHashRequest) GetBlockHashRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockHashRequest"); } // Use GetBlockHashRequest.newBuilder() to construct. private GetBlockHashRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockHashRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHashRequest.class, pactus.BlockchainOuterClass.GetBlockHashRequest.Builder.class); } public static final int HEIGHT_FIELD_NUMBER = 1; private int height_ = 0; /** *
     * The height of the block to retrieve the hash for.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (height_ != 0) { output.writeUInt32(1, height_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, height_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockHashRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockHashRequest other = (pactus.BlockchainOuterClass.GetBlockHashRequest) obj; if (getHeight() != other.getHeight()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHashRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockHashRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving block hash by height.
     * 
* * Protobuf type {@code pactus.GetBlockHashRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockHashRequest) pactus.BlockchainOuterClass.GetBlockHashRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHashRequest.class, pactus.BlockchainOuterClass.GetBlockHashRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockHashRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; height_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockHashRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashRequest build() { pactus.BlockchainOuterClass.GetBlockHashRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashRequest buildPartial() { pactus.BlockchainOuterClass.GetBlockHashRequest result = new pactus.BlockchainOuterClass.GetBlockHashRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockHashRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.height_ = height_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockHashRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockHashRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockHashRequest other) { if (other == pactus.BlockchainOuterClass.GetBlockHashRequest.getDefaultInstance()) return this; if (other.getHeight() != 0) { setHeight(other.getHeight()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { height_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int height_ ; /** *
       * The height of the block to retrieve the hash for.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * The height of the block to retrieve the hash for.
       * 
* * uint32 height = 1 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the block to retrieve the hash for.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000001); height_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockHashRequest) } // @@protoc_insertion_point(class_scope:pactus.GetBlockHashRequest) private static final pactus.BlockchainOuterClass.GetBlockHashRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockHashRequest(); } public static pactus.BlockchainOuterClass.GetBlockHashRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockHashRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockHashResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockHashResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The hash of the block.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ java.lang.String getHash(); /** *
     * The hash of the block.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ com.google.protobuf.ByteString getHashBytes(); } /** *
   * Response message contains block hash.
   * 
* * Protobuf type {@code pactus.GetBlockHashResponse} */ public static final class GetBlockHashResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockHashResponse) GetBlockHashResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockHashResponse"); } // Use GetBlockHashResponse.newBuilder() to construct. private GetBlockHashResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockHashResponse() { hash_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHashResponse.class, pactus.BlockchainOuterClass.GetBlockHashResponse.Builder.class); } public static final int HASH_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object hash_ = ""; /** *
     * The hash of the block.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ @java.lang.Override public java.lang.String getHash() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } } /** *
     * The hash of the block.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ @java.lang.Override public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, hash_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, hash_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockHashResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockHashResponse other = (pactus.BlockchainOuterClass.GetBlockHashResponse) obj; if (!getHash() .equals(other.getHash())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HASH_FIELD_NUMBER; hash = (53 * hash) + getHash().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHashResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockHashResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains block hash.
     * 
* * Protobuf type {@code pactus.GetBlockHashResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockHashResponse) pactus.BlockchainOuterClass.GetBlockHashResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHashResponse.class, pactus.BlockchainOuterClass.GetBlockHashResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockHashResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; hash_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHashResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockHashResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashResponse build() { pactus.BlockchainOuterClass.GetBlockHashResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashResponse buildPartial() { pactus.BlockchainOuterClass.GetBlockHashResponse result = new pactus.BlockchainOuterClass.GetBlockHashResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockHashResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.hash_ = hash_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockHashResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockHashResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockHashResponse other) { if (other == pactus.BlockchainOuterClass.GetBlockHashResponse.getDefaultInstance()) return this; if (!other.getHash().isEmpty()) { hash_ = other.hash_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { hash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object hash_ = ""; /** *
       * The hash of the block.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ public java.lang.String getHash() { java.lang.Object ref = hash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the block.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the block.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The hash of the block.
       * 
* * string hash = 1 [json_name = "hash"]; * @return This builder for chaining. */ public Builder clearHash() { hash_ = getDefaultInstance().getHash(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The hash of the block.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The bytes for hash to set. * @return This builder for chaining. */ public Builder setHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockHashResponse) } // @@protoc_insertion_point(class_scope:pactus.GetBlockHashResponse) private static final pactus.BlockchainOuterClass.GetBlockHashResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockHashResponse(); } public static pactus.BlockchainOuterClass.GetBlockHashResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockHashResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHashResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockHeightRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockHeightRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The hash of the block to retrieve the height for.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ java.lang.String getHash(); /** *
     * The hash of the block to retrieve the height for.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ com.google.protobuf.ByteString getHashBytes(); } /** *
   * Request message for retrieving block height by hash.
   * 
* * Protobuf type {@code pactus.GetBlockHeightRequest} */ public static final class GetBlockHeightRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockHeightRequest) GetBlockHeightRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockHeightRequest"); } // Use GetBlockHeightRequest.newBuilder() to construct. private GetBlockHeightRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockHeightRequest() { hash_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHeightRequest.class, pactus.BlockchainOuterClass.GetBlockHeightRequest.Builder.class); } public static final int HASH_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object hash_ = ""; /** *
     * The hash of the block to retrieve the height for.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ @java.lang.Override public java.lang.String getHash() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } } /** *
     * The hash of the block to retrieve the height for.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ @java.lang.Override public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, hash_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, hash_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockHeightRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockHeightRequest other = (pactus.BlockchainOuterClass.GetBlockHeightRequest) obj; if (!getHash() .equals(other.getHash())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HASH_FIELD_NUMBER; hash = (53 * hash) + getHash().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockHeightRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving block height by hash.
     * 
* * Protobuf type {@code pactus.GetBlockHeightRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockHeightRequest) pactus.BlockchainOuterClass.GetBlockHeightRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHeightRequest.class, pactus.BlockchainOuterClass.GetBlockHeightRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockHeightRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; hash_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockHeightRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightRequest build() { pactus.BlockchainOuterClass.GetBlockHeightRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightRequest buildPartial() { pactus.BlockchainOuterClass.GetBlockHeightRequest result = new pactus.BlockchainOuterClass.GetBlockHeightRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockHeightRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.hash_ = hash_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockHeightRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockHeightRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockHeightRequest other) { if (other == pactus.BlockchainOuterClass.GetBlockHeightRequest.getDefaultInstance()) return this; if (!other.getHash().isEmpty()) { hash_ = other.hash_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { hash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object hash_ = ""; /** *
       * The hash of the block to retrieve the height for.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ public java.lang.String getHash() { java.lang.Object ref = hash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the block to retrieve the height for.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the block to retrieve the height for.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The hash of the block to retrieve the height for.
       * 
* * string hash = 1 [json_name = "hash"]; * @return This builder for chaining. */ public Builder clearHash() { hash_ = getDefaultInstance().getHash(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The hash of the block to retrieve the height for.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The bytes for hash to set. * @return This builder for chaining. */ public Builder setHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockHeightRequest) } // @@protoc_insertion_point(class_scope:pactus.GetBlockHeightRequest) private static final pactus.BlockchainOuterClass.GetBlockHeightRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockHeightRequest(); } public static pactus.BlockchainOuterClass.GetBlockHeightRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockHeightRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockHeightResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockHeightResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the block.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ int getHeight(); } /** *
   * Response message contains block height.
   * 
* * Protobuf type {@code pactus.GetBlockHeightResponse} */ public static final class GetBlockHeightResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockHeightResponse) GetBlockHeightResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockHeightResponse"); } // Use GetBlockHeightResponse.newBuilder() to construct. private GetBlockHeightResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockHeightResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHeightResponse.class, pactus.BlockchainOuterClass.GetBlockHeightResponse.Builder.class); } public static final int HEIGHT_FIELD_NUMBER = 1; private int height_ = 0; /** *
     * The height of the block.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (height_ != 0) { output.writeUInt32(1, height_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, height_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockHeightResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockHeightResponse other = (pactus.BlockchainOuterClass.GetBlockHeightResponse) obj; if (getHeight() != other.getHeight()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockHeightResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains block height.
     * 
* * Protobuf type {@code pactus.GetBlockHeightResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockHeightResponse) pactus.BlockchainOuterClass.GetBlockHeightResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockHeightResponse.class, pactus.BlockchainOuterClass.GetBlockHeightResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockHeightResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; height_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockHeightResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockHeightResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightResponse build() { pactus.BlockchainOuterClass.GetBlockHeightResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightResponse buildPartial() { pactus.BlockchainOuterClass.GetBlockHeightResponse result = new pactus.BlockchainOuterClass.GetBlockHeightResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockHeightResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.height_ = height_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockHeightResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockHeightResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockHeightResponse other) { if (other == pactus.BlockchainOuterClass.GetBlockHeightResponse.getDefaultInstance()) return this; if (other.getHeight() != 0) { setHeight(other.getHeight()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { height_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int height_ ; /** *
       * The height of the block.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * The height of the block.
       * 
* * uint32 height = 1 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the block.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000001); height_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockHeightResponse) } // @@protoc_insertion_point(class_scope:pactus.GetBlockHeightResponse) private static final pactus.BlockchainOuterClass.GetBlockHeightResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockHeightResponse(); } public static pactus.BlockchainOuterClass.GetBlockHeightResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockHeightResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockHeightResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockchainInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockchainInfoRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for retrieving blockchain information.
   * 
* * Protobuf type {@code pactus.GetBlockchainInfoRequest} */ public static final class GetBlockchainInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockchainInfoRequest) GetBlockchainInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockchainInfoRequest"); } // Use GetBlockchainInfoRequest.newBuilder() to construct. private GetBlockchainInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockchainInfoRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockchainInfoRequest.class, pactus.BlockchainOuterClass.GetBlockchainInfoRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockchainInfoRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockchainInfoRequest other = (pactus.BlockchainOuterClass.GetBlockchainInfoRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockchainInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving blockchain information.
     * 
* * Protobuf type {@code pactus.GetBlockchainInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockchainInfoRequest) pactus.BlockchainOuterClass.GetBlockchainInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockchainInfoRequest.class, pactus.BlockchainOuterClass.GetBlockchainInfoRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockchainInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockchainInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoRequest build() { pactus.BlockchainOuterClass.GetBlockchainInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoRequest buildPartial() { pactus.BlockchainOuterClass.GetBlockchainInfoRequest result = new pactus.BlockchainOuterClass.GetBlockchainInfoRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockchainInfoRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockchainInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockchainInfoRequest other) { if (other == pactus.BlockchainOuterClass.GetBlockchainInfoRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockchainInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetBlockchainInfoRequest) private static final pactus.BlockchainOuterClass.GetBlockchainInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockchainInfoRequest(); } public static pactus.BlockchainOuterClass.GetBlockchainInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockchainInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetBlockchainInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetBlockchainInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the last block in the blockchain.
     * 
* * uint32 last_block_height = 1 [json_name = "lastBlockHeight"]; * @return The lastBlockHeight. */ int getLastBlockHeight(); /** *
     * The hash of the last block in the blockchain.
     * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return The lastBlockHash. */ java.lang.String getLastBlockHash(); /** *
     * The hash of the last block in the blockchain.
     * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return The bytes for lastBlockHash. */ com.google.protobuf.ByteString getLastBlockHashBytes(); /** *
     * The timestamp of the last block in Unix format.
     * 
* * int64 last_block_time = 10 [json_name = "lastBlockTime"]; * @return The lastBlockTime. */ long getLastBlockTime(); /** *
     * The total number of accounts in the blockchain.
     * 
* * int32 total_accounts = 3 [json_name = "totalAccounts"]; * @return The totalAccounts. */ int getTotalAccounts(); /** *
     * The total number of validators in the blockchain.
     * 
* * int32 total_validators = 4 [json_name = "totalValidators"]; * @return The totalValidators. */ int getTotalValidators(); /** *
     * The number of active (not unbonded) validators in the blockchain.
     * 
* * int32 active_validators = 12 [json_name = "activeValidators"]; * @return The activeValidators. */ int getActiveValidators(); /** *
     * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
     * 
* * int64 total_power = 5 [json_name = "totalPower"]; * @return The totalPower. */ long getTotalPower(); /** *
     * The power of the committee.
     * 
* * int64 committee_power = 6 [json_name = "committeePower"]; * @return The committeePower. */ long getCommitteePower(); /** *
     * If the blocks are subject to pruning.
     * 
* * bool is_pruned = 8 [json_name = "isPruned"]; * @return The isPruned. */ boolean getIsPruned(); /** *
     * Lowest-height block stored (only present if pruning is enabled)
     * 
* * uint32 pruning_height = 9 [json_name = "pruningHeight"]; * @return The pruningHeight. */ int getPruningHeight(); /** *
     * Indicates whether this node participates in consensus: true if at least one
     * of its running validators is a member of the current committee.
     * 
* * bool in_committee = 13 [json_name = "inCommittee"]; * @return The inCommittee. */ boolean getInCommittee(); /** *
     * The number of validators in the current committee.
     * 
* * int32 committee_size = 14 [json_name = "committeeSize"]; * @return The committeeSize. */ int getCommitteeSize(); /** *
     * Average availability score of validators with stake, in percentage (0-100).
     * 
* * double average_score = 15 [json_name = "averageScore"]; * @return The averageScore. */ double getAverageScore(); } /** *
   * Response message contains general blockchain information.
   * 
* * Protobuf type {@code pactus.GetBlockchainInfoResponse} */ public static final class GetBlockchainInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetBlockchainInfoResponse) GetBlockchainInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetBlockchainInfoResponse"); } // Use GetBlockchainInfoResponse.newBuilder() to construct. private GetBlockchainInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetBlockchainInfoResponse() { lastBlockHash_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockchainInfoResponse.class, pactus.BlockchainOuterClass.GetBlockchainInfoResponse.Builder.class); } public static final int LAST_BLOCK_HEIGHT_FIELD_NUMBER = 1; private int lastBlockHeight_ = 0; /** *
     * The height of the last block in the blockchain.
     * 
* * uint32 last_block_height = 1 [json_name = "lastBlockHeight"]; * @return The lastBlockHeight. */ @java.lang.Override public int getLastBlockHeight() { return lastBlockHeight_; } public static final int LAST_BLOCK_HASH_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object lastBlockHash_ = ""; /** *
     * The hash of the last block in the blockchain.
     * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return The lastBlockHash. */ @java.lang.Override public java.lang.String getLastBlockHash() { java.lang.Object ref = lastBlockHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastBlockHash_ = s; return s; } } /** *
     * The hash of the last block in the blockchain.
     * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return The bytes for lastBlockHash. */ @java.lang.Override public com.google.protobuf.ByteString getLastBlockHashBytes() { java.lang.Object ref = lastBlockHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lastBlockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LAST_BLOCK_TIME_FIELD_NUMBER = 10; private long lastBlockTime_ = 0L; /** *
     * The timestamp of the last block in Unix format.
     * 
* * int64 last_block_time = 10 [json_name = "lastBlockTime"]; * @return The lastBlockTime. */ @java.lang.Override public long getLastBlockTime() { return lastBlockTime_; } public static final int TOTAL_ACCOUNTS_FIELD_NUMBER = 3; private int totalAccounts_ = 0; /** *
     * The total number of accounts in the blockchain.
     * 
* * int32 total_accounts = 3 [json_name = "totalAccounts"]; * @return The totalAccounts. */ @java.lang.Override public int getTotalAccounts() { return totalAccounts_; } public static final int TOTAL_VALIDATORS_FIELD_NUMBER = 4; private int totalValidators_ = 0; /** *
     * The total number of validators in the blockchain.
     * 
* * int32 total_validators = 4 [json_name = "totalValidators"]; * @return The totalValidators. */ @java.lang.Override public int getTotalValidators() { return totalValidators_; } public static final int ACTIVE_VALIDATORS_FIELD_NUMBER = 12; private int activeValidators_ = 0; /** *
     * The number of active (not unbonded) validators in the blockchain.
     * 
* * int32 active_validators = 12 [json_name = "activeValidators"]; * @return The activeValidators. */ @java.lang.Override public int getActiveValidators() { return activeValidators_; } public static final int TOTAL_POWER_FIELD_NUMBER = 5; private long totalPower_ = 0L; /** *
     * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
     * 
* * int64 total_power = 5 [json_name = "totalPower"]; * @return The totalPower. */ @java.lang.Override public long getTotalPower() { return totalPower_; } public static final int COMMITTEE_POWER_FIELD_NUMBER = 6; private long committeePower_ = 0L; /** *
     * The power of the committee.
     * 
* * int64 committee_power = 6 [json_name = "committeePower"]; * @return The committeePower. */ @java.lang.Override public long getCommitteePower() { return committeePower_; } public static final int IS_PRUNED_FIELD_NUMBER = 8; private boolean isPruned_ = false; /** *
     * If the blocks are subject to pruning.
     * 
* * bool is_pruned = 8 [json_name = "isPruned"]; * @return The isPruned. */ @java.lang.Override public boolean getIsPruned() { return isPruned_; } public static final int PRUNING_HEIGHT_FIELD_NUMBER = 9; private int pruningHeight_ = 0; /** *
     * Lowest-height block stored (only present if pruning is enabled)
     * 
* * uint32 pruning_height = 9 [json_name = "pruningHeight"]; * @return The pruningHeight. */ @java.lang.Override public int getPruningHeight() { return pruningHeight_; } public static final int IN_COMMITTEE_FIELD_NUMBER = 13; private boolean inCommittee_ = false; /** *
     * Indicates whether this node participates in consensus: true if at least one
     * of its running validators is a member of the current committee.
     * 
* * bool in_committee = 13 [json_name = "inCommittee"]; * @return The inCommittee. */ @java.lang.Override public boolean getInCommittee() { return inCommittee_; } public static final int COMMITTEE_SIZE_FIELD_NUMBER = 14; private int committeeSize_ = 0; /** *
     * The number of validators in the current committee.
     * 
* * int32 committee_size = 14 [json_name = "committeeSize"]; * @return The committeeSize. */ @java.lang.Override public int getCommitteeSize() { return committeeSize_; } public static final int AVERAGE_SCORE_FIELD_NUMBER = 15; private double averageScore_ = 0D; /** *
     * Average availability score of validators with stake, in percentage (0-100).
     * 
* * double average_score = 15 [json_name = "averageScore"]; * @return The averageScore. */ @java.lang.Override public double getAverageScore() { return averageScore_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (lastBlockHeight_ != 0) { output.writeUInt32(1, lastBlockHeight_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(lastBlockHash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, lastBlockHash_); } if (totalAccounts_ != 0) { output.writeInt32(3, totalAccounts_); } if (totalValidators_ != 0) { output.writeInt32(4, totalValidators_); } if (totalPower_ != 0L) { output.writeInt64(5, totalPower_); } if (committeePower_ != 0L) { output.writeInt64(6, committeePower_); } if (isPruned_ != false) { output.writeBool(8, isPruned_); } if (pruningHeight_ != 0) { output.writeUInt32(9, pruningHeight_); } if (lastBlockTime_ != 0L) { output.writeInt64(10, lastBlockTime_); } if (activeValidators_ != 0) { output.writeInt32(12, activeValidators_); } if (inCommittee_ != false) { output.writeBool(13, inCommittee_); } if (committeeSize_ != 0) { output.writeInt32(14, committeeSize_); } if (java.lang.Double.doubleToRawLongBits(averageScore_) != 0) { output.writeDouble(15, averageScore_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (lastBlockHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, lastBlockHeight_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(lastBlockHash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, lastBlockHash_); } if (totalAccounts_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, totalAccounts_); } if (totalValidators_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, totalValidators_); } if (totalPower_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, totalPower_); } if (committeePower_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, committeePower_); } if (isPruned_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(8, isPruned_); } if (pruningHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(9, pruningHeight_); } if (lastBlockTime_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(10, lastBlockTime_); } if (activeValidators_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(12, activeValidators_); } if (inCommittee_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(13, inCommittee_); } if (committeeSize_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(14, committeeSize_); } if (java.lang.Double.doubleToRawLongBits(averageScore_) != 0) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(15, averageScore_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetBlockchainInfoResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetBlockchainInfoResponse other = (pactus.BlockchainOuterClass.GetBlockchainInfoResponse) obj; if (getLastBlockHeight() != other.getLastBlockHeight()) return false; if (!getLastBlockHash() .equals(other.getLastBlockHash())) return false; if (getLastBlockTime() != other.getLastBlockTime()) return false; if (getTotalAccounts() != other.getTotalAccounts()) return false; if (getTotalValidators() != other.getTotalValidators()) return false; if (getActiveValidators() != other.getActiveValidators()) return false; if (getTotalPower() != other.getTotalPower()) return false; if (getCommitteePower() != other.getCommitteePower()) return false; if (getIsPruned() != other.getIsPruned()) return false; if (getPruningHeight() != other.getPruningHeight()) return false; if (getInCommittee() != other.getInCommittee()) return false; if (getCommitteeSize() != other.getCommitteeSize()) return false; if (java.lang.Double.doubleToLongBits(getAverageScore()) != java.lang.Double.doubleToLongBits( other.getAverageScore())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LAST_BLOCK_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getLastBlockHeight(); hash = (37 * hash) + LAST_BLOCK_HASH_FIELD_NUMBER; hash = (53 * hash) + getLastBlockHash().hashCode(); hash = (37 * hash) + LAST_BLOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastBlockTime()); hash = (37 * hash) + TOTAL_ACCOUNTS_FIELD_NUMBER; hash = (53 * hash) + getTotalAccounts(); hash = (37 * hash) + TOTAL_VALIDATORS_FIELD_NUMBER; hash = (53 * hash) + getTotalValidators(); hash = (37 * hash) + ACTIVE_VALIDATORS_FIELD_NUMBER; hash = (53 * hash) + getActiveValidators(); hash = (37 * hash) + TOTAL_POWER_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTotalPower()); hash = (37 * hash) + COMMITTEE_POWER_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCommitteePower()); hash = (37 * hash) + IS_PRUNED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsPruned()); hash = (37 * hash) + PRUNING_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getPruningHeight(); hash = (37 * hash) + IN_COMMITTEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getInCommittee()); hash = (37 * hash) + COMMITTEE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getCommitteeSize(); hash = (37 * hash) + AVERAGE_SCORE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getAverageScore())); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetBlockchainInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains general blockchain information.
     * 
* * Protobuf type {@code pactus.GetBlockchainInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetBlockchainInfoResponse) pactus.BlockchainOuterClass.GetBlockchainInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetBlockchainInfoResponse.class, pactus.BlockchainOuterClass.GetBlockchainInfoResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetBlockchainInfoResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; lastBlockHeight_ = 0; lastBlockHash_ = ""; lastBlockTime_ = 0L; totalAccounts_ = 0; totalValidators_ = 0; activeValidators_ = 0; totalPower_ = 0L; committeePower_ = 0L; isPruned_ = false; pruningHeight_ = 0; inCommittee_ = false; committeeSize_ = 0; averageScore_ = 0D; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetBlockchainInfoResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetBlockchainInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoResponse build() { pactus.BlockchainOuterClass.GetBlockchainInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoResponse buildPartial() { pactus.BlockchainOuterClass.GetBlockchainInfoResponse result = new pactus.BlockchainOuterClass.GetBlockchainInfoResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetBlockchainInfoResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.lastBlockHeight_ = lastBlockHeight_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.lastBlockHash_ = lastBlockHash_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.lastBlockTime_ = lastBlockTime_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.totalAccounts_ = totalAccounts_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.totalValidators_ = totalValidators_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.activeValidators_ = activeValidators_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.totalPower_ = totalPower_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.committeePower_ = committeePower_; } if (((from_bitField0_ & 0x00000100) != 0)) { result.isPruned_ = isPruned_; } if (((from_bitField0_ & 0x00000200) != 0)) { result.pruningHeight_ = pruningHeight_; } if (((from_bitField0_ & 0x00000400) != 0)) { result.inCommittee_ = inCommittee_; } if (((from_bitField0_ & 0x00000800) != 0)) { result.committeeSize_ = committeeSize_; } if (((from_bitField0_ & 0x00001000) != 0)) { result.averageScore_ = averageScore_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetBlockchainInfoResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetBlockchainInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetBlockchainInfoResponse other) { if (other == pactus.BlockchainOuterClass.GetBlockchainInfoResponse.getDefaultInstance()) return this; if (other.getLastBlockHeight() != 0) { setLastBlockHeight(other.getLastBlockHeight()); } if (!other.getLastBlockHash().isEmpty()) { lastBlockHash_ = other.lastBlockHash_; bitField0_ |= 0x00000002; onChanged(); } if (other.getLastBlockTime() != 0L) { setLastBlockTime(other.getLastBlockTime()); } if (other.getTotalAccounts() != 0) { setTotalAccounts(other.getTotalAccounts()); } if (other.getTotalValidators() != 0) { setTotalValidators(other.getTotalValidators()); } if (other.getActiveValidators() != 0) { setActiveValidators(other.getActiveValidators()); } if (other.getTotalPower() != 0L) { setTotalPower(other.getTotalPower()); } if (other.getCommitteePower() != 0L) { setCommitteePower(other.getCommitteePower()); } if (other.getIsPruned() != false) { setIsPruned(other.getIsPruned()); } if (other.getPruningHeight() != 0) { setPruningHeight(other.getPruningHeight()); } if (other.getInCommittee() != false) { setInCommittee(other.getInCommittee()); } if (other.getCommitteeSize() != 0) { setCommitteeSize(other.getCommitteeSize()); } if (java.lang.Double.doubleToRawLongBits(other.getAverageScore()) != 0) { setAverageScore(other.getAverageScore()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { lastBlockHeight_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { lastBlockHash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { totalAccounts_ = input.readInt32(); bitField0_ |= 0x00000008; break; } // case 24 case 32: { totalValidators_ = input.readInt32(); bitField0_ |= 0x00000010; break; } // case 32 case 40: { totalPower_ = input.readInt64(); bitField0_ |= 0x00000040; break; } // case 40 case 48: { committeePower_ = input.readInt64(); bitField0_ |= 0x00000080; break; } // case 48 case 64: { isPruned_ = input.readBool(); bitField0_ |= 0x00000100; break; } // case 64 case 72: { pruningHeight_ = input.readUInt32(); bitField0_ |= 0x00000200; break; } // case 72 case 80: { lastBlockTime_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 80 case 96: { activeValidators_ = input.readInt32(); bitField0_ |= 0x00000020; break; } // case 96 case 104: { inCommittee_ = input.readBool(); bitField0_ |= 0x00000400; break; } // case 104 case 112: { committeeSize_ = input.readInt32(); bitField0_ |= 0x00000800; break; } // case 112 case 121: { averageScore_ = input.readDouble(); bitField0_ |= 0x00001000; break; } // case 121 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int lastBlockHeight_ ; /** *
       * The height of the last block in the blockchain.
       * 
* * uint32 last_block_height = 1 [json_name = "lastBlockHeight"]; * @return The lastBlockHeight. */ @java.lang.Override public int getLastBlockHeight() { return lastBlockHeight_; } /** *
       * The height of the last block in the blockchain.
       * 
* * uint32 last_block_height = 1 [json_name = "lastBlockHeight"]; * @param value The lastBlockHeight to set. * @return This builder for chaining. */ public Builder setLastBlockHeight(int value) { lastBlockHeight_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the last block in the blockchain.
       * 
* * uint32 last_block_height = 1 [json_name = "lastBlockHeight"]; * @return This builder for chaining. */ public Builder clearLastBlockHeight() { bitField0_ = (bitField0_ & ~0x00000001); lastBlockHeight_ = 0; onChanged(); return this; } private java.lang.Object lastBlockHash_ = ""; /** *
       * The hash of the last block in the blockchain.
       * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return The lastBlockHash. */ public java.lang.String getLastBlockHash() { java.lang.Object ref = lastBlockHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastBlockHash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the last block in the blockchain.
       * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return The bytes for lastBlockHash. */ public com.google.protobuf.ByteString getLastBlockHashBytes() { java.lang.Object ref = lastBlockHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lastBlockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the last block in the blockchain.
       * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @param value The lastBlockHash to set. * @return This builder for chaining. */ public Builder setLastBlockHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } lastBlockHash_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The hash of the last block in the blockchain.
       * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @return This builder for chaining. */ public Builder clearLastBlockHash() { lastBlockHash_ = getDefaultInstance().getLastBlockHash(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The hash of the last block in the blockchain.
       * 
* * string last_block_hash = 2 [json_name = "lastBlockHash"]; * @param value The bytes for lastBlockHash to set. * @return This builder for chaining. */ public Builder setLastBlockHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); lastBlockHash_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long lastBlockTime_ ; /** *
       * The timestamp of the last block in Unix format.
       * 
* * int64 last_block_time = 10 [json_name = "lastBlockTime"]; * @return The lastBlockTime. */ @java.lang.Override public long getLastBlockTime() { return lastBlockTime_; } /** *
       * The timestamp of the last block in Unix format.
       * 
* * int64 last_block_time = 10 [json_name = "lastBlockTime"]; * @param value The lastBlockTime to set. * @return This builder for chaining. */ public Builder setLastBlockTime(long value) { lastBlockTime_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The timestamp of the last block in Unix format.
       * 
* * int64 last_block_time = 10 [json_name = "lastBlockTime"]; * @return This builder for chaining. */ public Builder clearLastBlockTime() { bitField0_ = (bitField0_ & ~0x00000004); lastBlockTime_ = 0L; onChanged(); return this; } private int totalAccounts_ ; /** *
       * The total number of accounts in the blockchain.
       * 
* * int32 total_accounts = 3 [json_name = "totalAccounts"]; * @return The totalAccounts. */ @java.lang.Override public int getTotalAccounts() { return totalAccounts_; } /** *
       * The total number of accounts in the blockchain.
       * 
* * int32 total_accounts = 3 [json_name = "totalAccounts"]; * @param value The totalAccounts to set. * @return This builder for chaining. */ public Builder setTotalAccounts(int value) { totalAccounts_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The total number of accounts in the blockchain.
       * 
* * int32 total_accounts = 3 [json_name = "totalAccounts"]; * @return This builder for chaining. */ public Builder clearTotalAccounts() { bitField0_ = (bitField0_ & ~0x00000008); totalAccounts_ = 0; onChanged(); return this; } private int totalValidators_ ; /** *
       * The total number of validators in the blockchain.
       * 
* * int32 total_validators = 4 [json_name = "totalValidators"]; * @return The totalValidators. */ @java.lang.Override public int getTotalValidators() { return totalValidators_; } /** *
       * The total number of validators in the blockchain.
       * 
* * int32 total_validators = 4 [json_name = "totalValidators"]; * @param value The totalValidators to set. * @return This builder for chaining. */ public Builder setTotalValidators(int value) { totalValidators_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The total number of validators in the blockchain.
       * 
* * int32 total_validators = 4 [json_name = "totalValidators"]; * @return This builder for chaining. */ public Builder clearTotalValidators() { bitField0_ = (bitField0_ & ~0x00000010); totalValidators_ = 0; onChanged(); return this; } private int activeValidators_ ; /** *
       * The number of active (not unbonded) validators in the blockchain.
       * 
* * int32 active_validators = 12 [json_name = "activeValidators"]; * @return The activeValidators. */ @java.lang.Override public int getActiveValidators() { return activeValidators_; } /** *
       * The number of active (not unbonded) validators in the blockchain.
       * 
* * int32 active_validators = 12 [json_name = "activeValidators"]; * @param value The activeValidators to set. * @return This builder for chaining. */ public Builder setActiveValidators(int value) { activeValidators_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The number of active (not unbonded) validators in the blockchain.
       * 
* * int32 active_validators = 12 [json_name = "activeValidators"]; * @return This builder for chaining. */ public Builder clearActiveValidators() { bitField0_ = (bitField0_ & ~0x00000020); activeValidators_ = 0; onChanged(); return this; } private long totalPower_ ; /** *
       * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
       * 
* * int64 total_power = 5 [json_name = "totalPower"]; * @return The totalPower. */ @java.lang.Override public long getTotalPower() { return totalPower_; } /** *
       * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
       * 
* * int64 total_power = 5 [json_name = "totalPower"]; * @param value The totalPower to set. * @return This builder for chaining. */ public Builder setTotalPower(long value) { totalPower_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
       * 
* * int64 total_power = 5 [json_name = "totalPower"]; * @return This builder for chaining. */ public Builder clearTotalPower() { bitField0_ = (bitField0_ & ~0x00000040); totalPower_ = 0L; onChanged(); return this; } private long committeePower_ ; /** *
       * The power of the committee.
       * 
* * int64 committee_power = 6 [json_name = "committeePower"]; * @return The committeePower. */ @java.lang.Override public long getCommitteePower() { return committeePower_; } /** *
       * The power of the committee.
       * 
* * int64 committee_power = 6 [json_name = "committeePower"]; * @param value The committeePower to set. * @return This builder for chaining. */ public Builder setCommitteePower(long value) { committeePower_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * The power of the committee.
       * 
* * int64 committee_power = 6 [json_name = "committeePower"]; * @return This builder for chaining. */ public Builder clearCommitteePower() { bitField0_ = (bitField0_ & ~0x00000080); committeePower_ = 0L; onChanged(); return this; } private boolean isPruned_ ; /** *
       * If the blocks are subject to pruning.
       * 
* * bool is_pruned = 8 [json_name = "isPruned"]; * @return The isPruned. */ @java.lang.Override public boolean getIsPruned() { return isPruned_; } /** *
       * If the blocks are subject to pruning.
       * 
* * bool is_pruned = 8 [json_name = "isPruned"]; * @param value The isPruned to set. * @return This builder for chaining. */ public Builder setIsPruned(boolean value) { isPruned_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * If the blocks are subject to pruning.
       * 
* * bool is_pruned = 8 [json_name = "isPruned"]; * @return This builder for chaining. */ public Builder clearIsPruned() { bitField0_ = (bitField0_ & ~0x00000100); isPruned_ = false; onChanged(); return this; } private int pruningHeight_ ; /** *
       * Lowest-height block stored (only present if pruning is enabled)
       * 
* * uint32 pruning_height = 9 [json_name = "pruningHeight"]; * @return The pruningHeight. */ @java.lang.Override public int getPruningHeight() { return pruningHeight_; } /** *
       * Lowest-height block stored (only present if pruning is enabled)
       * 
* * uint32 pruning_height = 9 [json_name = "pruningHeight"]; * @param value The pruningHeight to set. * @return This builder for chaining. */ public Builder setPruningHeight(int value) { pruningHeight_ = value; bitField0_ |= 0x00000200; onChanged(); return this; } /** *
       * Lowest-height block stored (only present if pruning is enabled)
       * 
* * uint32 pruning_height = 9 [json_name = "pruningHeight"]; * @return This builder for chaining. */ public Builder clearPruningHeight() { bitField0_ = (bitField0_ & ~0x00000200); pruningHeight_ = 0; onChanged(); return this; } private boolean inCommittee_ ; /** *
       * Indicates whether this node participates in consensus: true if at least one
       * of its running validators is a member of the current committee.
       * 
* * bool in_committee = 13 [json_name = "inCommittee"]; * @return The inCommittee. */ @java.lang.Override public boolean getInCommittee() { return inCommittee_; } /** *
       * Indicates whether this node participates in consensus: true if at least one
       * of its running validators is a member of the current committee.
       * 
* * bool in_committee = 13 [json_name = "inCommittee"]; * @param value The inCommittee to set. * @return This builder for chaining. */ public Builder setInCommittee(boolean value) { inCommittee_ = value; bitField0_ |= 0x00000400; onChanged(); return this; } /** *
       * Indicates whether this node participates in consensus: true if at least one
       * of its running validators is a member of the current committee.
       * 
* * bool in_committee = 13 [json_name = "inCommittee"]; * @return This builder for chaining. */ public Builder clearInCommittee() { bitField0_ = (bitField0_ & ~0x00000400); inCommittee_ = false; onChanged(); return this; } private int committeeSize_ ; /** *
       * The number of validators in the current committee.
       * 
* * int32 committee_size = 14 [json_name = "committeeSize"]; * @return The committeeSize. */ @java.lang.Override public int getCommitteeSize() { return committeeSize_; } /** *
       * The number of validators in the current committee.
       * 
* * int32 committee_size = 14 [json_name = "committeeSize"]; * @param value The committeeSize to set. * @return This builder for chaining. */ public Builder setCommitteeSize(int value) { committeeSize_ = value; bitField0_ |= 0x00000800; onChanged(); return this; } /** *
       * The number of validators in the current committee.
       * 
* * int32 committee_size = 14 [json_name = "committeeSize"]; * @return This builder for chaining. */ public Builder clearCommitteeSize() { bitField0_ = (bitField0_ & ~0x00000800); committeeSize_ = 0; onChanged(); return this; } private double averageScore_ ; /** *
       * Average availability score of validators with stake, in percentage (0-100).
       * 
* * double average_score = 15 [json_name = "averageScore"]; * @return The averageScore. */ @java.lang.Override public double getAverageScore() { return averageScore_; } /** *
       * Average availability score of validators with stake, in percentage (0-100).
       * 
* * double average_score = 15 [json_name = "averageScore"]; * @param value The averageScore to set. * @return This builder for chaining. */ public Builder setAverageScore(double value) { averageScore_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } /** *
       * Average availability score of validators with stake, in percentage (0-100).
       * 
* * double average_score = 15 [json_name = "averageScore"]; * @return This builder for chaining. */ public Builder clearAverageScore() { bitField0_ = (bitField0_ & ~0x00001000); averageScore_ = 0D; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetBlockchainInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetBlockchainInfoResponse) private static final pactus.BlockchainOuterClass.GetBlockchainInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetBlockchainInfoResponse(); } public static pactus.BlockchainOuterClass.GetBlockchainInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetBlockchainInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetBlockchainInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetCommitteeInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetCommitteeInfoRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for retrieving committee information.
   * 
* * Protobuf type {@code pactus.GetCommitteeInfoRequest} */ public static final class GetCommitteeInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetCommitteeInfoRequest) GetCommitteeInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetCommitteeInfoRequest"); } // Use GetCommitteeInfoRequest.newBuilder() to construct. private GetCommitteeInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetCommitteeInfoRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetCommitteeInfoRequest.class, pactus.BlockchainOuterClass.GetCommitteeInfoRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetCommitteeInfoRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetCommitteeInfoRequest other = (pactus.BlockchainOuterClass.GetCommitteeInfoRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetCommitteeInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving committee information.
     * 
* * Protobuf type {@code pactus.GetCommitteeInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetCommitteeInfoRequest) pactus.BlockchainOuterClass.GetCommitteeInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetCommitteeInfoRequest.class, pactus.BlockchainOuterClass.GetCommitteeInfoRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetCommitteeInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetCommitteeInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoRequest build() { pactus.BlockchainOuterClass.GetCommitteeInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoRequest buildPartial() { pactus.BlockchainOuterClass.GetCommitteeInfoRequest result = new pactus.BlockchainOuterClass.GetCommitteeInfoRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetCommitteeInfoRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetCommitteeInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetCommitteeInfoRequest other) { if (other == pactus.BlockchainOuterClass.GetCommitteeInfoRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.GetCommitteeInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetCommitteeInfoRequest) private static final pactus.BlockchainOuterClass.GetCommitteeInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetCommitteeInfoRequest(); } public static pactus.BlockchainOuterClass.GetCommitteeInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetCommitteeInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetCommitteeInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetCommitteeInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The number of validators in the committee.
     * 
* * int32 committee_size = 1 [json_name = "committeeSize"]; * @return The committeeSize. */ int getCommitteeSize(); /** *
     * The power of the committee.
     * 
* * int64 committee_power = 2 [json_name = "committeePower"]; * @return The committeePower. */ long getCommitteePower(); /** *
     * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
     * 
* * int64 total_power = 3 [json_name = "totalPower"]; * @return The totalPower. */ long getTotalPower(); /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ java.util.List getValidatorsList(); /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ pactus.BlockchainOuterClass.ValidatorInfo getValidators(int index); /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ int getValidatorsCount(); /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ java.util.List getValidatorsOrBuilderList(); /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ pactus.BlockchainOuterClass.ValidatorInfoOrBuilder getValidatorsOrBuilder( int index); /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ int getProtocolVersionsCount(); /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ boolean containsProtocolVersions( int key); /** * Use {@link #getProtocolVersionsMap()} instead. */ @java.lang.Deprecated java.util.Map getProtocolVersions(); /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ java.util.Map getProtocolVersionsMap(); /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ double getProtocolVersionsOrDefault( int key, double defaultValue); /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ double getProtocolVersionsOrThrow( int key); } /** *
   * Response message contains committee information.
   * 
* * Protobuf type {@code pactus.GetCommitteeInfoResponse} */ public static final class GetCommitteeInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetCommitteeInfoResponse) GetCommitteeInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetCommitteeInfoResponse"); } // Use GetCommitteeInfoResponse.newBuilder() to construct. private GetCommitteeInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetCommitteeInfoResponse() { validators_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoResponse_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 5: return internalGetProtocolVersions(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetCommitteeInfoResponse.class, pactus.BlockchainOuterClass.GetCommitteeInfoResponse.Builder.class); } public static final int COMMITTEE_SIZE_FIELD_NUMBER = 1; private int committeeSize_ = 0; /** *
     * The number of validators in the committee.
     * 
* * int32 committee_size = 1 [json_name = "committeeSize"]; * @return The committeeSize. */ @java.lang.Override public int getCommitteeSize() { return committeeSize_; } public static final int COMMITTEE_POWER_FIELD_NUMBER = 2; private long committeePower_ = 0L; /** *
     * The power of the committee.
     * 
* * int64 committee_power = 2 [json_name = "committeePower"]; * @return The committeePower. */ @java.lang.Override public long getCommitteePower() { return committeePower_; } public static final int TOTAL_POWER_FIELD_NUMBER = 3; private long totalPower_ = 0L; /** *
     * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
     * 
* * int64 total_power = 3 [json_name = "totalPower"]; * @return The totalPower. */ @java.lang.Override public long getTotalPower() { return totalPower_; } public static final int VALIDATORS_FIELD_NUMBER = 4; @SuppressWarnings("serial") private java.util.List validators_; /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ @java.lang.Override public java.util.List getValidatorsList() { return validators_; } /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ @java.lang.Override public java.util.List getValidatorsOrBuilderList() { return validators_; } /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ @java.lang.Override public int getValidatorsCount() { return validators_.size(); } /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfo getValidators(int index) { return validators_.get(index); } /** *
     * List of committee validators.
     * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfoOrBuilder getValidatorsOrBuilder( int index) { return validators_.get(index); } public static final int PROTOCOL_VERSIONS_FIELD_NUMBER = 5; private static final class ProtocolVersionsDefaultEntryHolder { static final com.google.protobuf.MapEntry< java.lang.Integer, java.lang.Double> defaultEntry = com.google.protobuf.MapEntry .newDefaultInstance( pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoResponse_ProtocolVersionsEntry_descriptor, com.google.protobuf.WireFormat.FieldType.INT32, 0, com.google.protobuf.WireFormat.FieldType.DOUBLE, 0D); } @SuppressWarnings("serial") private com.google.protobuf.MapField< java.lang.Integer, java.lang.Double> protocolVersions_; private com.google.protobuf.MapField internalGetProtocolVersions() { if (protocolVersions_ == null) { return com.google.protobuf.MapField.emptyMapField( ProtocolVersionsDefaultEntryHolder.defaultEntry); } return protocolVersions_; } public int getProtocolVersionsCount() { return internalGetProtocolVersions().getMap().size(); } /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public boolean containsProtocolVersions( int key) { return internalGetProtocolVersions().getMap().containsKey(key); } /** * Use {@link #getProtocolVersionsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map getProtocolVersions() { return getProtocolVersionsMap(); } /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public java.util.Map getProtocolVersionsMap() { return internalGetProtocolVersions().getMap(); } /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public double getProtocolVersionsOrDefault( int key, double defaultValue) { java.util.Map map = internalGetProtocolVersions().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** *
     * Map of protocol versions and their percentages in the committee.
     * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public double getProtocolVersionsOrThrow( int key) { java.util.Map map = internalGetProtocolVersions().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (committeeSize_ != 0) { output.writeInt32(1, committeeSize_); } if (committeePower_ != 0L) { output.writeInt64(2, committeePower_); } if (totalPower_ != 0L) { output.writeInt64(3, totalPower_); } for (int i = 0; i < validators_.size(); i++) { output.writeMessage(4, validators_.get(i)); } com.google.protobuf.GeneratedMessage .serializeIntegerMapTo( output, internalGetProtocolVersions(), ProtocolVersionsDefaultEntryHolder.defaultEntry, 5); getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (committeeSize_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, committeeSize_); } if (committeePower_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, committeePower_); } if (totalPower_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, totalPower_); } for (int i = 0; i < validators_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, validators_.get(i)); } for (java.util.Map.Entry entry : internalGetProtocolVersions().getMap().entrySet()) { com.google.protobuf.MapEntry protocolVersions__ = ProtocolVersionsDefaultEntryHolder.defaultEntry.newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, protocolVersions__); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetCommitteeInfoResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetCommitteeInfoResponse other = (pactus.BlockchainOuterClass.GetCommitteeInfoResponse) obj; if (getCommitteeSize() != other.getCommitteeSize()) return false; if (getCommitteePower() != other.getCommitteePower()) return false; if (getTotalPower() != other.getTotalPower()) return false; if (!getValidatorsList() .equals(other.getValidatorsList())) return false; if (!internalGetProtocolVersions().equals( other.internalGetProtocolVersions())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + COMMITTEE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getCommitteeSize(); hash = (37 * hash) + COMMITTEE_POWER_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCommitteePower()); hash = (37 * hash) + TOTAL_POWER_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTotalPower()); if (getValidatorsCount() > 0) { hash = (37 * hash) + VALIDATORS_FIELD_NUMBER; hash = (53 * hash) + getValidatorsList().hashCode(); } if (!internalGetProtocolVersions().getMap().isEmpty()) { hash = (37 * hash) + PROTOCOL_VERSIONS_FIELD_NUMBER; hash = (53 * hash) + internalGetProtocolVersions().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetCommitteeInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains committee information.
     * 
* * Protobuf type {@code pactus.GetCommitteeInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetCommitteeInfoResponse) pactus.BlockchainOuterClass.GetCommitteeInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoResponse_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 5: return internalGetProtocolVersions(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 5: return internalGetMutableProtocolVersions(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetCommitteeInfoResponse.class, pactus.BlockchainOuterClass.GetCommitteeInfoResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetCommitteeInfoResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; committeeSize_ = 0; committeePower_ = 0L; totalPower_ = 0L; if (validatorsBuilder_ == null) { validators_ = java.util.Collections.emptyList(); } else { validators_ = null; validatorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000008); internalGetMutableProtocolVersions().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetCommitteeInfoResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetCommitteeInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoResponse build() { pactus.BlockchainOuterClass.GetCommitteeInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoResponse buildPartial() { pactus.BlockchainOuterClass.GetCommitteeInfoResponse result = new pactus.BlockchainOuterClass.GetCommitteeInfoResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.BlockchainOuterClass.GetCommitteeInfoResponse result) { if (validatorsBuilder_ == null) { if (((bitField0_ & 0x00000008) != 0)) { validators_ = java.util.Collections.unmodifiableList(validators_); bitField0_ = (bitField0_ & ~0x00000008); } result.validators_ = validators_; } else { result.validators_ = validatorsBuilder_.build(); } } private void buildPartial0(pactus.BlockchainOuterClass.GetCommitteeInfoResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.committeeSize_ = committeeSize_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.committeePower_ = committeePower_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.totalPower_ = totalPower_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.protocolVersions_ = internalGetProtocolVersions(); result.protocolVersions_.makeImmutable(); } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetCommitteeInfoResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetCommitteeInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetCommitteeInfoResponse other) { if (other == pactus.BlockchainOuterClass.GetCommitteeInfoResponse.getDefaultInstance()) return this; if (other.getCommitteeSize() != 0) { setCommitteeSize(other.getCommitteeSize()); } if (other.getCommitteePower() != 0L) { setCommitteePower(other.getCommitteePower()); } if (other.getTotalPower() != 0L) { setTotalPower(other.getTotalPower()); } if (validatorsBuilder_ == null) { if (!other.validators_.isEmpty()) { if (validators_.isEmpty()) { validators_ = other.validators_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureValidatorsIsMutable(); validators_.addAll(other.validators_); } onChanged(); } } else { if (!other.validators_.isEmpty()) { if (validatorsBuilder_.isEmpty()) { validatorsBuilder_.dispose(); validatorsBuilder_ = null; validators_ = other.validators_; bitField0_ = (bitField0_ & ~0x00000008); validatorsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetValidatorsFieldBuilder() : null; } else { validatorsBuilder_.addAllMessages(other.validators_); } } } internalGetMutableProtocolVersions().mergeFrom( other.internalGetProtocolVersions()); bitField0_ |= 0x00000010; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { committeeSize_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { committeePower_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { totalPower_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { pactus.BlockchainOuterClass.ValidatorInfo m = input.readMessage( pactus.BlockchainOuterClass.ValidatorInfo.parser(), extensionRegistry); if (validatorsBuilder_ == null) { ensureValidatorsIsMutable(); validators_.add(m); } else { validatorsBuilder_.addMessage(m); } break; } // case 34 case 42: { com.google.protobuf.MapEntry protocolVersions__ = input.readMessage( ProtocolVersionsDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableProtocolVersions().getMutableMap().put( protocolVersions__.getKey(), protocolVersions__.getValue()); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int committeeSize_ ; /** *
       * The number of validators in the committee.
       * 
* * int32 committee_size = 1 [json_name = "committeeSize"]; * @return The committeeSize. */ @java.lang.Override public int getCommitteeSize() { return committeeSize_; } /** *
       * The number of validators in the committee.
       * 
* * int32 committee_size = 1 [json_name = "committeeSize"]; * @param value The committeeSize to set. * @return This builder for chaining. */ public Builder setCommitteeSize(int value) { committeeSize_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The number of validators in the committee.
       * 
* * int32 committee_size = 1 [json_name = "committeeSize"]; * @return This builder for chaining. */ public Builder clearCommitteeSize() { bitField0_ = (bitField0_ & ~0x00000001); committeeSize_ = 0; onChanged(); return this; } private long committeePower_ ; /** *
       * The power of the committee.
       * 
* * int64 committee_power = 2 [json_name = "committeePower"]; * @return The committeePower. */ @java.lang.Override public long getCommitteePower() { return committeePower_; } /** *
       * The power of the committee.
       * 
* * int64 committee_power = 2 [json_name = "committeePower"]; * @param value The committeePower to set. * @return This builder for chaining. */ public Builder setCommitteePower(long value) { committeePower_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The power of the committee.
       * 
* * int64 committee_power = 2 [json_name = "committeePower"]; * @return This builder for chaining. */ public Builder clearCommitteePower() { bitField0_ = (bitField0_ & ~0x00000002); committeePower_ = 0L; onChanged(); return this; } private long totalPower_ ; /** *
       * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
       * 
* * int64 total_power = 3 [json_name = "totalPower"]; * @return The totalPower. */ @java.lang.Override public long getTotalPower() { return totalPower_; } /** *
       * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
       * 
* * int64 total_power = 3 [json_name = "totalPower"]; * @param value The totalPower to set. * @return This builder for chaining. */ public Builder setTotalPower(long value) { totalPower_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC.
       * 
* * int64 total_power = 3 [json_name = "totalPower"]; * @return This builder for chaining. */ public Builder clearTotalPower() { bitField0_ = (bitField0_ & ~0x00000004); totalPower_ = 0L; onChanged(); return this; } private java.util.List validators_ = java.util.Collections.emptyList(); private void ensureValidatorsIsMutable() { if (!((bitField0_ & 0x00000008) != 0)) { validators_ = new java.util.ArrayList(validators_); bitField0_ |= 0x00000008; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.ValidatorInfo, pactus.BlockchainOuterClass.ValidatorInfo.Builder, pactus.BlockchainOuterClass.ValidatorInfoOrBuilder> validatorsBuilder_; /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public java.util.List getValidatorsList() { if (validatorsBuilder_ == null) { return java.util.Collections.unmodifiableList(validators_); } else { return validatorsBuilder_.getMessageList(); } } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public int getValidatorsCount() { if (validatorsBuilder_ == null) { return validators_.size(); } else { return validatorsBuilder_.getCount(); } } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public pactus.BlockchainOuterClass.ValidatorInfo getValidators(int index) { if (validatorsBuilder_ == null) { return validators_.get(index); } else { return validatorsBuilder_.getMessage(index); } } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder setValidators( int index, pactus.BlockchainOuterClass.ValidatorInfo value) { if (validatorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureValidatorsIsMutable(); validators_.set(index, value); onChanged(); } else { validatorsBuilder_.setMessage(index, value); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder setValidators( int index, pactus.BlockchainOuterClass.ValidatorInfo.Builder builderForValue) { if (validatorsBuilder_ == null) { ensureValidatorsIsMutable(); validators_.set(index, builderForValue.build()); onChanged(); } else { validatorsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder addValidators(pactus.BlockchainOuterClass.ValidatorInfo value) { if (validatorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureValidatorsIsMutable(); validators_.add(value); onChanged(); } else { validatorsBuilder_.addMessage(value); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder addValidators( int index, pactus.BlockchainOuterClass.ValidatorInfo value) { if (validatorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureValidatorsIsMutable(); validators_.add(index, value); onChanged(); } else { validatorsBuilder_.addMessage(index, value); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder addValidators( pactus.BlockchainOuterClass.ValidatorInfo.Builder builderForValue) { if (validatorsBuilder_ == null) { ensureValidatorsIsMutable(); validators_.add(builderForValue.build()); onChanged(); } else { validatorsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder addValidators( int index, pactus.BlockchainOuterClass.ValidatorInfo.Builder builderForValue) { if (validatorsBuilder_ == null) { ensureValidatorsIsMutable(); validators_.add(index, builderForValue.build()); onChanged(); } else { validatorsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder addAllValidators( java.lang.Iterable values) { if (validatorsBuilder_ == null) { ensureValidatorsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, validators_); onChanged(); } else { validatorsBuilder_.addAllMessages(values); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder clearValidators() { if (validatorsBuilder_ == null) { validators_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); } else { validatorsBuilder_.clear(); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public Builder removeValidators(int index) { if (validatorsBuilder_ == null) { ensureValidatorsIsMutable(); validators_.remove(index); onChanged(); } else { validatorsBuilder_.remove(index); } return this; } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public pactus.BlockchainOuterClass.ValidatorInfo.Builder getValidatorsBuilder( int index) { return internalGetValidatorsFieldBuilder().getBuilder(index); } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public pactus.BlockchainOuterClass.ValidatorInfoOrBuilder getValidatorsOrBuilder( int index) { if (validatorsBuilder_ == null) { return validators_.get(index); } else { return validatorsBuilder_.getMessageOrBuilder(index); } } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public java.util.List getValidatorsOrBuilderList() { if (validatorsBuilder_ != null) { return validatorsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(validators_); } } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public pactus.BlockchainOuterClass.ValidatorInfo.Builder addValidatorsBuilder() { return internalGetValidatorsFieldBuilder().addBuilder( pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance()); } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public pactus.BlockchainOuterClass.ValidatorInfo.Builder addValidatorsBuilder( int index) { return internalGetValidatorsFieldBuilder().addBuilder( index, pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance()); } /** *
       * List of committee validators.
       * 
* * repeated .pactus.ValidatorInfo validators = 4 [json_name = "validators"]; */ public java.util.List getValidatorsBuilderList() { return internalGetValidatorsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.ValidatorInfo, pactus.BlockchainOuterClass.ValidatorInfo.Builder, pactus.BlockchainOuterClass.ValidatorInfoOrBuilder> internalGetValidatorsFieldBuilder() { if (validatorsBuilder_ == null) { validatorsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.ValidatorInfo, pactus.BlockchainOuterClass.ValidatorInfo.Builder, pactus.BlockchainOuterClass.ValidatorInfoOrBuilder>( validators_, ((bitField0_ & 0x00000008) != 0), getParentForChildren(), isClean()); validators_ = null; } return validatorsBuilder_; } private com.google.protobuf.MapField< java.lang.Integer, java.lang.Double> protocolVersions_; private com.google.protobuf.MapField internalGetProtocolVersions() { if (protocolVersions_ == null) { return com.google.protobuf.MapField.emptyMapField( ProtocolVersionsDefaultEntryHolder.defaultEntry); } return protocolVersions_; } private com.google.protobuf.MapField internalGetMutableProtocolVersions() { if (protocolVersions_ == null) { protocolVersions_ = com.google.protobuf.MapField.newMapField( ProtocolVersionsDefaultEntryHolder.defaultEntry); } if (!protocolVersions_.isMutable()) { protocolVersions_ = protocolVersions_.copy(); } bitField0_ |= 0x00000010; onChanged(); return protocolVersions_; } public int getProtocolVersionsCount() { return internalGetProtocolVersions().getMap().size(); } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public boolean containsProtocolVersions( int key) { return internalGetProtocolVersions().getMap().containsKey(key); } /** * Use {@link #getProtocolVersionsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map getProtocolVersions() { return getProtocolVersionsMap(); } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public java.util.Map getProtocolVersionsMap() { return internalGetProtocolVersions().getMap(); } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public double getProtocolVersionsOrDefault( int key, double defaultValue) { java.util.Map map = internalGetProtocolVersions().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ @java.lang.Override public double getProtocolVersionsOrThrow( int key) { java.util.Map map = internalGetProtocolVersions().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearProtocolVersions() { bitField0_ = (bitField0_ & ~0x00000010); internalGetMutableProtocolVersions().getMutableMap() .clear(); return this; } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ public Builder removeProtocolVersions( int key) { internalGetMutableProtocolVersions().getMutableMap() .remove(key); return this; } /** * Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map getMutableProtocolVersions() { bitField0_ |= 0x00000010; return internalGetMutableProtocolVersions().getMutableMap(); } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ public Builder putProtocolVersions( int key, double value) { internalGetMutableProtocolVersions().getMutableMap() .put(key, value); bitField0_ |= 0x00000010; return this; } /** *
       * Map of protocol versions and their percentages in the committee.
       * 
* * map<int32, double> protocol_versions = 5 [json_name = "protocolVersions"]; */ public Builder putAllProtocolVersions( java.util.Map values) { internalGetMutableProtocolVersions().getMutableMap() .putAll(values); bitField0_ |= 0x00000010; return this; } // @@protoc_insertion_point(builder_scope:pactus.GetCommitteeInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetCommitteeInfoResponse) private static final pactus.BlockchainOuterClass.GetCommitteeInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetCommitteeInfoResponse(); } public static pactus.BlockchainOuterClass.GetCommitteeInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetCommitteeInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetCommitteeInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetConsensusInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetConsensusInfoRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for retrieving consensus information.
   * 
* * Protobuf type {@code pactus.GetConsensusInfoRequest} */ public static final class GetConsensusInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetConsensusInfoRequest) GetConsensusInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetConsensusInfoRequest"); } // Use GetConsensusInfoRequest.newBuilder() to construct. private GetConsensusInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetConsensusInfoRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetConsensusInfoRequest.class, pactus.BlockchainOuterClass.GetConsensusInfoRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetConsensusInfoRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetConsensusInfoRequest other = (pactus.BlockchainOuterClass.GetConsensusInfoRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetConsensusInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving consensus information.
     * 
* * Protobuf type {@code pactus.GetConsensusInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetConsensusInfoRequest) pactus.BlockchainOuterClass.GetConsensusInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetConsensusInfoRequest.class, pactus.BlockchainOuterClass.GetConsensusInfoRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetConsensusInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetConsensusInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoRequest build() { pactus.BlockchainOuterClass.GetConsensusInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoRequest buildPartial() { pactus.BlockchainOuterClass.GetConsensusInfoRequest result = new pactus.BlockchainOuterClass.GetConsensusInfoRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetConsensusInfoRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetConsensusInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetConsensusInfoRequest other) { if (other == pactus.BlockchainOuterClass.GetConsensusInfoRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.GetConsensusInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetConsensusInfoRequest) private static final pactus.BlockchainOuterClass.GetConsensusInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetConsensusInfoRequest(); } public static pactus.BlockchainOuterClass.GetConsensusInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetConsensusInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetConsensusInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetConsensusInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The proposal of the consensus info.
     * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; * @return Whether the proposal field is set. */ boolean hasProposal(); /** *
     * The proposal of the consensus info.
     * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; * @return The proposal. */ pactus.BlockchainOuterClass.ProposalInfo getProposal(); /** *
     * The proposal of the consensus info.
     * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ pactus.BlockchainOuterClass.ProposalInfoOrBuilder getProposalOrBuilder(); /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ java.util.List getInstancesList(); /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ pactus.BlockchainOuterClass.ConsensusInfo getInstances(int index); /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ int getInstancesCount(); /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ java.util.List getInstancesOrBuilderList(); /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ pactus.BlockchainOuterClass.ConsensusInfoOrBuilder getInstancesOrBuilder( int index); } /** *
   * Response message contains consensus information.
   * 
* * Protobuf type {@code pactus.GetConsensusInfoResponse} */ public static final class GetConsensusInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetConsensusInfoResponse) GetConsensusInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetConsensusInfoResponse"); } // Use GetConsensusInfoResponse.newBuilder() to construct. private GetConsensusInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetConsensusInfoResponse() { instances_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetConsensusInfoResponse.class, pactus.BlockchainOuterClass.GetConsensusInfoResponse.Builder.class); } private int bitField0_; public static final int PROPOSAL_FIELD_NUMBER = 1; private pactus.BlockchainOuterClass.ProposalInfo proposal_; /** *
     * The proposal of the consensus info.
     * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; * @return Whether the proposal field is set. */ @java.lang.Override public boolean hasProposal() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * The proposal of the consensus info.
     * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; * @return The proposal. */ @java.lang.Override public pactus.BlockchainOuterClass.ProposalInfo getProposal() { return proposal_ == null ? pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance() : proposal_; } /** *
     * The proposal of the consensus info.
     * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ @java.lang.Override public pactus.BlockchainOuterClass.ProposalInfoOrBuilder getProposalOrBuilder() { return proposal_ == null ? pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance() : proposal_; } public static final int INSTANCES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List instances_; /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ @java.lang.Override public java.util.List getInstancesList() { return instances_; } /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ @java.lang.Override public java.util.List getInstancesOrBuilderList() { return instances_; } /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ @java.lang.Override public int getInstancesCount() { return instances_.size(); } /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ @java.lang.Override public pactus.BlockchainOuterClass.ConsensusInfo getInstances(int index) { return instances_.get(index); } /** *
     * List of consensus instances.
     * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ @java.lang.Override public pactus.BlockchainOuterClass.ConsensusInfoOrBuilder getInstancesOrBuilder( int index) { return instances_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getProposal()); } for (int i = 0; i < instances_.size(); i++) { output.writeMessage(2, instances_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getProposal()); } for (int i = 0; i < instances_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, instances_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetConsensusInfoResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetConsensusInfoResponse other = (pactus.BlockchainOuterClass.GetConsensusInfoResponse) obj; if (hasProposal() != other.hasProposal()) return false; if (hasProposal()) { if (!getProposal() .equals(other.getProposal())) return false; } if (!getInstancesList() .equals(other.getInstancesList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasProposal()) { hash = (37 * hash) + PROPOSAL_FIELD_NUMBER; hash = (53 * hash) + getProposal().hashCode(); } if (getInstancesCount() > 0) { hash = (37 * hash) + INSTANCES_FIELD_NUMBER; hash = (53 * hash) + getInstancesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetConsensusInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains consensus information.
     * 
* * Protobuf type {@code pactus.GetConsensusInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetConsensusInfoResponse) pactus.BlockchainOuterClass.GetConsensusInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetConsensusInfoResponse.class, pactus.BlockchainOuterClass.GetConsensusInfoResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetConsensusInfoResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetProposalFieldBuilder(); internalGetInstancesFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; proposal_ = null; if (proposalBuilder_ != null) { proposalBuilder_.dispose(); proposalBuilder_ = null; } if (instancesBuilder_ == null) { instances_ = java.util.Collections.emptyList(); } else { instances_ = null; instancesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetConsensusInfoResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetConsensusInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoResponse build() { pactus.BlockchainOuterClass.GetConsensusInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoResponse buildPartial() { pactus.BlockchainOuterClass.GetConsensusInfoResponse result = new pactus.BlockchainOuterClass.GetConsensusInfoResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.BlockchainOuterClass.GetConsensusInfoResponse result) { if (instancesBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { instances_ = java.util.Collections.unmodifiableList(instances_); bitField0_ = (bitField0_ & ~0x00000002); } result.instances_ = instances_; } else { result.instances_ = instancesBuilder_.build(); } } private void buildPartial0(pactus.BlockchainOuterClass.GetConsensusInfoResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.proposal_ = proposalBuilder_ == null ? proposal_ : proposalBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetConsensusInfoResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetConsensusInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetConsensusInfoResponse other) { if (other == pactus.BlockchainOuterClass.GetConsensusInfoResponse.getDefaultInstance()) return this; if (other.hasProposal()) { mergeProposal(other.getProposal()); } if (instancesBuilder_ == null) { if (!other.instances_.isEmpty()) { if (instances_.isEmpty()) { instances_ = other.instances_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureInstancesIsMutable(); instances_.addAll(other.instances_); } onChanged(); } } else { if (!other.instances_.isEmpty()) { if (instancesBuilder_.isEmpty()) { instancesBuilder_.dispose(); instancesBuilder_ = null; instances_ = other.instances_; bitField0_ = (bitField0_ & ~0x00000002); instancesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetInstancesFieldBuilder() : null; } else { instancesBuilder_.addAllMessages(other.instances_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( internalGetProposalFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { pactus.BlockchainOuterClass.ConsensusInfo m = input.readMessage( pactus.BlockchainOuterClass.ConsensusInfo.parser(), extensionRegistry); if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.add(m); } else { instancesBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private pactus.BlockchainOuterClass.ProposalInfo proposal_; private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.ProposalInfo, pactus.BlockchainOuterClass.ProposalInfo.Builder, pactus.BlockchainOuterClass.ProposalInfoOrBuilder> proposalBuilder_; /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; * @return Whether the proposal field is set. */ public boolean hasProposal() { return ((bitField0_ & 0x00000001) != 0); } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; * @return The proposal. */ public pactus.BlockchainOuterClass.ProposalInfo getProposal() { if (proposalBuilder_ == null) { return proposal_ == null ? pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance() : proposal_; } else { return proposalBuilder_.getMessage(); } } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ public Builder setProposal(pactus.BlockchainOuterClass.ProposalInfo value) { if (proposalBuilder_ == null) { if (value == null) { throw new NullPointerException(); } proposal_ = value; } else { proposalBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ public Builder setProposal( pactus.BlockchainOuterClass.ProposalInfo.Builder builderForValue) { if (proposalBuilder_ == null) { proposal_ = builderForValue.build(); } else { proposalBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ public Builder mergeProposal(pactus.BlockchainOuterClass.ProposalInfo value) { if (proposalBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && proposal_ != null && proposal_ != pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance()) { getProposalBuilder().mergeFrom(value); } else { proposal_ = value; } } else { proposalBuilder_.mergeFrom(value); } if (proposal_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ public Builder clearProposal() { bitField0_ = (bitField0_ & ~0x00000001); proposal_ = null; if (proposalBuilder_ != null) { proposalBuilder_.dispose(); proposalBuilder_ = null; } onChanged(); return this; } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ public pactus.BlockchainOuterClass.ProposalInfo.Builder getProposalBuilder() { bitField0_ |= 0x00000001; onChanged(); return internalGetProposalFieldBuilder().getBuilder(); } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ public pactus.BlockchainOuterClass.ProposalInfoOrBuilder getProposalOrBuilder() { if (proposalBuilder_ != null) { return proposalBuilder_.getMessageOrBuilder(); } else { return proposal_ == null ? pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance() : proposal_; } } /** *
       * The proposal of the consensus info.
       * 
* * .pactus.ProposalInfo proposal = 1 [json_name = "proposal"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.ProposalInfo, pactus.BlockchainOuterClass.ProposalInfo.Builder, pactus.BlockchainOuterClass.ProposalInfoOrBuilder> internalGetProposalFieldBuilder() { if (proposalBuilder_ == null) { proposalBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.BlockchainOuterClass.ProposalInfo, pactus.BlockchainOuterClass.ProposalInfo.Builder, pactus.BlockchainOuterClass.ProposalInfoOrBuilder>( getProposal(), getParentForChildren(), isClean()); proposal_ = null; } return proposalBuilder_; } private java.util.List instances_ = java.util.Collections.emptyList(); private void ensureInstancesIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { instances_ = new java.util.ArrayList(instances_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.ConsensusInfo, pactus.BlockchainOuterClass.ConsensusInfo.Builder, pactus.BlockchainOuterClass.ConsensusInfoOrBuilder> instancesBuilder_; /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public java.util.List getInstancesList() { if (instancesBuilder_ == null) { return java.util.Collections.unmodifiableList(instances_); } else { return instancesBuilder_.getMessageList(); } } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public int getInstancesCount() { if (instancesBuilder_ == null) { return instances_.size(); } else { return instancesBuilder_.getCount(); } } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public pactus.BlockchainOuterClass.ConsensusInfo getInstances(int index) { if (instancesBuilder_ == null) { return instances_.get(index); } else { return instancesBuilder_.getMessage(index); } } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder setInstances( int index, pactus.BlockchainOuterClass.ConsensusInfo value) { if (instancesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstancesIsMutable(); instances_.set(index, value); onChanged(); } else { instancesBuilder_.setMessage(index, value); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder setInstances( int index, pactus.BlockchainOuterClass.ConsensusInfo.Builder builderForValue) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.set(index, builderForValue.build()); onChanged(); } else { instancesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder addInstances(pactus.BlockchainOuterClass.ConsensusInfo value) { if (instancesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstancesIsMutable(); instances_.add(value); onChanged(); } else { instancesBuilder_.addMessage(value); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder addInstances( int index, pactus.BlockchainOuterClass.ConsensusInfo value) { if (instancesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstancesIsMutable(); instances_.add(index, value); onChanged(); } else { instancesBuilder_.addMessage(index, value); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder addInstances( pactus.BlockchainOuterClass.ConsensusInfo.Builder builderForValue) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.add(builderForValue.build()); onChanged(); } else { instancesBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder addInstances( int index, pactus.BlockchainOuterClass.ConsensusInfo.Builder builderForValue) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.add(index, builderForValue.build()); onChanged(); } else { instancesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder addAllInstances( java.lang.Iterable values) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, instances_); onChanged(); } else { instancesBuilder_.addAllMessages(values); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder clearInstances() { if (instancesBuilder_ == null) { instances_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { instancesBuilder_.clear(); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public Builder removeInstances(int index) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.remove(index); onChanged(); } else { instancesBuilder_.remove(index); } return this; } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public pactus.BlockchainOuterClass.ConsensusInfo.Builder getInstancesBuilder( int index) { return internalGetInstancesFieldBuilder().getBuilder(index); } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public pactus.BlockchainOuterClass.ConsensusInfoOrBuilder getInstancesOrBuilder( int index) { if (instancesBuilder_ == null) { return instances_.get(index); } else { return instancesBuilder_.getMessageOrBuilder(index); } } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public java.util.List getInstancesOrBuilderList() { if (instancesBuilder_ != null) { return instancesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(instances_); } } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public pactus.BlockchainOuterClass.ConsensusInfo.Builder addInstancesBuilder() { return internalGetInstancesFieldBuilder().addBuilder( pactus.BlockchainOuterClass.ConsensusInfo.getDefaultInstance()); } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public pactus.BlockchainOuterClass.ConsensusInfo.Builder addInstancesBuilder( int index) { return internalGetInstancesFieldBuilder().addBuilder( index, pactus.BlockchainOuterClass.ConsensusInfo.getDefaultInstance()); } /** *
       * List of consensus instances.
       * 
* * repeated .pactus.ConsensusInfo instances = 2 [json_name = "instances"]; */ public java.util.List getInstancesBuilderList() { return internalGetInstancesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.ConsensusInfo, pactus.BlockchainOuterClass.ConsensusInfo.Builder, pactus.BlockchainOuterClass.ConsensusInfoOrBuilder> internalGetInstancesFieldBuilder() { if (instancesBuilder_ == null) { instancesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.ConsensusInfo, pactus.BlockchainOuterClass.ConsensusInfo.Builder, pactus.BlockchainOuterClass.ConsensusInfoOrBuilder>( instances_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); instances_ = null; } return instancesBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetConsensusInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetConsensusInfoResponse) private static final pactus.BlockchainOuterClass.GetConsensusInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetConsensusInfoResponse(); } public static pactus.BlockchainOuterClass.GetConsensusInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetConsensusInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetConsensusInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTxPoolContentRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTxPoolContentRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The type of transactions to retrieve from the transaction pool. 0 means all types.
     * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ int getPayloadTypeValue(); /** *
     * The type of transactions to retrieve from the transaction pool. 0 means all types.
     * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return The payloadType. */ pactus.TransactionOuterClass.PayloadType getPayloadType(); } /** *
   * Request message for retrieving transactions in the transaction pool.
   * 
* * Protobuf type {@code pactus.GetTxPoolContentRequest} */ public static final class GetTxPoolContentRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTxPoolContentRequest) GetTxPoolContentRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTxPoolContentRequest"); } // Use GetTxPoolContentRequest.newBuilder() to construct. private GetTxPoolContentRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTxPoolContentRequest() { payloadType_ = 0; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetTxPoolContentRequest.class, pactus.BlockchainOuterClass.GetTxPoolContentRequest.Builder.class); } public static final int PAYLOAD_TYPE_FIELD_NUMBER = 1; private int payloadType_ = 0; /** *
     * The type of transactions to retrieve from the transaction pool. 0 means all types.
     * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
     * The type of transactions to retrieve from the transaction pool. 0 means all types.
     * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(1, payloadType_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, payloadType_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetTxPoolContentRequest)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetTxPoolContentRequest other = (pactus.BlockchainOuterClass.GetTxPoolContentRequest) obj; if (payloadType_ != other.payloadType_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PAYLOAD_TYPE_FIELD_NUMBER; hash = (53 * hash) + payloadType_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetTxPoolContentRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving transactions in the transaction pool.
     * 
* * Protobuf type {@code pactus.GetTxPoolContentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTxPoolContentRequest) pactus.BlockchainOuterClass.GetTxPoolContentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetTxPoolContentRequest.class, pactus.BlockchainOuterClass.GetTxPoolContentRequest.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetTxPoolContentRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; payloadType_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentRequest_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentRequest getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetTxPoolContentRequest.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentRequest build() { pactus.BlockchainOuterClass.GetTxPoolContentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentRequest buildPartial() { pactus.BlockchainOuterClass.GetTxPoolContentRequest result = new pactus.BlockchainOuterClass.GetTxPoolContentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.GetTxPoolContentRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.payloadType_ = payloadType_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetTxPoolContentRequest) { return mergeFrom((pactus.BlockchainOuterClass.GetTxPoolContentRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetTxPoolContentRequest other) { if (other == pactus.BlockchainOuterClass.GetTxPoolContentRequest.getDefaultInstance()) return this; if (other.payloadType_ != 0) { setPayloadTypeValue(other.getPayloadTypeValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { payloadType_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int payloadType_ = 0; /** *
       * The type of transactions to retrieve from the transaction pool. 0 means all types.
       * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
       * The type of transactions to retrieve from the transaction pool. 0 means all types.
       * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @param value The enum numeric value on the wire for payloadType to set. * @return This builder for chaining. */ public Builder setPayloadTypeValue(int value) { payloadType_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The type of transactions to retrieve from the transaction pool. 0 means all types.
       * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } /** *
       * The type of transactions to retrieve from the transaction pool. 0 means all types.
       * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @param value The payloadType to set. * @return This builder for chaining. */ public Builder setPayloadType(pactus.TransactionOuterClass.PayloadType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; payloadType_ = value.getNumber(); onChanged(); return this; } /** *
       * The type of transactions to retrieve from the transaction pool. 0 means all types.
       * 
* * .pactus.PayloadType payload_type = 1 [json_name = "payloadType"]; * @return This builder for chaining. */ public Builder clearPayloadType() { bitField0_ = (bitField0_ & ~0x00000001); payloadType_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetTxPoolContentRequest) } // @@protoc_insertion_point(class_scope:pactus.GetTxPoolContentRequest) private static final pactus.BlockchainOuterClass.GetTxPoolContentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetTxPoolContentRequest(); } public static pactus.BlockchainOuterClass.GetTxPoolContentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTxPoolContentRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTxPoolContentResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTxPoolContentResponse) com.google.protobuf.MessageOrBuilder { /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ java.util.List getTxsList(); /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ pactus.TransactionOuterClass.TransactionInfo getTxs(int index); /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ int getTxsCount(); /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ java.util.List getTxsOrBuilderList(); /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ pactus.TransactionOuterClass.TransactionInfoOrBuilder getTxsOrBuilder( int index); } /** *
   * Response message contains transactions in the transaction pool.
   * 
* * Protobuf type {@code pactus.GetTxPoolContentResponse} */ public static final class GetTxPoolContentResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTxPoolContentResponse) GetTxPoolContentResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTxPoolContentResponse"); } // Use GetTxPoolContentResponse.newBuilder() to construct. private GetTxPoolContentResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTxPoolContentResponse() { txs_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetTxPoolContentResponse.class, pactus.BlockchainOuterClass.GetTxPoolContentResponse.Builder.class); } public static final int TXS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List txs_; /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ @java.lang.Override public java.util.List getTxsList() { return txs_; } /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ @java.lang.Override public java.util.List getTxsOrBuilderList() { return txs_; } /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ @java.lang.Override public int getTxsCount() { return txs_.size(); } /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo getTxs(int index) { return txs_.get(index); } /** *
     * List of transactions currently in the pool.
     * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTxsOrBuilder( int index) { return txs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < txs_.size(); i++) { output.writeMessage(1, txs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < txs_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, txs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.GetTxPoolContentResponse)) { return super.equals(obj); } pactus.BlockchainOuterClass.GetTxPoolContentResponse other = (pactus.BlockchainOuterClass.GetTxPoolContentResponse) obj; if (!getTxsList() .equals(other.getTxsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getTxsCount() > 0) { hash = (37 * hash) + TXS_FIELD_NUMBER; hash = (53 * hash) + getTxsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.GetTxPoolContentResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains transactions in the transaction pool.
     * 
* * Protobuf type {@code pactus.GetTxPoolContentResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTxPoolContentResponse) pactus.BlockchainOuterClass.GetTxPoolContentResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.GetTxPoolContentResponse.class, pactus.BlockchainOuterClass.GetTxPoolContentResponse.Builder.class); } // Construct using pactus.BlockchainOuterClass.GetTxPoolContentResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (txsBuilder_ == null) { txs_ = java.util.Collections.emptyList(); } else { txs_ = null; txsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_GetTxPoolContentResponse_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentResponse getDefaultInstanceForType() { return pactus.BlockchainOuterClass.GetTxPoolContentResponse.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentResponse build() { pactus.BlockchainOuterClass.GetTxPoolContentResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentResponse buildPartial() { pactus.BlockchainOuterClass.GetTxPoolContentResponse result = new pactus.BlockchainOuterClass.GetTxPoolContentResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.BlockchainOuterClass.GetTxPoolContentResponse result) { if (txsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { txs_ = java.util.Collections.unmodifiableList(txs_); bitField0_ = (bitField0_ & ~0x00000001); } result.txs_ = txs_; } else { result.txs_ = txsBuilder_.build(); } } private void buildPartial0(pactus.BlockchainOuterClass.GetTxPoolContentResponse result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.GetTxPoolContentResponse) { return mergeFrom((pactus.BlockchainOuterClass.GetTxPoolContentResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.GetTxPoolContentResponse other) { if (other == pactus.BlockchainOuterClass.GetTxPoolContentResponse.getDefaultInstance()) return this; if (txsBuilder_ == null) { if (!other.txs_.isEmpty()) { if (txs_.isEmpty()) { txs_ = other.txs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTxsIsMutable(); txs_.addAll(other.txs_); } onChanged(); } } else { if (!other.txs_.isEmpty()) { if (txsBuilder_.isEmpty()) { txsBuilder_.dispose(); txsBuilder_ = null; txs_ = other.txs_; bitField0_ = (bitField0_ & ~0x00000001); txsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetTxsFieldBuilder() : null; } else { txsBuilder_.addAllMessages(other.txs_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { pactus.TransactionOuterClass.TransactionInfo m = input.readMessage( pactus.TransactionOuterClass.TransactionInfo.parser(), extensionRegistry); if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(m); } else { txsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List txs_ = java.util.Collections.emptyList(); private void ensureTxsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { txs_ = new java.util.ArrayList(txs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> txsBuilder_; /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public java.util.List getTxsList() { if (txsBuilder_ == null) { return java.util.Collections.unmodifiableList(txs_); } else { return txsBuilder_.getMessageList(); } } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public int getTxsCount() { if (txsBuilder_ == null) { return txs_.size(); } else { return txsBuilder_.getCount(); } } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo getTxs(int index) { if (txsBuilder_ == null) { return txs_.get(index); } else { return txsBuilder_.getMessage(index); } } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder setTxs( int index, pactus.TransactionOuterClass.TransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.set(index, value); onChanged(); } else { txsBuilder_.setMessage(index, value); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder setTxs( int index, pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.set(index, builderForValue.build()); onChanged(); } else { txsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder addTxs(pactus.TransactionOuterClass.TransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.add(value); onChanged(); } else { txsBuilder_.addMessage(value); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder addTxs( int index, pactus.TransactionOuterClass.TransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.add(index, value); onChanged(); } else { txsBuilder_.addMessage(index, value); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder addTxs( pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(builderForValue.build()); onChanged(); } else { txsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder addTxs( int index, pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(index, builderForValue.build()); onChanged(); } else { txsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder addAllTxs( java.lang.Iterable values) { if (txsBuilder_ == null) { ensureTxsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, txs_); onChanged(); } else { txsBuilder_.addAllMessages(values); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder clearTxs() { if (txsBuilder_ == null) { txs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { txsBuilder_.clear(); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public Builder removeTxs(int index) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.remove(index); onChanged(); } else { txsBuilder_.remove(index); } return this; } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder getTxsBuilder( int index) { return internalGetTxsFieldBuilder().getBuilder(index); } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTxsOrBuilder( int index) { if (txsBuilder_ == null) { return txs_.get(index); } else { return txsBuilder_.getMessageOrBuilder(index); } } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public java.util.List getTxsOrBuilderList() { if (txsBuilder_ != null) { return txsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(txs_); } } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder addTxsBuilder() { return internalGetTxsFieldBuilder().addBuilder( pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()); } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder addTxsBuilder( int index) { return internalGetTxsFieldBuilder().addBuilder( index, pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()); } /** *
       * List of transactions currently in the pool.
       * 
* * repeated .pactus.TransactionInfo txs = 1 [json_name = "txs"]; */ public java.util.List getTxsBuilderList() { return internalGetTxsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> internalGetTxsFieldBuilder() { if (txsBuilder_ == null) { txsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder>( txs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); txs_ = null; } return txsBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetTxPoolContentResponse) } // @@protoc_insertion_point(class_scope:pactus.GetTxPoolContentResponse) private static final pactus.BlockchainOuterClass.GetTxPoolContentResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.GetTxPoolContentResponse(); } public static pactus.BlockchainOuterClass.GetTxPoolContentResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTxPoolContentResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.GetTxPoolContentResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ValidatorInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ValidatorInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The hash of the validator.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ java.lang.String getHash(); /** *
     * The hash of the validator.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ com.google.protobuf.ByteString getHashBytes(); /** *
     * The serialized data of the validator.
     * 
* * string data = 2 [json_name = "data"]; * @return The data. */ java.lang.String getData(); /** *
     * The serialized data of the validator.
     * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ com.google.protobuf.ByteString getDataBytes(); /** *
     * The public key of the validator.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key of the validator.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); /** *
     * The unique number assigned to the validator.
     * 
* * int32 number = 4 [json_name = "number"]; * @return The number. */ int getNumber(); /** *
     * The stake of the validator in NanoPAC.
     * 
* * int64 stake = 5 [json_name = "stake"]; * @return The stake. */ long getStake(); /** *
     * The height at which the validator last bonded.
     * 
* * uint32 last_bonding_height = 6 [json_name = "lastBondingHeight"]; * @return The lastBondingHeight. */ int getLastBondingHeight(); /** *
     * The height at which the validator last participated in sortition.
     * 
* * uint32 last_sortition_height = 7 [json_name = "lastSortitionHeight"]; * @return The lastSortitionHeight. */ int getLastSortitionHeight(); /** *
     * The height at which the validator will unbond.
     * 
* * uint32 unbonding_height = 8 [json_name = "unbondingHeight"]; * @return The unbondingHeight. */ int getUnbondingHeight(); /** *
     * The address of the validator.
     * 
* * string address = 9 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address of the validator.
     * 
* * string address = 9 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The availability score of the validator.
     * 
* * double availability_score = 10 [json_name = "availabilityScore"]; * @return The availabilityScore. */ double getAvailabilityScore(); /** *
     * The protocol version of the validator.
     * 
* * int32 protocol_version = 11 [json_name = "protocolVersion"]; * @return The protocolVersion. */ int getProtocolVersion(); /** *
     * Whether the validator is delegated.
     * 
* * bool is_delegated = 12 [json_name = "isDelegated"]; * @return The isDelegated. */ boolean getIsDelegated(); /** *
     * The address of the stake owner of the validator.
     * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return The delegateOwner. */ java.lang.String getDelegateOwner(); /** *
     * The address of the stake owner of the validator.
     * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ com.google.protobuf.ByteString getDelegateOwnerBytes(); /** *
     * The share of the stake owner of the validator.
     * 
* * int64 delegate_share = 14 [json_name = "delegateShare"]; * @return The delegateShare. */ long getDelegateShare(); /** *
     * The expiry of the stake owner of the validator.
     * 
* * uint32 delegate_expiry = 15 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ int getDelegateExpiry(); } /** *
   * Message contains information about a validator.
   * 
* * Protobuf type {@code pactus.ValidatorInfo} */ public static final class ValidatorInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ValidatorInfo) ValidatorInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ValidatorInfo"); } // Use ValidatorInfo.newBuilder() to construct. private ValidatorInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ValidatorInfo() { hash_ = ""; data_ = ""; publicKey_ = ""; address_ = ""; delegateOwner_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_ValidatorInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_ValidatorInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.ValidatorInfo.class, pactus.BlockchainOuterClass.ValidatorInfo.Builder.class); } public static final int HASH_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object hash_ = ""; /** *
     * The hash of the validator.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ @java.lang.Override public java.lang.String getHash() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } } /** *
     * The hash of the validator.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ @java.lang.Override public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object data_ = ""; /** *
     * The serialized data of the validator.
     * 
* * string data = 2 [json_name = "data"]; * @return The data. */ @java.lang.Override public java.lang.String getData() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } } /** *
     * The serialized data of the validator.
     * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ @java.lang.Override public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PUBLIC_KEY_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key of the validator.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key of the validator.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NUMBER_FIELD_NUMBER = 4; private int number_ = 0; /** *
     * The unique number assigned to the validator.
     * 
* * int32 number = 4 [json_name = "number"]; * @return The number. */ @java.lang.Override public int getNumber() { return number_; } public static final int STAKE_FIELD_NUMBER = 5; private long stake_ = 0L; /** *
     * The stake of the validator in NanoPAC.
     * 
* * int64 stake = 5 [json_name = "stake"]; * @return The stake. */ @java.lang.Override public long getStake() { return stake_; } public static final int LAST_BONDING_HEIGHT_FIELD_NUMBER = 6; private int lastBondingHeight_ = 0; /** *
     * The height at which the validator last bonded.
     * 
* * uint32 last_bonding_height = 6 [json_name = "lastBondingHeight"]; * @return The lastBondingHeight. */ @java.lang.Override public int getLastBondingHeight() { return lastBondingHeight_; } public static final int LAST_SORTITION_HEIGHT_FIELD_NUMBER = 7; private int lastSortitionHeight_ = 0; /** *
     * The height at which the validator last participated in sortition.
     * 
* * uint32 last_sortition_height = 7 [json_name = "lastSortitionHeight"]; * @return The lastSortitionHeight. */ @java.lang.Override public int getLastSortitionHeight() { return lastSortitionHeight_; } public static final int UNBONDING_HEIGHT_FIELD_NUMBER = 8; private int unbondingHeight_ = 0; /** *
     * The height at which the validator will unbond.
     * 
* * uint32 unbonding_height = 8 [json_name = "unbondingHeight"]; * @return The unbondingHeight. */ @java.lang.Override public int getUnbondingHeight() { return unbondingHeight_; } public static final int ADDRESS_FIELD_NUMBER = 9; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address of the validator.
     * 
* * string address = 9 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address of the validator.
     * 
* * string address = 9 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AVAILABILITY_SCORE_FIELD_NUMBER = 10; private double availabilityScore_ = 0D; /** *
     * The availability score of the validator.
     * 
* * double availability_score = 10 [json_name = "availabilityScore"]; * @return The availabilityScore. */ @java.lang.Override public double getAvailabilityScore() { return availabilityScore_; } public static final int PROTOCOL_VERSION_FIELD_NUMBER = 11; private int protocolVersion_ = 0; /** *
     * The protocol version of the validator.
     * 
* * int32 protocol_version = 11 [json_name = "protocolVersion"]; * @return The protocolVersion. */ @java.lang.Override public int getProtocolVersion() { return protocolVersion_; } public static final int IS_DELEGATED_FIELD_NUMBER = 12; private boolean isDelegated_ = false; /** *
     * Whether the validator is delegated.
     * 
* * bool is_delegated = 12 [json_name = "isDelegated"]; * @return The isDelegated. */ @java.lang.Override public boolean getIsDelegated() { return isDelegated_; } public static final int DELEGATE_OWNER_FIELD_NUMBER = 13; @SuppressWarnings("serial") private volatile java.lang.Object delegateOwner_ = ""; /** *
     * The address of the stake owner of the validator.
     * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return The delegateOwner. */ @java.lang.Override public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } } /** *
     * The address of the stake owner of the validator.
     * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ @java.lang.Override public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DELEGATE_SHARE_FIELD_NUMBER = 14; private long delegateShare_ = 0L; /** *
     * The share of the stake owner of the validator.
     * 
* * int64 delegate_share = 14 [json_name = "delegateShare"]; * @return The delegateShare. */ @java.lang.Override public long getDelegateShare() { return delegateShare_; } public static final int DELEGATE_EXPIRY_FIELD_NUMBER = 15; private int delegateExpiry_ = 0; /** *
     * The expiry of the stake owner of the validator.
     * 
* * uint32 delegate_expiry = 15 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ @java.lang.Override public int getDelegateExpiry() { return delegateExpiry_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, hash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, data_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, publicKey_); } if (number_ != 0) { output.writeInt32(4, number_); } if (stake_ != 0L) { output.writeInt64(5, stake_); } if (lastBondingHeight_ != 0) { output.writeUInt32(6, lastBondingHeight_); } if (lastSortitionHeight_ != 0) { output.writeUInt32(7, lastSortitionHeight_); } if (unbondingHeight_ != 0) { output.writeUInt32(8, unbondingHeight_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 9, address_); } if (java.lang.Double.doubleToRawLongBits(availabilityScore_) != 0) { output.writeDouble(10, availabilityScore_); } if (protocolVersion_ != 0) { output.writeInt32(11, protocolVersion_); } if (isDelegated_ != false) { output.writeBool(12, isDelegated_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { com.google.protobuf.GeneratedMessage.writeString(output, 13, delegateOwner_); } if (delegateShare_ != 0L) { output.writeInt64(14, delegateShare_); } if (delegateExpiry_ != 0) { output.writeUInt32(15, delegateExpiry_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, hash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, data_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, publicKey_); } if (number_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, number_); } if (stake_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, stake_); } if (lastBondingHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(6, lastBondingHeight_); } if (lastSortitionHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(7, lastSortitionHeight_); } if (unbondingHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(8, unbondingHeight_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(9, address_); } if (java.lang.Double.doubleToRawLongBits(availabilityScore_) != 0) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(10, availabilityScore_); } if (protocolVersion_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(11, protocolVersion_); } if (isDelegated_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(12, isDelegated_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(13, delegateOwner_); } if (delegateShare_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(14, delegateShare_); } if (delegateExpiry_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(15, delegateExpiry_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.ValidatorInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.ValidatorInfo other = (pactus.BlockchainOuterClass.ValidatorInfo) obj; if (!getHash() .equals(other.getHash())) return false; if (!getData() .equals(other.getData())) return false; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (getNumber() != other.getNumber()) return false; if (getStake() != other.getStake()) return false; if (getLastBondingHeight() != other.getLastBondingHeight()) return false; if (getLastSortitionHeight() != other.getLastSortitionHeight()) return false; if (getUnbondingHeight() != other.getUnbondingHeight()) return false; if (!getAddress() .equals(other.getAddress())) return false; if (java.lang.Double.doubleToLongBits(getAvailabilityScore()) != java.lang.Double.doubleToLongBits( other.getAvailabilityScore())) return false; if (getProtocolVersion() != other.getProtocolVersion()) return false; if (getIsDelegated() != other.getIsDelegated()) return false; if (!getDelegateOwner() .equals(other.getDelegateOwner())) return false; if (getDelegateShare() != other.getDelegateShare()) return false; if (getDelegateExpiry() != other.getDelegateExpiry()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HASH_FIELD_NUMBER; hash = (53 * hash) + getHash().hashCode(); hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (37 * hash) + NUMBER_FIELD_NUMBER; hash = (53 * hash) + getNumber(); hash = (37 * hash) + STAKE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getStake()); hash = (37 * hash) + LAST_BONDING_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getLastBondingHeight(); hash = (37 * hash) + LAST_SORTITION_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getLastSortitionHeight(); hash = (37 * hash) + UNBONDING_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getUnbondingHeight(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + AVAILABILITY_SCORE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getAvailabilityScore())); hash = (37 * hash) + PROTOCOL_VERSION_FIELD_NUMBER; hash = (53 * hash) + getProtocolVersion(); hash = (37 * hash) + IS_DELEGATED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsDelegated()); hash = (37 * hash) + DELEGATE_OWNER_FIELD_NUMBER; hash = (53 * hash) + getDelegateOwner().hashCode(); hash = (37 * hash) + DELEGATE_SHARE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getDelegateShare()); hash = (37 * hash) + DELEGATE_EXPIRY_FIELD_NUMBER; hash = (53 * hash) + getDelegateExpiry(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.ValidatorInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ValidatorInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ValidatorInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.ValidatorInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about a validator.
     * 
* * Protobuf type {@code pactus.ValidatorInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ValidatorInfo) pactus.BlockchainOuterClass.ValidatorInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_ValidatorInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_ValidatorInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.ValidatorInfo.class, pactus.BlockchainOuterClass.ValidatorInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.ValidatorInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; hash_ = ""; data_ = ""; publicKey_ = ""; number_ = 0; stake_ = 0L; lastBondingHeight_ = 0; lastSortitionHeight_ = 0; unbondingHeight_ = 0; address_ = ""; availabilityScore_ = 0D; protocolVersion_ = 0; isDelegated_ = false; delegateOwner_ = ""; delegateShare_ = 0L; delegateExpiry_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_ValidatorInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfo build() { pactus.BlockchainOuterClass.ValidatorInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfo buildPartial() { pactus.BlockchainOuterClass.ValidatorInfo result = new pactus.BlockchainOuterClass.ValidatorInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.ValidatorInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.hash_ = hash_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.data_ = data_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.publicKey_ = publicKey_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.number_ = number_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.stake_ = stake_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.lastBondingHeight_ = lastBondingHeight_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.lastSortitionHeight_ = lastSortitionHeight_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.unbondingHeight_ = unbondingHeight_; } if (((from_bitField0_ & 0x00000100) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000200) != 0)) { result.availabilityScore_ = availabilityScore_; } if (((from_bitField0_ & 0x00000400) != 0)) { result.protocolVersion_ = protocolVersion_; } if (((from_bitField0_ & 0x00000800) != 0)) { result.isDelegated_ = isDelegated_; } if (((from_bitField0_ & 0x00001000) != 0)) { result.delegateOwner_ = delegateOwner_; } if (((from_bitField0_ & 0x00002000) != 0)) { result.delegateShare_ = delegateShare_; } if (((from_bitField0_ & 0x00004000) != 0)) { result.delegateExpiry_ = delegateExpiry_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.ValidatorInfo) { return mergeFrom((pactus.BlockchainOuterClass.ValidatorInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.ValidatorInfo other) { if (other == pactus.BlockchainOuterClass.ValidatorInfo.getDefaultInstance()) return this; if (!other.getHash().isEmpty()) { hash_ = other.hash_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getData().isEmpty()) { data_ = other.data_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000004; onChanged(); } if (other.getNumber() != 0) { setNumber(other.getNumber()); } if (other.getStake() != 0L) { setStake(other.getStake()); } if (other.getLastBondingHeight() != 0) { setLastBondingHeight(other.getLastBondingHeight()); } if (other.getLastSortitionHeight() != 0) { setLastSortitionHeight(other.getLastSortitionHeight()); } if (other.getUnbondingHeight() != 0) { setUnbondingHeight(other.getUnbondingHeight()); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000100; onChanged(); } if (java.lang.Double.doubleToRawLongBits(other.getAvailabilityScore()) != 0) { setAvailabilityScore(other.getAvailabilityScore()); } if (other.getProtocolVersion() != 0) { setProtocolVersion(other.getProtocolVersion()); } if (other.getIsDelegated() != false) { setIsDelegated(other.getIsDelegated()); } if (!other.getDelegateOwner().isEmpty()) { delegateOwner_ = other.delegateOwner_; bitField0_ |= 0x00001000; onChanged(); } if (other.getDelegateShare() != 0L) { setDelegateShare(other.getDelegateShare()); } if (other.getDelegateExpiry() != 0) { setDelegateExpiry(other.getDelegateExpiry()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { hash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { data_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { number_ = input.readInt32(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { stake_ = input.readInt64(); bitField0_ |= 0x00000010; break; } // case 40 case 48: { lastBondingHeight_ = input.readUInt32(); bitField0_ |= 0x00000020; break; } // case 48 case 56: { lastSortitionHeight_ = input.readUInt32(); bitField0_ |= 0x00000040; break; } // case 56 case 64: { unbondingHeight_ = input.readUInt32(); bitField0_ |= 0x00000080; break; } // case 64 case 74: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000100; break; } // case 74 case 81: { availabilityScore_ = input.readDouble(); bitField0_ |= 0x00000200; break; } // case 81 case 88: { protocolVersion_ = input.readInt32(); bitField0_ |= 0x00000400; break; } // case 88 case 96: { isDelegated_ = input.readBool(); bitField0_ |= 0x00000800; break; } // case 96 case 106: { delegateOwner_ = input.readStringRequireUtf8(); bitField0_ |= 0x00001000; break; } // case 106 case 112: { delegateShare_ = input.readInt64(); bitField0_ |= 0x00002000; break; } // case 112 case 120: { delegateExpiry_ = input.readUInt32(); bitField0_ |= 0x00004000; break; } // case 120 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object hash_ = ""; /** *
       * The hash of the validator.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ public java.lang.String getHash() { java.lang.Object ref = hash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the validator.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the validator.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The hash of the validator.
       * 
* * string hash = 1 [json_name = "hash"]; * @return This builder for chaining. */ public Builder clearHash() { hash_ = getDefaultInstance().getHash(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The hash of the validator.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The bytes for hash to set. * @return This builder for chaining. */ public Builder setHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object data_ = ""; /** *
       * The serialized data of the validator.
       * 
* * string data = 2 [json_name = "data"]; * @return The data. */ public java.lang.String getData() { java.lang.Object ref = data_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The serialized data of the validator.
       * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The serialized data of the validator.
       * 
* * string data = 2 [json_name = "data"]; * @param value The data to set. * @return This builder for chaining. */ public Builder setData( java.lang.String value) { if (value == null) { throw new NullPointerException(); } data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The serialized data of the validator.
       * 
* * string data = 2 [json_name = "data"]; * @return This builder for chaining. */ public Builder clearData() { data_ = getDefaultInstance().getData(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The serialized data of the validator.
       * 
* * string data = 2 [json_name = "data"]; * @param value The bytes for data to set. * @return This builder for chaining. */ public Builder setDataBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object publicKey_ = ""; /** *
       * The public key of the validator.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key of the validator.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key of the validator.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The public key of the validator.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The public key of the validator.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int number_ ; /** *
       * The unique number assigned to the validator.
       * 
* * int32 number = 4 [json_name = "number"]; * @return The number. */ @java.lang.Override public int getNumber() { return number_; } /** *
       * The unique number assigned to the validator.
       * 
* * int32 number = 4 [json_name = "number"]; * @param value The number to set. * @return This builder for chaining. */ public Builder setNumber(int value) { number_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The unique number assigned to the validator.
       * 
* * int32 number = 4 [json_name = "number"]; * @return This builder for chaining. */ public Builder clearNumber() { bitField0_ = (bitField0_ & ~0x00000008); number_ = 0; onChanged(); return this; } private long stake_ ; /** *
       * The stake of the validator in NanoPAC.
       * 
* * int64 stake = 5 [json_name = "stake"]; * @return The stake. */ @java.lang.Override public long getStake() { return stake_; } /** *
       * The stake of the validator in NanoPAC.
       * 
* * int64 stake = 5 [json_name = "stake"]; * @param value The stake to set. * @return This builder for chaining. */ public Builder setStake(long value) { stake_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The stake of the validator in NanoPAC.
       * 
* * int64 stake = 5 [json_name = "stake"]; * @return This builder for chaining. */ public Builder clearStake() { bitField0_ = (bitField0_ & ~0x00000010); stake_ = 0L; onChanged(); return this; } private int lastBondingHeight_ ; /** *
       * The height at which the validator last bonded.
       * 
* * uint32 last_bonding_height = 6 [json_name = "lastBondingHeight"]; * @return The lastBondingHeight. */ @java.lang.Override public int getLastBondingHeight() { return lastBondingHeight_; } /** *
       * The height at which the validator last bonded.
       * 
* * uint32 last_bonding_height = 6 [json_name = "lastBondingHeight"]; * @param value The lastBondingHeight to set. * @return This builder for chaining. */ public Builder setLastBondingHeight(int value) { lastBondingHeight_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The height at which the validator last bonded.
       * 
* * uint32 last_bonding_height = 6 [json_name = "lastBondingHeight"]; * @return This builder for chaining. */ public Builder clearLastBondingHeight() { bitField0_ = (bitField0_ & ~0x00000020); lastBondingHeight_ = 0; onChanged(); return this; } private int lastSortitionHeight_ ; /** *
       * The height at which the validator last participated in sortition.
       * 
* * uint32 last_sortition_height = 7 [json_name = "lastSortitionHeight"]; * @return The lastSortitionHeight. */ @java.lang.Override public int getLastSortitionHeight() { return lastSortitionHeight_; } /** *
       * The height at which the validator last participated in sortition.
       * 
* * uint32 last_sortition_height = 7 [json_name = "lastSortitionHeight"]; * @param value The lastSortitionHeight to set. * @return This builder for chaining. */ public Builder setLastSortitionHeight(int value) { lastSortitionHeight_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * The height at which the validator last participated in sortition.
       * 
* * uint32 last_sortition_height = 7 [json_name = "lastSortitionHeight"]; * @return This builder for chaining. */ public Builder clearLastSortitionHeight() { bitField0_ = (bitField0_ & ~0x00000040); lastSortitionHeight_ = 0; onChanged(); return this; } private int unbondingHeight_ ; /** *
       * The height at which the validator will unbond.
       * 
* * uint32 unbonding_height = 8 [json_name = "unbondingHeight"]; * @return The unbondingHeight. */ @java.lang.Override public int getUnbondingHeight() { return unbondingHeight_; } /** *
       * The height at which the validator will unbond.
       * 
* * uint32 unbonding_height = 8 [json_name = "unbondingHeight"]; * @param value The unbondingHeight to set. * @return This builder for chaining. */ public Builder setUnbondingHeight(int value) { unbondingHeight_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * The height at which the validator will unbond.
       * 
* * uint32 unbonding_height = 8 [json_name = "unbondingHeight"]; * @return This builder for chaining. */ public Builder clearUnbondingHeight() { bitField0_ = (bitField0_ & ~0x00000080); unbondingHeight_ = 0; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address of the validator.
       * 
* * string address = 9 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the validator.
       * 
* * string address = 9 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the validator.
       * 
* * string address = 9 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * The address of the validator.
       * 
* * string address = 9 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000100); onChanged(); return this; } /** *
       * The address of the validator.
       * 
* * string address = 9 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } private double availabilityScore_ ; /** *
       * The availability score of the validator.
       * 
* * double availability_score = 10 [json_name = "availabilityScore"]; * @return The availabilityScore. */ @java.lang.Override public double getAvailabilityScore() { return availabilityScore_; } /** *
       * The availability score of the validator.
       * 
* * double availability_score = 10 [json_name = "availabilityScore"]; * @param value The availabilityScore to set. * @return This builder for chaining. */ public Builder setAvailabilityScore(double value) { availabilityScore_ = value; bitField0_ |= 0x00000200; onChanged(); return this; } /** *
       * The availability score of the validator.
       * 
* * double availability_score = 10 [json_name = "availabilityScore"]; * @return This builder for chaining. */ public Builder clearAvailabilityScore() { bitField0_ = (bitField0_ & ~0x00000200); availabilityScore_ = 0D; onChanged(); return this; } private int protocolVersion_ ; /** *
       * The protocol version of the validator.
       * 
* * int32 protocol_version = 11 [json_name = "protocolVersion"]; * @return The protocolVersion. */ @java.lang.Override public int getProtocolVersion() { return protocolVersion_; } /** *
       * The protocol version of the validator.
       * 
* * int32 protocol_version = 11 [json_name = "protocolVersion"]; * @param value The protocolVersion to set. * @return This builder for chaining. */ public Builder setProtocolVersion(int value) { protocolVersion_ = value; bitField0_ |= 0x00000400; onChanged(); return this; } /** *
       * The protocol version of the validator.
       * 
* * int32 protocol_version = 11 [json_name = "protocolVersion"]; * @return This builder for chaining. */ public Builder clearProtocolVersion() { bitField0_ = (bitField0_ & ~0x00000400); protocolVersion_ = 0; onChanged(); return this; } private boolean isDelegated_ ; /** *
       * Whether the validator is delegated.
       * 
* * bool is_delegated = 12 [json_name = "isDelegated"]; * @return The isDelegated. */ @java.lang.Override public boolean getIsDelegated() { return isDelegated_; } /** *
       * Whether the validator is delegated.
       * 
* * bool is_delegated = 12 [json_name = "isDelegated"]; * @param value The isDelegated to set. * @return This builder for chaining. */ public Builder setIsDelegated(boolean value) { isDelegated_ = value; bitField0_ |= 0x00000800; onChanged(); return this; } /** *
       * Whether the validator is delegated.
       * 
* * bool is_delegated = 12 [json_name = "isDelegated"]; * @return This builder for chaining. */ public Builder clearIsDelegated() { bitField0_ = (bitField0_ & ~0x00000800); isDelegated_ = false; onChanged(); return this; } private java.lang.Object delegateOwner_ = ""; /** *
       * The address of the stake owner of the validator.
       * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return The delegateOwner. */ public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the stake owner of the validator.
       * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the stake owner of the validator.
       * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @param value The delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } delegateOwner_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } /** *
       * The address of the stake owner of the validator.
       * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @return This builder for chaining. */ public Builder clearDelegateOwner() { delegateOwner_ = getDefaultInstance().getDelegateOwner(); bitField0_ = (bitField0_ & ~0x00001000); onChanged(); return this; } /** *
       * The address of the stake owner of the validator.
       * 
* * string delegate_owner = 13 [json_name = "delegateOwner"]; * @param value The bytes for delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); delegateOwner_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } private long delegateShare_ ; /** *
       * The share of the stake owner of the validator.
       * 
* * int64 delegate_share = 14 [json_name = "delegateShare"]; * @return The delegateShare. */ @java.lang.Override public long getDelegateShare() { return delegateShare_; } /** *
       * The share of the stake owner of the validator.
       * 
* * int64 delegate_share = 14 [json_name = "delegateShare"]; * @param value The delegateShare to set. * @return This builder for chaining. */ public Builder setDelegateShare(long value) { delegateShare_ = value; bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * The share of the stake owner of the validator.
       * 
* * int64 delegate_share = 14 [json_name = "delegateShare"]; * @return This builder for chaining. */ public Builder clearDelegateShare() { bitField0_ = (bitField0_ & ~0x00002000); delegateShare_ = 0L; onChanged(); return this; } private int delegateExpiry_ ; /** *
       * The expiry of the stake owner of the validator.
       * 
* * uint32 delegate_expiry = 15 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ @java.lang.Override public int getDelegateExpiry() { return delegateExpiry_; } /** *
       * The expiry of the stake owner of the validator.
       * 
* * uint32 delegate_expiry = 15 [json_name = "delegateExpiry"]; * @param value The delegateExpiry to set. * @return This builder for chaining. */ public Builder setDelegateExpiry(int value) { delegateExpiry_ = value; bitField0_ |= 0x00004000; onChanged(); return this; } /** *
       * The expiry of the stake owner of the validator.
       * 
* * uint32 delegate_expiry = 15 [json_name = "delegateExpiry"]; * @return This builder for chaining. */ public Builder clearDelegateExpiry() { bitField0_ = (bitField0_ & ~0x00004000); delegateExpiry_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ValidatorInfo) } // @@protoc_insertion_point(class_scope:pactus.ValidatorInfo) private static final pactus.BlockchainOuterClass.ValidatorInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.ValidatorInfo(); } public static pactus.BlockchainOuterClass.ValidatorInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ValidatorInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.ValidatorInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AccountInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.AccountInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The hash of the account.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ java.lang.String getHash(); /** *
     * The hash of the account.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ com.google.protobuf.ByteString getHashBytes(); /** *
     * The serialized data of the account.
     * 
* * string data = 2 [json_name = "data"]; * @return The data. */ java.lang.String getData(); /** *
     * The serialized data of the account.
     * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ com.google.protobuf.ByteString getDataBytes(); /** *
     * The unique number assigned to the account.
     * 
* * int32 number = 3 [json_name = "number"]; * @return The number. */ int getNumber(); /** *
     * The balance of the account in NanoPAC.
     * 
* * int64 balance = 4 [json_name = "balance"]; * @return The balance. */ long getBalance(); /** *
     * The address of the account.
     * 
* * string address = 5 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address of the account.
     * 
* * string address = 5 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Message contains information about an account.
   * 
* * Protobuf type {@code pactus.AccountInfo} */ public static final class AccountInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.AccountInfo) AccountInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "AccountInfo"); } // Use AccountInfo.newBuilder() to construct. private AccountInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private AccountInfo() { hash_ = ""; data_ = ""; address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_AccountInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_AccountInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.AccountInfo.class, pactus.BlockchainOuterClass.AccountInfo.Builder.class); } public static final int HASH_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object hash_ = ""; /** *
     * The hash of the account.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ @java.lang.Override public java.lang.String getHash() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } } /** *
     * The hash of the account.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ @java.lang.Override public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object data_ = ""; /** *
     * The serialized data of the account.
     * 
* * string data = 2 [json_name = "data"]; * @return The data. */ @java.lang.Override public java.lang.String getData() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } } /** *
     * The serialized data of the account.
     * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ @java.lang.Override public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NUMBER_FIELD_NUMBER = 3; private int number_ = 0; /** *
     * The unique number assigned to the account.
     * 
* * int32 number = 3 [json_name = "number"]; * @return The number. */ @java.lang.Override public int getNumber() { return number_; } public static final int BALANCE_FIELD_NUMBER = 4; private long balance_ = 0L; /** *
     * The balance of the account in NanoPAC.
     * 
* * int64 balance = 4 [json_name = "balance"]; * @return The balance. */ @java.lang.Override public long getBalance() { return balance_; } public static final int ADDRESS_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address of the account.
     * 
* * string address = 5 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address of the account.
     * 
* * string address = 5 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, hash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, data_); } if (number_ != 0) { output.writeInt32(3, number_); } if (balance_ != 0L) { output.writeInt64(4, balance_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, hash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, data_); } if (number_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, number_); } if (balance_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, balance_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.AccountInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.AccountInfo other = (pactus.BlockchainOuterClass.AccountInfo) obj; if (!getHash() .equals(other.getHash())) return false; if (!getData() .equals(other.getData())) return false; if (getNumber() != other.getNumber()) return false; if (getBalance() != other.getBalance()) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HASH_FIELD_NUMBER; hash = (53 * hash) + getHash().hashCode(); hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); hash = (37 * hash) + NUMBER_FIELD_NUMBER; hash = (53 * hash) + getNumber(); hash = (37 * hash) + BALANCE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getBalance()); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.AccountInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.AccountInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.AccountInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.AccountInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about an account.
     * 
* * Protobuf type {@code pactus.AccountInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.AccountInfo) pactus.BlockchainOuterClass.AccountInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_AccountInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_AccountInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.AccountInfo.class, pactus.BlockchainOuterClass.AccountInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.AccountInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; hash_ = ""; data_ = ""; number_ = 0; balance_ = 0L; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_AccountInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.AccountInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.AccountInfo build() { pactus.BlockchainOuterClass.AccountInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.AccountInfo buildPartial() { pactus.BlockchainOuterClass.AccountInfo result = new pactus.BlockchainOuterClass.AccountInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.AccountInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.hash_ = hash_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.data_ = data_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.number_ = number_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.balance_ = balance_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.AccountInfo) { return mergeFrom((pactus.BlockchainOuterClass.AccountInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.AccountInfo other) { if (other == pactus.BlockchainOuterClass.AccountInfo.getDefaultInstance()) return this; if (!other.getHash().isEmpty()) { hash_ = other.hash_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getData().isEmpty()) { data_ = other.data_; bitField0_ |= 0x00000002; onChanged(); } if (other.getNumber() != 0) { setNumber(other.getNumber()); } if (other.getBalance() != 0L) { setBalance(other.getBalance()); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { hash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { data_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { number_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { balance_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object hash_ = ""; /** *
       * The hash of the account.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ public java.lang.String getHash() { java.lang.Object ref = hash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the account.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the account.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The hash of the account.
       * 
* * string hash = 1 [json_name = "hash"]; * @return This builder for chaining. */ public Builder clearHash() { hash_ = getDefaultInstance().getHash(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The hash of the account.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The bytes for hash to set. * @return This builder for chaining. */ public Builder setHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object data_ = ""; /** *
       * The serialized data of the account.
       * 
* * string data = 2 [json_name = "data"]; * @return The data. */ public java.lang.String getData() { java.lang.Object ref = data_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The serialized data of the account.
       * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The serialized data of the account.
       * 
* * string data = 2 [json_name = "data"]; * @param value The data to set. * @return This builder for chaining. */ public Builder setData( java.lang.String value) { if (value == null) { throw new NullPointerException(); } data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The serialized data of the account.
       * 
* * string data = 2 [json_name = "data"]; * @return This builder for chaining. */ public Builder clearData() { data_ = getDefaultInstance().getData(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The serialized data of the account.
       * 
* * string data = 2 [json_name = "data"]; * @param value The bytes for data to set. * @return This builder for chaining. */ public Builder setDataBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int number_ ; /** *
       * The unique number assigned to the account.
       * 
* * int32 number = 3 [json_name = "number"]; * @return The number. */ @java.lang.Override public int getNumber() { return number_; } /** *
       * The unique number assigned to the account.
       * 
* * int32 number = 3 [json_name = "number"]; * @param value The number to set. * @return This builder for chaining. */ public Builder setNumber(int value) { number_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The unique number assigned to the account.
       * 
* * int32 number = 3 [json_name = "number"]; * @return This builder for chaining. */ public Builder clearNumber() { bitField0_ = (bitField0_ & ~0x00000004); number_ = 0; onChanged(); return this; } private long balance_ ; /** *
       * The balance of the account in NanoPAC.
       * 
* * int64 balance = 4 [json_name = "balance"]; * @return The balance. */ @java.lang.Override public long getBalance() { return balance_; } /** *
       * The balance of the account in NanoPAC.
       * 
* * int64 balance = 4 [json_name = "balance"]; * @param value The balance to set. * @return This builder for chaining. */ public Builder setBalance(long value) { balance_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The balance of the account in NanoPAC.
       * 
* * int64 balance = 4 [json_name = "balance"]; * @return This builder for chaining. */ public Builder clearBalance() { bitField0_ = (bitField0_ & ~0x00000008); balance_ = 0L; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address of the account.
       * 
* * string address = 5 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the account.
       * 
* * string address = 5 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the account.
       * 
* * string address = 5 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The address of the account.
       * 
* * string address = 5 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * The address of the account.
       * 
* * string address = 5 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.AccountInfo) } // @@protoc_insertion_point(class_scope:pactus.AccountInfo) private static final pactus.BlockchainOuterClass.AccountInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.AccountInfo(); } public static pactus.BlockchainOuterClass.AccountInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public AccountInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.AccountInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface BlockHeaderInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.BlockHeaderInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The version of the block.
     * 
* * int32 version = 1 [json_name = "version"]; * @return The version. */ int getVersion(); /** *
     * The hash of the previous block.
     * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return The prevBlockHash. */ java.lang.String getPrevBlockHash(); /** *
     * The hash of the previous block.
     * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return The bytes for prevBlockHash. */ com.google.protobuf.ByteString getPrevBlockHashBytes(); /** *
     * The state root hash of the blockchain.
     * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return The stateRoot. */ java.lang.String getStateRoot(); /** *
     * The state root hash of the blockchain.
     * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return The bytes for stateRoot. */ com.google.protobuf.ByteString getStateRootBytes(); /** *
     * The sortition seed of the block.
     * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return The sortitionSeed. */ java.lang.String getSortitionSeed(); /** *
     * The sortition seed of the block.
     * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return The bytes for sortitionSeed. */ com.google.protobuf.ByteString getSortitionSeedBytes(); /** *
     * The address of the proposer of the block.
     * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return The proposerAddress. */ java.lang.String getProposerAddress(); /** *
     * The address of the proposer of the block.
     * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return The bytes for proposerAddress. */ com.google.protobuf.ByteString getProposerAddressBytes(); } /** *
   * Message contains information about the header of a block.
   * 
* * Protobuf type {@code pactus.BlockHeaderInfo} */ public static final class BlockHeaderInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.BlockHeaderInfo) BlockHeaderInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "BlockHeaderInfo"); } // Use BlockHeaderInfo.newBuilder() to construct. private BlockHeaderInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private BlockHeaderInfo() { prevBlockHash_ = ""; stateRoot_ = ""; sortitionSeed_ = ""; proposerAddress_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_BlockHeaderInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_BlockHeaderInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.BlockHeaderInfo.class, pactus.BlockchainOuterClass.BlockHeaderInfo.Builder.class); } public static final int VERSION_FIELD_NUMBER = 1; private int version_ = 0; /** *
     * The version of the block.
     * 
* * int32 version = 1 [json_name = "version"]; * @return The version. */ @java.lang.Override public int getVersion() { return version_; } public static final int PREV_BLOCK_HASH_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object prevBlockHash_ = ""; /** *
     * The hash of the previous block.
     * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return The prevBlockHash. */ @java.lang.Override public java.lang.String getPrevBlockHash() { java.lang.Object ref = prevBlockHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); prevBlockHash_ = s; return s; } } /** *
     * The hash of the previous block.
     * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return The bytes for prevBlockHash. */ @java.lang.Override public com.google.protobuf.ByteString getPrevBlockHashBytes() { java.lang.Object ref = prevBlockHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); prevBlockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATE_ROOT_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object stateRoot_ = ""; /** *
     * The state root hash of the blockchain.
     * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return The stateRoot. */ @java.lang.Override public java.lang.String getStateRoot() { java.lang.Object ref = stateRoot_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); stateRoot_ = s; return s; } } /** *
     * The state root hash of the blockchain.
     * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return The bytes for stateRoot. */ @java.lang.Override public com.google.protobuf.ByteString getStateRootBytes() { java.lang.Object ref = stateRoot_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); stateRoot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SORTITION_SEED_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object sortitionSeed_ = ""; /** *
     * The sortition seed of the block.
     * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return The sortitionSeed. */ @java.lang.Override public java.lang.String getSortitionSeed() { java.lang.Object ref = sortitionSeed_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sortitionSeed_ = s; return s; } } /** *
     * The sortition seed of the block.
     * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return The bytes for sortitionSeed. */ @java.lang.Override public com.google.protobuf.ByteString getSortitionSeedBytes() { java.lang.Object ref = sortitionSeed_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sortitionSeed_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROPOSER_ADDRESS_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object proposerAddress_ = ""; /** *
     * The address of the proposer of the block.
     * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return The proposerAddress. */ @java.lang.Override public java.lang.String getProposerAddress() { java.lang.Object ref = proposerAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); proposerAddress_ = s; return s; } } /** *
     * The address of the proposer of the block.
     * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return The bytes for proposerAddress. */ @java.lang.Override public com.google.protobuf.ByteString getProposerAddressBytes() { java.lang.Object ref = proposerAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); proposerAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (version_ != 0) { output.writeInt32(1, version_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(prevBlockHash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, prevBlockHash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(stateRoot_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, stateRoot_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sortitionSeed_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, sortitionSeed_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(proposerAddress_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, proposerAddress_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (version_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, version_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(prevBlockHash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, prevBlockHash_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(stateRoot_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, stateRoot_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sortitionSeed_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, sortitionSeed_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(proposerAddress_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, proposerAddress_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.BlockHeaderInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.BlockHeaderInfo other = (pactus.BlockchainOuterClass.BlockHeaderInfo) obj; if (getVersion() != other.getVersion()) return false; if (!getPrevBlockHash() .equals(other.getPrevBlockHash())) return false; if (!getStateRoot() .equals(other.getStateRoot())) return false; if (!getSortitionSeed() .equals(other.getSortitionSeed())) return false; if (!getProposerAddress() .equals(other.getProposerAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion(); hash = (37 * hash) + PREV_BLOCK_HASH_FIELD_NUMBER; hash = (53 * hash) + getPrevBlockHash().hashCode(); hash = (37 * hash) + STATE_ROOT_FIELD_NUMBER; hash = (53 * hash) + getStateRoot().hashCode(); hash = (37 * hash) + SORTITION_SEED_FIELD_NUMBER; hash = (53 * hash) + getSortitionSeed().hashCode(); hash = (37 * hash) + PROPOSER_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getProposerAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.BlockHeaderInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.BlockHeaderInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about the header of a block.
     * 
* * Protobuf type {@code pactus.BlockHeaderInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.BlockHeaderInfo) pactus.BlockchainOuterClass.BlockHeaderInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_BlockHeaderInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_BlockHeaderInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.BlockHeaderInfo.class, pactus.BlockchainOuterClass.BlockHeaderInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.BlockHeaderInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; version_ = 0; prevBlockHash_ = ""; stateRoot_ = ""; sortitionSeed_ = ""; proposerAddress_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_BlockHeaderInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.BlockHeaderInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.BlockHeaderInfo build() { pactus.BlockchainOuterClass.BlockHeaderInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.BlockHeaderInfo buildPartial() { pactus.BlockchainOuterClass.BlockHeaderInfo result = new pactus.BlockchainOuterClass.BlockHeaderInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.BlockHeaderInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.version_ = version_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.prevBlockHash_ = prevBlockHash_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.stateRoot_ = stateRoot_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.sortitionSeed_ = sortitionSeed_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.proposerAddress_ = proposerAddress_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.BlockHeaderInfo) { return mergeFrom((pactus.BlockchainOuterClass.BlockHeaderInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.BlockHeaderInfo other) { if (other == pactus.BlockchainOuterClass.BlockHeaderInfo.getDefaultInstance()) return this; if (other.getVersion() != 0) { setVersion(other.getVersion()); } if (!other.getPrevBlockHash().isEmpty()) { prevBlockHash_ = other.prevBlockHash_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getStateRoot().isEmpty()) { stateRoot_ = other.stateRoot_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getSortitionSeed().isEmpty()) { sortitionSeed_ = other.sortitionSeed_; bitField0_ |= 0x00000008; onChanged(); } if (!other.getProposerAddress().isEmpty()) { proposerAddress_ = other.proposerAddress_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { version_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { prevBlockHash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { stateRoot_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { sortitionSeed_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 42: { proposerAddress_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int version_ ; /** *
       * The version of the block.
       * 
* * int32 version = 1 [json_name = "version"]; * @return The version. */ @java.lang.Override public int getVersion() { return version_; } /** *
       * The version of the block.
       * 
* * int32 version = 1 [json_name = "version"]; * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(int value) { version_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The version of the block.
       * 
* * int32 version = 1 [json_name = "version"]; * @return This builder for chaining. */ public Builder clearVersion() { bitField0_ = (bitField0_ & ~0x00000001); version_ = 0; onChanged(); return this; } private java.lang.Object prevBlockHash_ = ""; /** *
       * The hash of the previous block.
       * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return The prevBlockHash. */ public java.lang.String getPrevBlockHash() { java.lang.Object ref = prevBlockHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); prevBlockHash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the previous block.
       * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return The bytes for prevBlockHash. */ public com.google.protobuf.ByteString getPrevBlockHashBytes() { java.lang.Object ref = prevBlockHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); prevBlockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the previous block.
       * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @param value The prevBlockHash to set. * @return This builder for chaining. */ public Builder setPrevBlockHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } prevBlockHash_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The hash of the previous block.
       * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @return This builder for chaining. */ public Builder clearPrevBlockHash() { prevBlockHash_ = getDefaultInstance().getPrevBlockHash(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The hash of the previous block.
       * 
* * string prev_block_hash = 2 [json_name = "prevBlockHash"]; * @param value The bytes for prevBlockHash to set. * @return This builder for chaining. */ public Builder setPrevBlockHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); prevBlockHash_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object stateRoot_ = ""; /** *
       * The state root hash of the blockchain.
       * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return The stateRoot. */ public java.lang.String getStateRoot() { java.lang.Object ref = stateRoot_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); stateRoot_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The state root hash of the blockchain.
       * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return The bytes for stateRoot. */ public com.google.protobuf.ByteString getStateRootBytes() { java.lang.Object ref = stateRoot_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); stateRoot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The state root hash of the blockchain.
       * 
* * string state_root = 3 [json_name = "stateRoot"]; * @param value The stateRoot to set. * @return This builder for chaining. */ public Builder setStateRoot( java.lang.String value) { if (value == null) { throw new NullPointerException(); } stateRoot_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The state root hash of the blockchain.
       * 
* * string state_root = 3 [json_name = "stateRoot"]; * @return This builder for chaining. */ public Builder clearStateRoot() { stateRoot_ = getDefaultInstance().getStateRoot(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The state root hash of the blockchain.
       * 
* * string state_root = 3 [json_name = "stateRoot"]; * @param value The bytes for stateRoot to set. * @return This builder for chaining. */ public Builder setStateRootBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); stateRoot_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object sortitionSeed_ = ""; /** *
       * The sortition seed of the block.
       * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return The sortitionSeed. */ public java.lang.String getSortitionSeed() { java.lang.Object ref = sortitionSeed_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sortitionSeed_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sortition seed of the block.
       * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return The bytes for sortitionSeed. */ public com.google.protobuf.ByteString getSortitionSeedBytes() { java.lang.Object ref = sortitionSeed_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sortitionSeed_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sortition seed of the block.
       * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @param value The sortitionSeed to set. * @return This builder for chaining. */ public Builder setSortitionSeed( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sortitionSeed_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The sortition seed of the block.
       * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @return This builder for chaining. */ public Builder clearSortitionSeed() { sortitionSeed_ = getDefaultInstance().getSortitionSeed(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The sortition seed of the block.
       * 
* * string sortition_seed = 4 [json_name = "sortitionSeed"]; * @param value The bytes for sortitionSeed to set. * @return This builder for chaining. */ public Builder setSortitionSeedBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sortitionSeed_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private java.lang.Object proposerAddress_ = ""; /** *
       * The address of the proposer of the block.
       * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return The proposerAddress. */ public java.lang.String getProposerAddress() { java.lang.Object ref = proposerAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); proposerAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the proposer of the block.
       * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return The bytes for proposerAddress. */ public com.google.protobuf.ByteString getProposerAddressBytes() { java.lang.Object ref = proposerAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); proposerAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the proposer of the block.
       * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @param value The proposerAddress to set. * @return This builder for chaining. */ public Builder setProposerAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } proposerAddress_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The address of the proposer of the block.
       * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @return This builder for chaining. */ public Builder clearProposerAddress() { proposerAddress_ = getDefaultInstance().getProposerAddress(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * The address of the proposer of the block.
       * 
* * string proposer_address = 5 [json_name = "proposerAddress"]; * @param value The bytes for proposerAddress to set. * @return This builder for chaining. */ public Builder setProposerAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); proposerAddress_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.BlockHeaderInfo) } // @@protoc_insertion_point(class_scope:pactus.BlockHeaderInfo) private static final pactus.BlockchainOuterClass.BlockHeaderInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.BlockHeaderInfo(); } public static pactus.BlockchainOuterClass.BlockHeaderInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public BlockHeaderInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.BlockHeaderInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CertificateInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CertificateInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The hash of the certificate.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ java.lang.String getHash(); /** *
     * The hash of the certificate.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ com.google.protobuf.ByteString getHashBytes(); /** *
     * The round of the certificate.
     * 
* * int32 round = 2 [json_name = "round"]; * @return The round. */ int getRound(); /** *
     * List of committers in the certificate.
     * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return A list containing the committers. */ java.util.List getCommittersList(); /** *
     * List of committers in the certificate.
     * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return The count of committers. */ int getCommittersCount(); /** *
     * List of committers in the certificate.
     * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @param index The index of the element to return. * @return The committers at the given index. */ int getCommitters(int index); /** *
     * List of absentees in the certificate.
     * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return A list containing the absentees. */ java.util.List getAbsenteesList(); /** *
     * List of absentees in the certificate.
     * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return The count of absentees. */ int getAbsenteesCount(); /** *
     * List of absentees in the certificate.
     * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @param index The index of the element to return. * @return The absentees at the given index. */ int getAbsentees(int index); /** *
     * The signature of the certificate.
     * 
* * string signature = 5 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The signature of the certificate.
     * 
* * string signature = 5 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); } /** *
   * Message contains information about a certificate.
   * 
* * Protobuf type {@code pactus.CertificateInfo} */ public static final class CertificateInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CertificateInfo) CertificateInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CertificateInfo"); } // Use CertificateInfo.newBuilder() to construct. private CertificateInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CertificateInfo() { hash_ = ""; committers_ = emptyIntList(); absentees_ = emptyIntList(); signature_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_CertificateInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_CertificateInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.CertificateInfo.class, pactus.BlockchainOuterClass.CertificateInfo.Builder.class); } public static final int HASH_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object hash_ = ""; /** *
     * The hash of the certificate.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ @java.lang.Override public java.lang.String getHash() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } } /** *
     * The hash of the certificate.
     * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ @java.lang.Override public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ROUND_FIELD_NUMBER = 2; private int round_ = 0; /** *
     * The round of the certificate.
     * 
* * int32 round = 2 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } public static final int COMMITTERS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private com.google.protobuf.Internal.IntList committers_ = emptyIntList(); /** *
     * List of committers in the certificate.
     * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return A list containing the committers. */ @java.lang.Override public java.util.List getCommittersList() { return committers_; } /** *
     * List of committers in the certificate.
     * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return The count of committers. */ public int getCommittersCount() { return committers_.size(); } /** *
     * List of committers in the certificate.
     * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @param index The index of the element to return. * @return The committers at the given index. */ public int getCommitters(int index) { return committers_.getInt(index); } private int committersMemoizedSerializedSize = -1; public static final int ABSENTEES_FIELD_NUMBER = 4; @SuppressWarnings("serial") private com.google.protobuf.Internal.IntList absentees_ = emptyIntList(); /** *
     * List of absentees in the certificate.
     * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return A list containing the absentees. */ @java.lang.Override public java.util.List getAbsenteesList() { return absentees_; } /** *
     * List of absentees in the certificate.
     * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return The count of absentees. */ public int getAbsenteesCount() { return absentees_.size(); } /** *
     * List of absentees in the certificate.
     * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @param index The index of the element to return. * @return The absentees at the given index. */ public int getAbsentees(int index) { return absentees_.getInt(index); } private int absenteesMemoizedSerializedSize = -1; public static final int SIGNATURE_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The signature of the certificate.
     * 
* * string signature = 5 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The signature of the certificate.
     * 
* * string signature = 5 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, hash_); } if (round_ != 0) { output.writeInt32(2, round_); } if (getCommittersList().size() > 0) { output.writeUInt32NoTag(26); output.writeUInt32NoTag(committersMemoizedSerializedSize); } for (int i = 0; i < committers_.size(); i++) { output.writeInt32NoTag(committers_.getInt(i)); } if (getAbsenteesList().size() > 0) { output.writeUInt32NoTag(34); output.writeUInt32NoTag(absenteesMemoizedSerializedSize); } for (int i = 0; i < absentees_.size(); i++) { output.writeInt32NoTag(absentees_.getInt(i)); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, signature_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(hash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, hash_); } if (round_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, round_); } { int dataSize = 0; for (int i = 0; i < committers_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(committers_.getInt(i)); } size += dataSize; if (!getCommittersList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(dataSize); } committersMemoizedSerializedSize = dataSize; } { int dataSize = 0; for (int i = 0; i < absentees_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(absentees_.getInt(i)); } size += dataSize; if (!getAbsenteesList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(dataSize); } absenteesMemoizedSerializedSize = dataSize; } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, signature_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.CertificateInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.CertificateInfo other = (pactus.BlockchainOuterClass.CertificateInfo) obj; if (!getHash() .equals(other.getHash())) return false; if (getRound() != other.getRound()) return false; if (!getCommittersList() .equals(other.getCommittersList())) return false; if (!getAbsenteesList() .equals(other.getAbsenteesList())) return false; if (!getSignature() .equals(other.getSignature())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HASH_FIELD_NUMBER; hash = (53 * hash) + getHash().hashCode(); hash = (37 * hash) + ROUND_FIELD_NUMBER; hash = (53 * hash) + getRound(); if (getCommittersCount() > 0) { hash = (37 * hash) + COMMITTERS_FIELD_NUMBER; hash = (53 * hash) + getCommittersList().hashCode(); } if (getAbsenteesCount() > 0) { hash = (37 * hash) + ABSENTEES_FIELD_NUMBER; hash = (53 * hash) + getAbsenteesList().hashCode(); } hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.CertificateInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.CertificateInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.CertificateInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.CertificateInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about a certificate.
     * 
* * Protobuf type {@code pactus.CertificateInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CertificateInfo) pactus.BlockchainOuterClass.CertificateInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_CertificateInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_CertificateInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.CertificateInfo.class, pactus.BlockchainOuterClass.CertificateInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.CertificateInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; hash_ = ""; round_ = 0; committers_ = emptyIntList(); absentees_ = emptyIntList(); signature_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_CertificateInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.CertificateInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.CertificateInfo build() { pactus.BlockchainOuterClass.CertificateInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.CertificateInfo buildPartial() { pactus.BlockchainOuterClass.CertificateInfo result = new pactus.BlockchainOuterClass.CertificateInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.CertificateInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.hash_ = hash_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.round_ = round_; } if (((from_bitField0_ & 0x00000004) != 0)) { committers_.makeImmutable(); result.committers_ = committers_; } if (((from_bitField0_ & 0x00000008) != 0)) { absentees_.makeImmutable(); result.absentees_ = absentees_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.signature_ = signature_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.CertificateInfo) { return mergeFrom((pactus.BlockchainOuterClass.CertificateInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.CertificateInfo other) { if (other == pactus.BlockchainOuterClass.CertificateInfo.getDefaultInstance()) return this; if (!other.getHash().isEmpty()) { hash_ = other.hash_; bitField0_ |= 0x00000001; onChanged(); } if (other.getRound() != 0) { setRound(other.getRound()); } if (!other.committers_.isEmpty()) { if (committers_.isEmpty()) { committers_ = other.committers_; committers_.makeImmutable(); bitField0_ |= 0x00000004; } else { ensureCommittersIsMutable(); committers_.addAll(other.committers_); } onChanged(); } if (!other.absentees_.isEmpty()) { if (absentees_.isEmpty()) { absentees_ = other.absentees_; absentees_.makeImmutable(); bitField0_ |= 0x00000008; } else { ensureAbsenteesIsMutable(); absentees_.addAll(other.absentees_); } onChanged(); } if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { hash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { round_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { int v = input.readInt32(); ensureCommittersIsMutable(); committers_.addInt(v); break; } // case 24 case 26: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); ensureCommittersIsMutable(); while (input.getBytesUntilLimit() > 0) { committers_.addInt(input.readInt32()); } input.popLimit(limit); break; } // case 26 case 32: { int v = input.readInt32(); ensureAbsenteesIsMutable(); absentees_.addInt(v); break; } // case 32 case 34: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); ensureAbsenteesIsMutable(); while (input.getBytesUntilLimit() > 0) { absentees_.addInt(input.readInt32()); } input.popLimit(limit); break; } // case 34 case 42: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object hash_ = ""; /** *
       * The hash of the certificate.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The hash. */ public java.lang.String getHash() { java.lang.Object ref = hash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); hash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the certificate.
       * 
* * string hash = 1 [json_name = "hash"]; * @return The bytes for hash. */ public com.google.protobuf.ByteString getHashBytes() { java.lang.Object ref = hash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); hash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the certificate.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The hash of the certificate.
       * 
* * string hash = 1 [json_name = "hash"]; * @return This builder for chaining. */ public Builder clearHash() { hash_ = getDefaultInstance().getHash(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The hash of the certificate.
       * 
* * string hash = 1 [json_name = "hash"]; * @param value The bytes for hash to set. * @return This builder for chaining. */ public Builder setHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); hash_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int round_ ; /** *
       * The round of the certificate.
       * 
* * int32 round = 2 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } /** *
       * The round of the certificate.
       * 
* * int32 round = 2 [json_name = "round"]; * @param value The round to set. * @return This builder for chaining. */ public Builder setRound(int value) { round_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The round of the certificate.
       * 
* * int32 round = 2 [json_name = "round"]; * @return This builder for chaining. */ public Builder clearRound() { bitField0_ = (bitField0_ & ~0x00000002); round_ = 0; onChanged(); return this; } private com.google.protobuf.Internal.IntList committers_ = emptyIntList(); private void ensureCommittersIsMutable() { if (!committers_.isModifiable()) { committers_ = makeMutableCopy(committers_); } bitField0_ |= 0x00000004; } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return A list containing the committers. */ public java.util.List getCommittersList() { committers_.makeImmutable(); return committers_; } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return The count of committers. */ public int getCommittersCount() { return committers_.size(); } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @param index The index of the element to return. * @return The committers at the given index. */ public int getCommitters(int index) { return committers_.getInt(index); } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @param index The index to set the value at. * @param value The committers to set. * @return This builder for chaining. */ public Builder setCommitters( int index, int value) { ensureCommittersIsMutable(); committers_.setInt(index, value); bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @param value The committers to add. * @return This builder for chaining. */ public Builder addCommitters(int value) { ensureCommittersIsMutable(); committers_.addInt(value); bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @param values The committers to add. * @return This builder for chaining. */ public Builder addAllCommitters( java.lang.Iterable values) { ensureCommittersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, committers_); bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * List of committers in the certificate.
       * 
* * repeated int32 committers = 3 [json_name = "committers"]; * @return This builder for chaining. */ public Builder clearCommitters() { committers_ = emptyIntList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } private com.google.protobuf.Internal.IntList absentees_ = emptyIntList(); private void ensureAbsenteesIsMutable() { if (!absentees_.isModifiable()) { absentees_ = makeMutableCopy(absentees_); } bitField0_ |= 0x00000008; } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return A list containing the absentees. */ public java.util.List getAbsenteesList() { absentees_.makeImmutable(); return absentees_; } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return The count of absentees. */ public int getAbsenteesCount() { return absentees_.size(); } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @param index The index of the element to return. * @return The absentees at the given index. */ public int getAbsentees(int index) { return absentees_.getInt(index); } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @param index The index to set the value at. * @param value The absentees to set. * @return This builder for chaining. */ public Builder setAbsentees( int index, int value) { ensureAbsenteesIsMutable(); absentees_.setInt(index, value); bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @param value The absentees to add. * @return This builder for chaining. */ public Builder addAbsentees(int value) { ensureAbsenteesIsMutable(); absentees_.addInt(value); bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @param values The absentees to add. * @return This builder for chaining. */ public Builder addAllAbsentees( java.lang.Iterable values) { ensureAbsenteesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, absentees_); bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * List of absentees in the certificate.
       * 
* * repeated int32 absentees = 4 [json_name = "absentees"]; * @return This builder for chaining. */ public Builder clearAbsentees() { absentees_ = emptyIntList(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } private java.lang.Object signature_ = ""; /** *
       * The signature of the certificate.
       * 
* * string signature = 5 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signature of the certificate.
       * 
* * string signature = 5 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signature of the certificate.
       * 
* * string signature = 5 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The signature of the certificate.
       * 
* * string signature = 5 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * The signature of the certificate.
       * 
* * string signature = 5 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CertificateInfo) } // @@protoc_insertion_point(class_scope:pactus.CertificateInfo) private static final pactus.BlockchainOuterClass.CertificateInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.CertificateInfo(); } public static pactus.BlockchainOuterClass.CertificateInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CertificateInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.CertificateInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface VoteInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.VoteInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The type of the vote.
     * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return The enum numeric value on the wire for type. */ int getTypeValue(); /** *
     * The type of the vote.
     * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return The type. */ pactus.BlockchainOuterClass.VoteType getType(); /** *
     * The address of the voter.
     * 
* * string voter = 2 [json_name = "voter"]; * @return The voter. */ java.lang.String getVoter(); /** *
     * The address of the voter.
     * 
* * string voter = 2 [json_name = "voter"]; * @return The bytes for voter. */ com.google.protobuf.ByteString getVoterBytes(); /** *
     * The hash of the block being voted on.
     * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return The blockHash. */ java.lang.String getBlockHash(); /** *
     * The hash of the block being voted on.
     * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return The bytes for blockHash. */ com.google.protobuf.ByteString getBlockHashBytes(); /** *
     * The consensus round of the vote.
     * 
* * int32 round = 4 [json_name = "round"]; * @return The round. */ int getRound(); /** *
     * The change-proposer round of the vote.
     * 
* * int32 cp_round = 5 [json_name = "cpRound"]; * @return The cpRound. */ int getCpRound(); /** *
     * The change-proposer value of the vote.
     * 
* * int32 cp_value = 6 [json_name = "cpValue"]; * @return The cpValue. */ int getCpValue(); } /** *
   * Message contains information about a vote.
   * 
* * Protobuf type {@code pactus.VoteInfo} */ public static final class VoteInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.VoteInfo) VoteInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "VoteInfo"); } // Use VoteInfo.newBuilder() to construct. private VoteInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private VoteInfo() { type_ = 0; voter_ = ""; blockHash_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_VoteInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_VoteInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.VoteInfo.class, pactus.BlockchainOuterClass.VoteInfo.Builder.class); } public static final int TYPE_FIELD_NUMBER = 1; private int type_ = 0; /** *
     * The type of the vote.
     * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** *
     * The type of the vote.
     * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return The type. */ @java.lang.Override public pactus.BlockchainOuterClass.VoteType getType() { pactus.BlockchainOuterClass.VoteType result = pactus.BlockchainOuterClass.VoteType.forNumber(type_); return result == null ? pactus.BlockchainOuterClass.VoteType.UNRECOGNIZED : result; } public static final int VOTER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object voter_ = ""; /** *
     * The address of the voter.
     * 
* * string voter = 2 [json_name = "voter"]; * @return The voter. */ @java.lang.Override public java.lang.String getVoter() { java.lang.Object ref = voter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); voter_ = s; return s; } } /** *
     * The address of the voter.
     * 
* * string voter = 2 [json_name = "voter"]; * @return The bytes for voter. */ @java.lang.Override public com.google.protobuf.ByteString getVoterBytes() { java.lang.Object ref = voter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); voter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int BLOCK_HASH_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object blockHash_ = ""; /** *
     * The hash of the block being voted on.
     * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return The blockHash. */ @java.lang.Override public java.lang.String getBlockHash() { java.lang.Object ref = blockHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); blockHash_ = s; return s; } } /** *
     * The hash of the block being voted on.
     * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return The bytes for blockHash. */ @java.lang.Override public com.google.protobuf.ByteString getBlockHashBytes() { java.lang.Object ref = blockHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); blockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ROUND_FIELD_NUMBER = 4; private int round_ = 0; /** *
     * The consensus round of the vote.
     * 
* * int32 round = 4 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } public static final int CP_ROUND_FIELD_NUMBER = 5; private int cpRound_ = 0; /** *
     * The change-proposer round of the vote.
     * 
* * int32 cp_round = 5 [json_name = "cpRound"]; * @return The cpRound. */ @java.lang.Override public int getCpRound() { return cpRound_; } public static final int CP_VALUE_FIELD_NUMBER = 6; private int cpValue_ = 0; /** *
     * The change-proposer value of the vote.
     * 
* * int32 cp_value = 6 [json_name = "cpValue"]; * @return The cpValue. */ @java.lang.Override public int getCpValue() { return cpValue_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (type_ != pactus.BlockchainOuterClass.VoteType.VOTE_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(1, type_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(voter_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, voter_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(blockHash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, blockHash_); } if (round_ != 0) { output.writeInt32(4, round_); } if (cpRound_ != 0) { output.writeInt32(5, cpRound_); } if (cpValue_ != 0) { output.writeInt32(6, cpValue_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (type_ != pactus.BlockchainOuterClass.VoteType.VOTE_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, type_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(voter_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, voter_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(blockHash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, blockHash_); } if (round_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, round_); } if (cpRound_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(5, cpRound_); } if (cpValue_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(6, cpValue_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.VoteInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.VoteInfo other = (pactus.BlockchainOuterClass.VoteInfo) obj; if (type_ != other.type_) return false; if (!getVoter() .equals(other.getVoter())) return false; if (!getBlockHash() .equals(other.getBlockHash())) return false; if (getRound() != other.getRound()) return false; if (getCpRound() != other.getCpRound()) return false; if (getCpValue() != other.getCpValue()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + VOTER_FIELD_NUMBER; hash = (53 * hash) + getVoter().hashCode(); hash = (37 * hash) + BLOCK_HASH_FIELD_NUMBER; hash = (53 * hash) + getBlockHash().hashCode(); hash = (37 * hash) + ROUND_FIELD_NUMBER; hash = (53 * hash) + getRound(); hash = (37 * hash) + CP_ROUND_FIELD_NUMBER; hash = (53 * hash) + getCpRound(); hash = (37 * hash) + CP_VALUE_FIELD_NUMBER; hash = (53 * hash) + getCpValue(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.VoteInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.VoteInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.VoteInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.VoteInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about a vote.
     * 
* * Protobuf type {@code pactus.VoteInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.VoteInfo) pactus.BlockchainOuterClass.VoteInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_VoteInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_VoteInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.VoteInfo.class, pactus.BlockchainOuterClass.VoteInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.VoteInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; type_ = 0; voter_ = ""; blockHash_ = ""; round_ = 0; cpRound_ = 0; cpValue_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_VoteInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.VoteInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.VoteInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.VoteInfo build() { pactus.BlockchainOuterClass.VoteInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.VoteInfo buildPartial() { pactus.BlockchainOuterClass.VoteInfo result = new pactus.BlockchainOuterClass.VoteInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.VoteInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.voter_ = voter_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.blockHash_ = blockHash_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.round_ = round_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.cpRound_ = cpRound_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.cpValue_ = cpValue_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.VoteInfo) { return mergeFrom((pactus.BlockchainOuterClass.VoteInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.VoteInfo other) { if (other == pactus.BlockchainOuterClass.VoteInfo.getDefaultInstance()) return this; if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (!other.getVoter().isEmpty()) { voter_ = other.voter_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getBlockHash().isEmpty()) { blockHash_ = other.blockHash_; bitField0_ |= 0x00000004; onChanged(); } if (other.getRound() != 0) { setRound(other.getRound()); } if (other.getCpRound() != 0) { setCpRound(other.getCpRound()); } if (other.getCpValue() != 0) { setCpValue(other.getCpValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { type_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { voter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { blockHash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { round_ = input.readInt32(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { cpRound_ = input.readInt32(); bitField0_ |= 0x00000010; break; } // case 40 case 48: { cpValue_ = input.readInt32(); bitField0_ |= 0x00000020; break; } // case 48 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int type_ = 0; /** *
       * The type of the vote.
       * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** *
       * The type of the vote.
       * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The type of the vote.
       * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return The type. */ @java.lang.Override public pactus.BlockchainOuterClass.VoteType getType() { pactus.BlockchainOuterClass.VoteType result = pactus.BlockchainOuterClass.VoteType.forNumber(type_); return result == null ? pactus.BlockchainOuterClass.VoteType.UNRECOGNIZED : result; } /** *
       * The type of the vote.
       * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @param value The type to set. * @return This builder for chaining. */ public Builder setType(pactus.BlockchainOuterClass.VoteType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; type_ = value.getNumber(); onChanged(); return this; } /** *
       * The type of the vote.
       * 
* * .pactus.VoteType type = 1 [json_name = "type"]; * @return This builder for chaining. */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000001); type_ = 0; onChanged(); return this; } private java.lang.Object voter_ = ""; /** *
       * The address of the voter.
       * 
* * string voter = 2 [json_name = "voter"]; * @return The voter. */ public java.lang.String getVoter() { java.lang.Object ref = voter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); voter_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the voter.
       * 
* * string voter = 2 [json_name = "voter"]; * @return The bytes for voter. */ public com.google.protobuf.ByteString getVoterBytes() { java.lang.Object ref = voter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); voter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the voter.
       * 
* * string voter = 2 [json_name = "voter"]; * @param value The voter to set. * @return This builder for chaining. */ public Builder setVoter( java.lang.String value) { if (value == null) { throw new NullPointerException(); } voter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address of the voter.
       * 
* * string voter = 2 [json_name = "voter"]; * @return This builder for chaining. */ public Builder clearVoter() { voter_ = getDefaultInstance().getVoter(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address of the voter.
       * 
* * string voter = 2 [json_name = "voter"]; * @param value The bytes for voter to set. * @return This builder for chaining. */ public Builder setVoterBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); voter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object blockHash_ = ""; /** *
       * The hash of the block being voted on.
       * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return The blockHash. */ public java.lang.String getBlockHash() { java.lang.Object ref = blockHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); blockHash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The hash of the block being voted on.
       * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return The bytes for blockHash. */ public com.google.protobuf.ByteString getBlockHashBytes() { java.lang.Object ref = blockHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); blockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The hash of the block being voted on.
       * 
* * string block_hash = 3 [json_name = "blockHash"]; * @param value The blockHash to set. * @return This builder for chaining. */ public Builder setBlockHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } blockHash_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The hash of the block being voted on.
       * 
* * string block_hash = 3 [json_name = "blockHash"]; * @return This builder for chaining. */ public Builder clearBlockHash() { blockHash_ = getDefaultInstance().getBlockHash(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The hash of the block being voted on.
       * 
* * string block_hash = 3 [json_name = "blockHash"]; * @param value The bytes for blockHash to set. * @return This builder for chaining. */ public Builder setBlockHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); blockHash_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int round_ ; /** *
       * The consensus round of the vote.
       * 
* * int32 round = 4 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } /** *
       * The consensus round of the vote.
       * 
* * int32 round = 4 [json_name = "round"]; * @param value The round to set. * @return This builder for chaining. */ public Builder setRound(int value) { round_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The consensus round of the vote.
       * 
* * int32 round = 4 [json_name = "round"]; * @return This builder for chaining. */ public Builder clearRound() { bitField0_ = (bitField0_ & ~0x00000008); round_ = 0; onChanged(); return this; } private int cpRound_ ; /** *
       * The change-proposer round of the vote.
       * 
* * int32 cp_round = 5 [json_name = "cpRound"]; * @return The cpRound. */ @java.lang.Override public int getCpRound() { return cpRound_; } /** *
       * The change-proposer round of the vote.
       * 
* * int32 cp_round = 5 [json_name = "cpRound"]; * @param value The cpRound to set. * @return This builder for chaining. */ public Builder setCpRound(int value) { cpRound_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The change-proposer round of the vote.
       * 
* * int32 cp_round = 5 [json_name = "cpRound"]; * @return This builder for chaining. */ public Builder clearCpRound() { bitField0_ = (bitField0_ & ~0x00000010); cpRound_ = 0; onChanged(); return this; } private int cpValue_ ; /** *
       * The change-proposer value of the vote.
       * 
* * int32 cp_value = 6 [json_name = "cpValue"]; * @return The cpValue. */ @java.lang.Override public int getCpValue() { return cpValue_; } /** *
       * The change-proposer value of the vote.
       * 
* * int32 cp_value = 6 [json_name = "cpValue"]; * @param value The cpValue to set. * @return This builder for chaining. */ public Builder setCpValue(int value) { cpValue_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The change-proposer value of the vote.
       * 
* * int32 cp_value = 6 [json_name = "cpValue"]; * @return This builder for chaining. */ public Builder clearCpValue() { bitField0_ = (bitField0_ & ~0x00000020); cpValue_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.VoteInfo) } // @@protoc_insertion_point(class_scope:pactus.VoteInfo) private static final pactus.BlockchainOuterClass.VoteInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.VoteInfo(); } public static pactus.BlockchainOuterClass.VoteInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public VoteInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.VoteInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ConsensusInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ConsensusInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The address of the consensus instance.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address of the consensus instance.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * Indicates whether the consensus instance is active and part of the committee.
     * 
* * bool active = 2 [json_name = "active"]; * @return The active. */ boolean getActive(); /** *
     * The height of the consensus instance.
     * 
* * uint32 height = 3 [json_name = "height"]; * @return The height. */ int getHeight(); /** *
     * The round of the consensus instance.
     * 
* * int32 round = 4 [json_name = "round"]; * @return The round. */ int getRound(); /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ java.util.List getVotesList(); /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ pactus.BlockchainOuterClass.VoteInfo getVotes(int index); /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ int getVotesCount(); /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ java.util.List getVotesOrBuilderList(); /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ pactus.BlockchainOuterClass.VoteInfoOrBuilder getVotesOrBuilder( int index); } /** *
   * Message contains information about a consensus instance.
   * 
* * Protobuf type {@code pactus.ConsensusInfo} */ public static final class ConsensusInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ConsensusInfo) ConsensusInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ConsensusInfo"); } // Use ConsensusInfo.newBuilder() to construct. private ConsensusInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ConsensusInfo() { address_ = ""; votes_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_ConsensusInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_ConsensusInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.ConsensusInfo.class, pactus.BlockchainOuterClass.ConsensusInfo.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address of the consensus instance.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address of the consensus instance.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ACTIVE_FIELD_NUMBER = 2; private boolean active_ = false; /** *
     * Indicates whether the consensus instance is active and part of the committee.
     * 
* * bool active = 2 [json_name = "active"]; * @return The active. */ @java.lang.Override public boolean getActive() { return active_; } public static final int HEIGHT_FIELD_NUMBER = 3; private int height_ = 0; /** *
     * The height of the consensus instance.
     * 
* * uint32 height = 3 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } public static final int ROUND_FIELD_NUMBER = 4; private int round_ = 0; /** *
     * The round of the consensus instance.
     * 
* * int32 round = 4 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } public static final int VOTES_FIELD_NUMBER = 5; @SuppressWarnings("serial") private java.util.List votes_; /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ @java.lang.Override public java.util.List getVotesList() { return votes_; } /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ @java.lang.Override public java.util.List getVotesOrBuilderList() { return votes_; } /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ @java.lang.Override public int getVotesCount() { return votes_.size(); } /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ @java.lang.Override public pactus.BlockchainOuterClass.VoteInfo getVotes(int index) { return votes_.get(index); } /** *
     * List of votes in the consensus instance.
     * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ @java.lang.Override public pactus.BlockchainOuterClass.VoteInfoOrBuilder getVotesOrBuilder( int index) { return votes_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } if (active_ != false) { output.writeBool(2, active_); } if (height_ != 0) { output.writeUInt32(3, height_); } if (round_ != 0) { output.writeInt32(4, round_); } for (int i = 0; i < votes_.size(); i++) { output.writeMessage(5, votes_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } if (active_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(2, active_); } if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(3, height_); } if (round_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, round_); } for (int i = 0; i < votes_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, votes_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.ConsensusInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.ConsensusInfo other = (pactus.BlockchainOuterClass.ConsensusInfo) obj; if (!getAddress() .equals(other.getAddress())) return false; if (getActive() != other.getActive()) return false; if (getHeight() != other.getHeight()) return false; if (getRound() != other.getRound()) return false; if (!getVotesList() .equals(other.getVotesList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + ACTIVE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getActive()); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (37 * hash) + ROUND_FIELD_NUMBER; hash = (53 * hash) + getRound(); if (getVotesCount() > 0) { hash = (37 * hash) + VOTES_FIELD_NUMBER; hash = (53 * hash) + getVotesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.ConsensusInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ConsensusInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ConsensusInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.ConsensusInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about a consensus instance.
     * 
* * Protobuf type {@code pactus.ConsensusInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ConsensusInfo) pactus.BlockchainOuterClass.ConsensusInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_ConsensusInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_ConsensusInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.ConsensusInfo.class, pactus.BlockchainOuterClass.ConsensusInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.ConsensusInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; active_ = false; height_ = 0; round_ = 0; if (votesBuilder_ == null) { votes_ = java.util.Collections.emptyList(); } else { votes_ = null; votesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000010); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_ConsensusInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.ConsensusInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.ConsensusInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.ConsensusInfo build() { pactus.BlockchainOuterClass.ConsensusInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.ConsensusInfo buildPartial() { pactus.BlockchainOuterClass.ConsensusInfo result = new pactus.BlockchainOuterClass.ConsensusInfo(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.BlockchainOuterClass.ConsensusInfo result) { if (votesBuilder_ == null) { if (((bitField0_ & 0x00000010) != 0)) { votes_ = java.util.Collections.unmodifiableList(votes_); bitField0_ = (bitField0_ & ~0x00000010); } result.votes_ = votes_; } else { result.votes_ = votesBuilder_.build(); } } private void buildPartial0(pactus.BlockchainOuterClass.ConsensusInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.active_ = active_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.height_ = height_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.round_ = round_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.ConsensusInfo) { return mergeFrom((pactus.BlockchainOuterClass.ConsensusInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.ConsensusInfo other) { if (other == pactus.BlockchainOuterClass.ConsensusInfo.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } if (other.getActive() != false) { setActive(other.getActive()); } if (other.getHeight() != 0) { setHeight(other.getHeight()); } if (other.getRound() != 0) { setRound(other.getRound()); } if (votesBuilder_ == null) { if (!other.votes_.isEmpty()) { if (votes_.isEmpty()) { votes_ = other.votes_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureVotesIsMutable(); votes_.addAll(other.votes_); } onChanged(); } } else { if (!other.votes_.isEmpty()) { if (votesBuilder_.isEmpty()) { votesBuilder_.dispose(); votesBuilder_ = null; votes_ = other.votes_; bitField0_ = (bitField0_ & ~0x00000010); votesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetVotesFieldBuilder() : null; } else { votesBuilder_.addAllMessages(other.votes_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { active_ = input.readBool(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { height_ = input.readUInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { round_ = input.readInt32(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { pactus.BlockchainOuterClass.VoteInfo m = input.readMessage( pactus.BlockchainOuterClass.VoteInfo.parser(), extensionRegistry); if (votesBuilder_ == null) { ensureVotesIsMutable(); votes_.add(m); } else { votesBuilder_.addMessage(m); } break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The address of the consensus instance.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the consensus instance.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the consensus instance.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address of the consensus instance.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address of the consensus instance.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private boolean active_ ; /** *
       * Indicates whether the consensus instance is active and part of the committee.
       * 
* * bool active = 2 [json_name = "active"]; * @return The active. */ @java.lang.Override public boolean getActive() { return active_; } /** *
       * Indicates whether the consensus instance is active and part of the committee.
       * 
* * bool active = 2 [json_name = "active"]; * @param value The active to set. * @return This builder for chaining. */ public Builder setActive(boolean value) { active_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Indicates whether the consensus instance is active and part of the committee.
       * 
* * bool active = 2 [json_name = "active"]; * @return This builder for chaining. */ public Builder clearActive() { bitField0_ = (bitField0_ & ~0x00000002); active_ = false; onChanged(); return this; } private int height_ ; /** *
       * The height of the consensus instance.
       * 
* * uint32 height = 3 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * The height of the consensus instance.
       * 
* * uint32 height = 3 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The height of the consensus instance.
       * 
* * uint32 height = 3 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000004); height_ = 0; onChanged(); return this; } private int round_ ; /** *
       * The round of the consensus instance.
       * 
* * int32 round = 4 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } /** *
       * The round of the consensus instance.
       * 
* * int32 round = 4 [json_name = "round"]; * @param value The round to set. * @return This builder for chaining. */ public Builder setRound(int value) { round_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The round of the consensus instance.
       * 
* * int32 round = 4 [json_name = "round"]; * @return This builder for chaining. */ public Builder clearRound() { bitField0_ = (bitField0_ & ~0x00000008); round_ = 0; onChanged(); return this; } private java.util.List votes_ = java.util.Collections.emptyList(); private void ensureVotesIsMutable() { if (!((bitField0_ & 0x00000010) != 0)) { votes_ = new java.util.ArrayList(votes_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.VoteInfo, pactus.BlockchainOuterClass.VoteInfo.Builder, pactus.BlockchainOuterClass.VoteInfoOrBuilder> votesBuilder_; /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public java.util.List getVotesList() { if (votesBuilder_ == null) { return java.util.Collections.unmodifiableList(votes_); } else { return votesBuilder_.getMessageList(); } } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public int getVotesCount() { if (votesBuilder_ == null) { return votes_.size(); } else { return votesBuilder_.getCount(); } } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public pactus.BlockchainOuterClass.VoteInfo getVotes(int index) { if (votesBuilder_ == null) { return votes_.get(index); } else { return votesBuilder_.getMessage(index); } } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder setVotes( int index, pactus.BlockchainOuterClass.VoteInfo value) { if (votesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVotesIsMutable(); votes_.set(index, value); onChanged(); } else { votesBuilder_.setMessage(index, value); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder setVotes( int index, pactus.BlockchainOuterClass.VoteInfo.Builder builderForValue) { if (votesBuilder_ == null) { ensureVotesIsMutable(); votes_.set(index, builderForValue.build()); onChanged(); } else { votesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder addVotes(pactus.BlockchainOuterClass.VoteInfo value) { if (votesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVotesIsMutable(); votes_.add(value); onChanged(); } else { votesBuilder_.addMessage(value); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder addVotes( int index, pactus.BlockchainOuterClass.VoteInfo value) { if (votesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVotesIsMutable(); votes_.add(index, value); onChanged(); } else { votesBuilder_.addMessage(index, value); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder addVotes( pactus.BlockchainOuterClass.VoteInfo.Builder builderForValue) { if (votesBuilder_ == null) { ensureVotesIsMutable(); votes_.add(builderForValue.build()); onChanged(); } else { votesBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder addVotes( int index, pactus.BlockchainOuterClass.VoteInfo.Builder builderForValue) { if (votesBuilder_ == null) { ensureVotesIsMutable(); votes_.add(index, builderForValue.build()); onChanged(); } else { votesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder addAllVotes( java.lang.Iterable values) { if (votesBuilder_ == null) { ensureVotesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, votes_); onChanged(); } else { votesBuilder_.addAllMessages(values); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder clearVotes() { if (votesBuilder_ == null) { votes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { votesBuilder_.clear(); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public Builder removeVotes(int index) { if (votesBuilder_ == null) { ensureVotesIsMutable(); votes_.remove(index); onChanged(); } else { votesBuilder_.remove(index); } return this; } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public pactus.BlockchainOuterClass.VoteInfo.Builder getVotesBuilder( int index) { return internalGetVotesFieldBuilder().getBuilder(index); } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public pactus.BlockchainOuterClass.VoteInfoOrBuilder getVotesOrBuilder( int index) { if (votesBuilder_ == null) { return votes_.get(index); } else { return votesBuilder_.getMessageOrBuilder(index); } } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public java.util.List getVotesOrBuilderList() { if (votesBuilder_ != null) { return votesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(votes_); } } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public pactus.BlockchainOuterClass.VoteInfo.Builder addVotesBuilder() { return internalGetVotesFieldBuilder().addBuilder( pactus.BlockchainOuterClass.VoteInfo.getDefaultInstance()); } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public pactus.BlockchainOuterClass.VoteInfo.Builder addVotesBuilder( int index) { return internalGetVotesFieldBuilder().addBuilder( index, pactus.BlockchainOuterClass.VoteInfo.getDefaultInstance()); } /** *
       * List of votes in the consensus instance.
       * 
* * repeated .pactus.VoteInfo votes = 5 [json_name = "votes"]; */ public java.util.List getVotesBuilderList() { return internalGetVotesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.VoteInfo, pactus.BlockchainOuterClass.VoteInfo.Builder, pactus.BlockchainOuterClass.VoteInfoOrBuilder> internalGetVotesFieldBuilder() { if (votesBuilder_ == null) { votesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.BlockchainOuterClass.VoteInfo, pactus.BlockchainOuterClass.VoteInfo.Builder, pactus.BlockchainOuterClass.VoteInfoOrBuilder>( votes_, ((bitField0_ & 0x00000010) != 0), getParentForChildren(), isClean()); votes_ = null; } return votesBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.ConsensusInfo) } // @@protoc_insertion_point(class_scope:pactus.ConsensusInfo) private static final pactus.BlockchainOuterClass.ConsensusInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.ConsensusInfo(); } public static pactus.BlockchainOuterClass.ConsensusInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ConsensusInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.ConsensusInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ProposalInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ProposalInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the proposal.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ int getHeight(); /** *
     * The round of the proposal.
     * 
* * int32 round = 2 [json_name = "round"]; * @return The round. */ int getRound(); /** *
     * The block data of the proposal.
     * 
* * string block_data = 3 [json_name = "blockData"]; * @return The blockData. */ java.lang.String getBlockData(); /** *
     * The block data of the proposal.
     * 
* * string block_data = 3 [json_name = "blockData"]; * @return The bytes for blockData. */ com.google.protobuf.ByteString getBlockDataBytes(); /** *
     * The signature of the proposal, signed by the proposer.
     * 
* * string signature = 4 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The signature of the proposal, signed by the proposer.
     * 
* * string signature = 4 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); } /** *
   * Message contains information about a proposal.
   * 
* * Protobuf type {@code pactus.ProposalInfo} */ public static final class ProposalInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ProposalInfo) ProposalInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ProposalInfo"); } // Use ProposalInfo.newBuilder() to construct. private ProposalInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ProposalInfo() { blockData_ = ""; signature_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_ProposalInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_ProposalInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.ProposalInfo.class, pactus.BlockchainOuterClass.ProposalInfo.Builder.class); } public static final int HEIGHT_FIELD_NUMBER = 1; private int height_ = 0; /** *
     * The height of the proposal.
     * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } public static final int ROUND_FIELD_NUMBER = 2; private int round_ = 0; /** *
     * The round of the proposal.
     * 
* * int32 round = 2 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } public static final int BLOCK_DATA_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object blockData_ = ""; /** *
     * The block data of the proposal.
     * 
* * string block_data = 3 [json_name = "blockData"]; * @return The blockData. */ @java.lang.Override public java.lang.String getBlockData() { java.lang.Object ref = blockData_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); blockData_ = s; return s; } } /** *
     * The block data of the proposal.
     * 
* * string block_data = 3 [json_name = "blockData"]; * @return The bytes for blockData. */ @java.lang.Override public com.google.protobuf.ByteString getBlockDataBytes() { java.lang.Object ref = blockData_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); blockData_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SIGNATURE_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The signature of the proposal, signed by the proposer.
     * 
* * string signature = 4 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The signature of the proposal, signed by the proposer.
     * 
* * string signature = 4 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (height_ != 0) { output.writeUInt32(1, height_); } if (round_ != 0) { output.writeInt32(2, round_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(blockData_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, blockData_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, signature_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, height_); } if (round_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, round_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(blockData_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, blockData_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, signature_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.BlockchainOuterClass.ProposalInfo)) { return super.equals(obj); } pactus.BlockchainOuterClass.ProposalInfo other = (pactus.BlockchainOuterClass.ProposalInfo) obj; if (getHeight() != other.getHeight()) return false; if (getRound() != other.getRound()) return false; if (!getBlockData() .equals(other.getBlockData())) return false; if (!getSignature() .equals(other.getSignature())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (37 * hash) + ROUND_FIELD_NUMBER; hash = (53 * hash) + getRound(); hash = (37 * hash) + BLOCK_DATA_FIELD_NUMBER; hash = (53 * hash) + getBlockData().hashCode(); hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.ProposalInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ProposalInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.BlockchainOuterClass.ProposalInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.BlockchainOuterClass.ProposalInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Message contains information about a proposal.
     * 
* * Protobuf type {@code pactus.ProposalInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ProposalInfo) pactus.BlockchainOuterClass.ProposalInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.BlockchainOuterClass.internal_static_pactus_ProposalInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.BlockchainOuterClass.internal_static_pactus_ProposalInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.BlockchainOuterClass.ProposalInfo.class, pactus.BlockchainOuterClass.ProposalInfo.Builder.class); } // Construct using pactus.BlockchainOuterClass.ProposalInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; height_ = 0; round_ = 0; blockData_ = ""; signature_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.BlockchainOuterClass.internal_static_pactus_ProposalInfo_descriptor; } @java.lang.Override public pactus.BlockchainOuterClass.ProposalInfo getDefaultInstanceForType() { return pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance(); } @java.lang.Override public pactus.BlockchainOuterClass.ProposalInfo build() { pactus.BlockchainOuterClass.ProposalInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.BlockchainOuterClass.ProposalInfo buildPartial() { pactus.BlockchainOuterClass.ProposalInfo result = new pactus.BlockchainOuterClass.ProposalInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.BlockchainOuterClass.ProposalInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.height_ = height_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.round_ = round_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.blockData_ = blockData_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.signature_ = signature_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.BlockchainOuterClass.ProposalInfo) { return mergeFrom((pactus.BlockchainOuterClass.ProposalInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.BlockchainOuterClass.ProposalInfo other) { if (other == pactus.BlockchainOuterClass.ProposalInfo.getDefaultInstance()) return this; if (other.getHeight() != 0) { setHeight(other.getHeight()); } if (other.getRound() != 0) { setRound(other.getRound()); } if (!other.getBlockData().isEmpty()) { blockData_ = other.blockData_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { height_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { round_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { blockData_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int height_ ; /** *
       * The height of the proposal.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * The height of the proposal.
       * 
* * uint32 height = 1 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the proposal.
       * 
* * uint32 height = 1 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000001); height_ = 0; onChanged(); return this; } private int round_ ; /** *
       * The round of the proposal.
       * 
* * int32 round = 2 [json_name = "round"]; * @return The round. */ @java.lang.Override public int getRound() { return round_; } /** *
       * The round of the proposal.
       * 
* * int32 round = 2 [json_name = "round"]; * @param value The round to set. * @return This builder for chaining. */ public Builder setRound(int value) { round_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The round of the proposal.
       * 
* * int32 round = 2 [json_name = "round"]; * @return This builder for chaining. */ public Builder clearRound() { bitField0_ = (bitField0_ & ~0x00000002); round_ = 0; onChanged(); return this; } private java.lang.Object blockData_ = ""; /** *
       * The block data of the proposal.
       * 
* * string block_data = 3 [json_name = "blockData"]; * @return The blockData. */ public java.lang.String getBlockData() { java.lang.Object ref = blockData_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); blockData_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The block data of the proposal.
       * 
* * string block_data = 3 [json_name = "blockData"]; * @return The bytes for blockData. */ public com.google.protobuf.ByteString getBlockDataBytes() { java.lang.Object ref = blockData_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); blockData_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The block data of the proposal.
       * 
* * string block_data = 3 [json_name = "blockData"]; * @param value The blockData to set. * @return This builder for chaining. */ public Builder setBlockData( java.lang.String value) { if (value == null) { throw new NullPointerException(); } blockData_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The block data of the proposal.
       * 
* * string block_data = 3 [json_name = "blockData"]; * @return This builder for chaining. */ public Builder clearBlockData() { blockData_ = getDefaultInstance().getBlockData(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The block data of the proposal.
       * 
* * string block_data = 3 [json_name = "blockData"]; * @param value The bytes for blockData to set. * @return This builder for chaining. */ public Builder setBlockDataBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); blockData_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object signature_ = ""; /** *
       * The signature of the proposal, signed by the proposer.
       * 
* * string signature = 4 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signature of the proposal, signed by the proposer.
       * 
* * string signature = 4 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signature of the proposal, signed by the proposer.
       * 
* * string signature = 4 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The signature of the proposal, signed by the proposer.
       * 
* * string signature = 4 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The signature of the proposal, signed by the proposer.
       * 
* * string signature = 4 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ProposalInfo) } // @@protoc_insertion_point(class_scope:pactus.ProposalInfo) private static final pactus.BlockchainOuterClass.ProposalInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.BlockchainOuterClass.ProposalInfo(); } public static pactus.BlockchainOuterClass.ProposalInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ProposalInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.BlockchainOuterClass.ProposalInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetAccountRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetAccountRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetAccountResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetAccountResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorAddressesRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorAddressesRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorAddressesResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorAddressesResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorByNumberRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorByNumberRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetPublicKeyRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetPublicKeyRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetPublicKeyResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetPublicKeyResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockHashRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockHashRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockHashResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockHashResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockHeightRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockHeightRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockHeightResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockHeightResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockchainInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockchainInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetBlockchainInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetBlockchainInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetCommitteeInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetCommitteeInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetCommitteeInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetCommitteeInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetCommitteeInfoResponse_ProtocolVersionsEntry_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetCommitteeInfoResponse_ProtocolVersionsEntry_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetConsensusInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetConsensusInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetConsensusInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetConsensusInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTxPoolContentRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTxPoolContentRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTxPoolContentResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTxPoolContentResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ValidatorInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ValidatorInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_AccountInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_AccountInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_BlockHeaderInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_BlockHeaderInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CertificateInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CertificateInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_VoteInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_VoteInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ConsensusInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ConsensusInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ProposalInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ProposalInfo_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\020blockchain.proto\022\006pactus\032\021transaction." + "proto\"-\n\021GetAccountRequest\022\030\n\007address\030\001 " + "\001(\tR\007address\"C\n\022GetAccountResponse\022-\n\007ac" + "count\030\001 \001(\0132\023.pactus.AccountInfoR\007accoun" + "t\"\036\n\034GetValidatorAddressesRequest\"=\n\035Get" + "ValidatorAddressesResponse\022\034\n\taddresses\030" + "\001 \003(\tR\taddresses\"/\n\023GetValidatorRequest\022" + "\030\n\007address\030\001 \001(\tR\007address\"5\n\033GetValidato" + "rByNumberRequest\022\026\n\006number\030\001 \001(\005R\006number" + "\"K\n\024GetValidatorResponse\0223\n\tvalidator\030\001 " + "\001(\0132\025.pactus.ValidatorInfoR\tvalidator\"/\n" + "\023GetPublicKeyRequest\022\030\n\007address\030\001 \001(\tR\007a" + "ddress\"5\n\024GetPublicKeyResponse\022\035\n\npublic" + "_key\030\001 \001(\tR\tpublicKey\"_\n\017GetBlockRequest" + "\022\026\n\006height\030\001 \001(\rR\006height\0224\n\tverbosity\030\002 " + "\001(\0162\026.pactus.BlockVerbosityR\tverbosity\"\203" + "\002\n\020GetBlockResponse\022\026\n\006height\030\001 \001(\rR\006hei" + "ght\022\022\n\004hash\030\002 \001(\tR\004hash\022\022\n\004data\030\003 \001(\tR\004d" + "ata\022\035\n\nblock_time\030\004 \001(\rR\tblockTime\022/\n\006he" + "ader\030\005 \001(\0132\027.pactus.BlockHeaderInfoR\006hea" + "der\0224\n\tprev_cert\030\006 \001(\0132\027.pactus.Certific" + "ateInfoR\010prevCert\022)\n\003txs\030\007 \003(\0132\027.pactus." + "TransactionInfoR\003txs\"-\n\023GetBlockHashRequ" + "est\022\026\n\006height\030\001 \001(\rR\006height\"*\n\024GetBlockH" + "ashResponse\022\022\n\004hash\030\001 \001(\tR\004hash\"+\n\025GetBl" + "ockHeightRequest\022\022\n\004hash\030\001 \001(\tR\004hash\"0\n\026" + "GetBlockHeightResponse\022\026\n\006height\030\001 \001(\rR\006" + "height\"\032\n\030GetBlockchainInfoRequest\"\223\004\n\031G" + "etBlockchainInfoResponse\022*\n\021last_block_h" + "eight\030\001 \001(\rR\017lastBlockHeight\022&\n\017last_blo" + "ck_hash\030\002 \001(\tR\rlastBlockHash\022&\n\017last_blo" + "ck_time\030\n \001(\003R\rlastBlockTime\022%\n\016total_ac" + "counts\030\003 \001(\005R\rtotalAccounts\022)\n\020total_val" + "idators\030\004 \001(\005R\017totalValidators\022+\n\021active" + "_validators\030\014 \001(\005R\020activeValidators\022\037\n\013t" + "otal_power\030\005 \001(\003R\ntotalPower\022\'\n\017committe" + "e_power\030\006 \001(\003R\016committeePower\022\033\n\tis_prun" + "ed\030\010 \001(\010R\010isPruned\022%\n\016pruning_height\030\t \001" + "(\rR\rpruningHeight\022!\n\014in_committee\030\r \001(\010R" + "\013inCommittee\022%\n\016committee_size\030\016 \001(\005R\rco" + "mmitteeSize\022#\n\raverage_score\030\017 \001(\001R\014aver" + "ageScore\"\031\n\027GetCommitteeInfoRequest\"\354\002\n\030" + "GetCommitteeInfoResponse\022%\n\016committee_si" + "ze\030\001 \001(\005R\rcommitteeSize\022\'\n\017committee_pow" + "er\030\002 \001(\003R\016committeePower\022\037\n\013total_power\030" + "\003 \001(\003R\ntotalPower\0225\n\nvalidators\030\004 \003(\0132\025." + "pactus.ValidatorInfoR\nvalidators\022c\n\021prot" + "ocol_versions\030\005 \003(\01326.pactus.GetCommitte" + "eInfoResponse.ProtocolVersionsEntryR\020pro" + "tocolVersions\032C\n\025ProtocolVersionsEntry\022\020" + "\n\003key\030\001 \001(\005R\003key\022\024\n\005value\030\002 \001(\001R\005value:\002" + "8\001\"\031\n\027GetConsensusInfoRequest\"\201\001\n\030GetCon" + "sensusInfoResponse\0220\n\010proposal\030\001 \001(\0132\024.p" + "actus.ProposalInfoR\010proposal\0223\n\tinstance" + "s\030\002 \003(\0132\025.pactus.ConsensusInfoR\tinstance" + "s\"Q\n\027GetTxPoolContentRequest\0226\n\014payload_" + "type\030\001 \001(\0162\023.pactus.PayloadTypeR\013payload" + "Type\"E\n\030GetTxPoolContentResponse\022)\n\003txs\030" + "\001 \003(\0132\027.pactus.TransactionInfoR\003txs\"\241\004\n\r" + "ValidatorInfo\022\022\n\004hash\030\001 \001(\tR\004hash\022\022\n\004dat" + "a\030\002 \001(\tR\004data\022\035\n\npublic_key\030\003 \001(\tR\tpubli" + "cKey\022\026\n\006number\030\004 \001(\005R\006number\022\024\n\005stake\030\005 " + "\001(\003R\005stake\022.\n\023last_bonding_height\030\006 \001(\rR" + "\021lastBondingHeight\0222\n\025last_sortition_hei" + "ght\030\007 \001(\rR\023lastSortitionHeight\022)\n\020unbond" + "ing_height\030\010 \001(\rR\017unbondingHeight\022\030\n\007add" + "ress\030\t \001(\tR\007address\022-\n\022availability_scor" + "e\030\n \001(\001R\021availabilityScore\022)\n\020protocol_v" + "ersion\030\013 \001(\005R\017protocolVersion\022!\n\014is_dele" + "gated\030\014 \001(\010R\013isDelegated\022%\n\016delegate_own" + "er\030\r \001(\tR\rdelegateOwner\022%\n\016delegate_shar" + "e\030\016 \001(\003R\rdelegateShare\022\'\n\017delegate_expir" + "y\030\017 \001(\rR\016delegateExpiry\"\201\001\n\013AccountInfo\022" + "\022\n\004hash\030\001 \001(\tR\004hash\022\022\n\004data\030\002 \001(\tR\004data\022" + "\026\n\006number\030\003 \001(\005R\006number\022\030\n\007balance\030\004 \001(\003" + "R\007balance\022\030\n\007address\030\005 \001(\tR\007address\"\304\001\n\017" + "BlockHeaderInfo\022\030\n\007version\030\001 \001(\005R\007versio" + "n\022&\n\017prev_block_hash\030\002 \001(\tR\rprevBlockHas" + "h\022\035\n\nstate_root\030\003 \001(\tR\tstateRoot\022%\n\016sort" + "ition_seed\030\004 \001(\tR\rsortitionSeed\022)\n\020propo" + "ser_address\030\005 \001(\tR\017proposerAddress\"\227\001\n\017C" + "ertificateInfo\022\022\n\004hash\030\001 \001(\tR\004hash\022\024\n\005ro" + "und\030\002 \001(\005R\005round\022\036\n\ncommitters\030\003 \003(\005R\nco" + "mmitters\022\034\n\tabsentees\030\004 \003(\005R\tabsentees\022\034" + "\n\tsignature\030\005 \001(\tR\tsignature\"\261\001\n\010VoteInf" + "o\022$\n\004type\030\001 \001(\0162\020.pactus.VoteTypeR\004type\022" + "\024\n\005voter\030\002 \001(\tR\005voter\022\035\n\nblock_hash\030\003 \001(" + "\tR\tblockHash\022\024\n\005round\030\004 \001(\005R\005round\022\031\n\010cp" + "_round\030\005 \001(\005R\007cpRound\022\031\n\010cp_value\030\006 \001(\005R" + "\007cpValue\"\227\001\n\rConsensusInfo\022\030\n\007address\030\001 " + "\001(\tR\007address\022\026\n\006active\030\002 \001(\010R\006active\022\026\n\006" + "height\030\003 \001(\rR\006height\022\024\n\005round\030\004 \001(\005R\005rou" + "nd\022&\n\005votes\030\005 \003(\0132\020.pactus.VoteInfoR\005vot" + "es\"y\n\014ProposalInfo\022\026\n\006height\030\001 \001(\rR\006heig" + "ht\022\024\n\005round\030\002 \001(\005R\005round\022\035\n\nblock_data\030\003" + " \001(\tR\tblockData\022\034\n\tsignature\030\004 \001(\tR\tsign" + "ature*f\n\016BlockVerbosity\022\030\n\024BLOCK_VERBOSI" + "TY_DATA\020\000\022\030\n\024BLOCK_VERBOSITY_INFO\020\001\022 \n\034B" + "LOCK_VERBOSITY_TRANSACTIONS\020\002*\246\001\n\010VoteTy" + "pe\022\031\n\025VOTE_TYPE_UNSPECIFIED\020\000\022\025\n\021VOTE_TY" + "PE_PREPARE\020\001\022\027\n\023VOTE_TYPE_PRECOMMIT\020\002\022\031\n" + "\025VOTE_TYPE_CP_PRE_VOTE\020\003\022\032\n\026VOTE_TYPE_CP" + "_MAIN_VOTE\020\004\022\030\n\024VOTE_TYPE_CP_DECIDED\020\0052\342" + "\007\n\nBlockchain\022=\n\010GetBlock\022\027.pactus.GetBl" + "ockRequest\032\030.pactus.GetBlockResponse\022I\n\014" + "GetBlockHash\022\033.pactus.GetBlockHashReques" + "t\032\034.pactus.GetBlockHashResponse\022O\n\016GetBl" + "ockHeight\022\035.pactus.GetBlockHeightRequest" + "\032\036.pactus.GetBlockHeightResponse\022X\n\021GetB" + "lockchainInfo\022 .pactus.GetBlockchainInfo" + "Request\032!.pactus.GetBlockchainInfoRespon" + "se\022U\n\020GetCommitteeInfo\022\037.pactus.GetCommi" + "tteeInfoRequest\032 .pactus.GetCommitteeInf" + "oResponse\022U\n\020GetConsensusInfo\022\037.pactus.G" + "etConsensusInfoRequest\032 .pactus.GetConse" + "nsusInfoResponse\022C\n\nGetAccount\022\031.pactus." + "GetAccountRequest\032\032.pactus.GetAccountRes" + "ponse\022I\n\014GetValidator\022\033.pactus.GetValida" + "torRequest\032\034.pactus.GetValidatorResponse" + "\022Y\n\024GetValidatorByNumber\022#.pactus.GetVal" + "idatorByNumberRequest\032\034.pactus.GetValida" + "torResponse\022d\n\025GetValidatorAddresses\022$.p" + "actus.GetValidatorAddressesRequest\032%.pac" + "tus.GetValidatorAddressesResponse\022I\n\014Get" + "PublicKey\022\033.pactus.GetPublicKeyRequest\032\034" + ".pactus.GetPublicKeyResponse\022U\n\020GetTxPoo" + "lContent\022\037.pactus.GetTxPoolContentReques" + "t\032 .pactus.GetTxPoolContentResponseB:\n\006p" + "actusZ0github.com/pactus-project/pactus/" + "www/grpc/pactusb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { pactus.TransactionOuterClass.getDescriptor(), }); internal_static_pactus_GetAccountRequest_descriptor = getDescriptor().getMessageType(0); internal_static_pactus_GetAccountRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetAccountRequest_descriptor, new java.lang.String[] { "Address", }); internal_static_pactus_GetAccountResponse_descriptor = getDescriptor().getMessageType(1); internal_static_pactus_GetAccountResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetAccountResponse_descriptor, new java.lang.String[] { "Account", }); internal_static_pactus_GetValidatorAddressesRequest_descriptor = getDescriptor().getMessageType(2); internal_static_pactus_GetValidatorAddressesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorAddressesRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_GetValidatorAddressesResponse_descriptor = getDescriptor().getMessageType(3); internal_static_pactus_GetValidatorAddressesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorAddressesResponse_descriptor, new java.lang.String[] { "Addresses", }); internal_static_pactus_GetValidatorRequest_descriptor = getDescriptor().getMessageType(4); internal_static_pactus_GetValidatorRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorRequest_descriptor, new java.lang.String[] { "Address", }); internal_static_pactus_GetValidatorByNumberRequest_descriptor = getDescriptor().getMessageType(5); internal_static_pactus_GetValidatorByNumberRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorByNumberRequest_descriptor, new java.lang.String[] { "Number", }); internal_static_pactus_GetValidatorResponse_descriptor = getDescriptor().getMessageType(6); internal_static_pactus_GetValidatorResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorResponse_descriptor, new java.lang.String[] { "Validator", }); internal_static_pactus_GetPublicKeyRequest_descriptor = getDescriptor().getMessageType(7); internal_static_pactus_GetPublicKeyRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetPublicKeyRequest_descriptor, new java.lang.String[] { "Address", }); internal_static_pactus_GetPublicKeyResponse_descriptor = getDescriptor().getMessageType(8); internal_static_pactus_GetPublicKeyResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetPublicKeyResponse_descriptor, new java.lang.String[] { "PublicKey", }); internal_static_pactus_GetBlockRequest_descriptor = getDescriptor().getMessageType(9); internal_static_pactus_GetBlockRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockRequest_descriptor, new java.lang.String[] { "Height", "Verbosity", }); internal_static_pactus_GetBlockResponse_descriptor = getDescriptor().getMessageType(10); internal_static_pactus_GetBlockResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockResponse_descriptor, new java.lang.String[] { "Height", "Hash", "Data", "BlockTime", "Header", "PrevCert", "Txs", }); internal_static_pactus_GetBlockHashRequest_descriptor = getDescriptor().getMessageType(11); internal_static_pactus_GetBlockHashRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockHashRequest_descriptor, new java.lang.String[] { "Height", }); internal_static_pactus_GetBlockHashResponse_descriptor = getDescriptor().getMessageType(12); internal_static_pactus_GetBlockHashResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockHashResponse_descriptor, new java.lang.String[] { "Hash", }); internal_static_pactus_GetBlockHeightRequest_descriptor = getDescriptor().getMessageType(13); internal_static_pactus_GetBlockHeightRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockHeightRequest_descriptor, new java.lang.String[] { "Hash", }); internal_static_pactus_GetBlockHeightResponse_descriptor = getDescriptor().getMessageType(14); internal_static_pactus_GetBlockHeightResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockHeightResponse_descriptor, new java.lang.String[] { "Height", }); internal_static_pactus_GetBlockchainInfoRequest_descriptor = getDescriptor().getMessageType(15); internal_static_pactus_GetBlockchainInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockchainInfoRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_GetBlockchainInfoResponse_descriptor = getDescriptor().getMessageType(16); internal_static_pactus_GetBlockchainInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetBlockchainInfoResponse_descriptor, new java.lang.String[] { "LastBlockHeight", "LastBlockHash", "LastBlockTime", "TotalAccounts", "TotalValidators", "ActiveValidators", "TotalPower", "CommitteePower", "IsPruned", "PruningHeight", "InCommittee", "CommitteeSize", "AverageScore", }); internal_static_pactus_GetCommitteeInfoRequest_descriptor = getDescriptor().getMessageType(17); internal_static_pactus_GetCommitteeInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetCommitteeInfoRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_GetCommitteeInfoResponse_descriptor = getDescriptor().getMessageType(18); internal_static_pactus_GetCommitteeInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetCommitteeInfoResponse_descriptor, new java.lang.String[] { "CommitteeSize", "CommitteePower", "TotalPower", "Validators", "ProtocolVersions", }); internal_static_pactus_GetCommitteeInfoResponse_ProtocolVersionsEntry_descriptor = internal_static_pactus_GetCommitteeInfoResponse_descriptor.getNestedType(0); internal_static_pactus_GetCommitteeInfoResponse_ProtocolVersionsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetCommitteeInfoResponse_ProtocolVersionsEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_pactus_GetConsensusInfoRequest_descriptor = getDescriptor().getMessageType(19); internal_static_pactus_GetConsensusInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetConsensusInfoRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_GetConsensusInfoResponse_descriptor = getDescriptor().getMessageType(20); internal_static_pactus_GetConsensusInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetConsensusInfoResponse_descriptor, new java.lang.String[] { "Proposal", "Instances", }); internal_static_pactus_GetTxPoolContentRequest_descriptor = getDescriptor().getMessageType(21); internal_static_pactus_GetTxPoolContentRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTxPoolContentRequest_descriptor, new java.lang.String[] { "PayloadType", }); internal_static_pactus_GetTxPoolContentResponse_descriptor = getDescriptor().getMessageType(22); internal_static_pactus_GetTxPoolContentResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTxPoolContentResponse_descriptor, new java.lang.String[] { "Txs", }); internal_static_pactus_ValidatorInfo_descriptor = getDescriptor().getMessageType(23); internal_static_pactus_ValidatorInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ValidatorInfo_descriptor, new java.lang.String[] { "Hash", "Data", "PublicKey", "Number", "Stake", "LastBondingHeight", "LastSortitionHeight", "UnbondingHeight", "Address", "AvailabilityScore", "ProtocolVersion", "IsDelegated", "DelegateOwner", "DelegateShare", "DelegateExpiry", }); internal_static_pactus_AccountInfo_descriptor = getDescriptor().getMessageType(24); internal_static_pactus_AccountInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_AccountInfo_descriptor, new java.lang.String[] { "Hash", "Data", "Number", "Balance", "Address", }); internal_static_pactus_BlockHeaderInfo_descriptor = getDescriptor().getMessageType(25); internal_static_pactus_BlockHeaderInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_BlockHeaderInfo_descriptor, new java.lang.String[] { "Version", "PrevBlockHash", "StateRoot", "SortitionSeed", "ProposerAddress", }); internal_static_pactus_CertificateInfo_descriptor = getDescriptor().getMessageType(26); internal_static_pactus_CertificateInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CertificateInfo_descriptor, new java.lang.String[] { "Hash", "Round", "Committers", "Absentees", "Signature", }); internal_static_pactus_VoteInfo_descriptor = getDescriptor().getMessageType(27); internal_static_pactus_VoteInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_VoteInfo_descriptor, new java.lang.String[] { "Type", "Voter", "BlockHash", "Round", "CpRound", "CpValue", }); internal_static_pactus_ConsensusInfo_descriptor = getDescriptor().getMessageType(28); internal_static_pactus_ConsensusInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ConsensusInfo_descriptor, new java.lang.String[] { "Address", "Active", "Height", "Round", "Votes", }); internal_static_pactus_ProposalInfo_descriptor = getDescriptor().getMessageType(29); internal_static_pactus_ProposalInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ProposalInfo_descriptor, new java.lang.String[] { "Height", "Round", "BlockData", "Signature", }); descriptor.resolveAllFeaturesImmutable(); pactus.TransactionOuterClass.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) } ================================================ FILE: www/grpc/gen/java/pactus/NetworkGrpc.java ================================================ package pactus; import static io.grpc.MethodDescriptor.generateFullMethodName; /** *
 * Network service provides RPCs for retrieving information about the network.
 * 
*/ @io.grpc.stub.annotations.GrpcGenerated public final class NetworkGrpc { private NetworkGrpc() {} public static final java.lang.String SERVICE_NAME = "pactus.Network"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor getGetNetworkInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetNetworkInfo", requestType = pactus.NetworkOuterClass.GetNetworkInfoRequest.class, responseType = pactus.NetworkOuterClass.GetNetworkInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetNetworkInfoMethod() { io.grpc.MethodDescriptor getGetNetworkInfoMethod; if ((getGetNetworkInfoMethod = NetworkGrpc.getGetNetworkInfoMethod) == null) { synchronized (NetworkGrpc.class) { if ((getGetNetworkInfoMethod = NetworkGrpc.getGetNetworkInfoMethod) == null) { NetworkGrpc.getGetNetworkInfoMethod = getGetNetworkInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetNetworkInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.GetNetworkInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.GetNetworkInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new NetworkMethodDescriptorSupplier("GetNetworkInfo")) .build(); } } } return getGetNetworkInfoMethod; } private static volatile io.grpc.MethodDescriptor getListPeersMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListPeers", requestType = pactus.NetworkOuterClass.ListPeersRequest.class, responseType = pactus.NetworkOuterClass.ListPeersResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getListPeersMethod() { io.grpc.MethodDescriptor getListPeersMethod; if ((getListPeersMethod = NetworkGrpc.getListPeersMethod) == null) { synchronized (NetworkGrpc.class) { if ((getListPeersMethod = NetworkGrpc.getListPeersMethod) == null) { NetworkGrpc.getListPeersMethod = getListPeersMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListPeers")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.ListPeersRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.ListPeersResponse.getDefaultInstance())) .setSchemaDescriptor(new NetworkMethodDescriptorSupplier("ListPeers")) .build(); } } } return getListPeersMethod; } private static volatile io.grpc.MethodDescriptor getGetNodeInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetNodeInfo", requestType = pactus.NetworkOuterClass.GetNodeInfoRequest.class, responseType = pactus.NetworkOuterClass.GetNodeInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetNodeInfoMethod() { io.grpc.MethodDescriptor getGetNodeInfoMethod; if ((getGetNodeInfoMethod = NetworkGrpc.getGetNodeInfoMethod) == null) { synchronized (NetworkGrpc.class) { if ((getGetNodeInfoMethod = NetworkGrpc.getGetNodeInfoMethod) == null) { NetworkGrpc.getGetNodeInfoMethod = getGetNodeInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetNodeInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.GetNodeInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.GetNodeInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new NetworkMethodDescriptorSupplier("GetNodeInfo")) .build(); } } } return getGetNodeInfoMethod; } private static volatile io.grpc.MethodDescriptor getPingMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "Ping", requestType = pactus.NetworkOuterClass.PingRequest.class, responseType = pactus.NetworkOuterClass.PingResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getPingMethod() { io.grpc.MethodDescriptor getPingMethod; if ((getPingMethod = NetworkGrpc.getPingMethod) == null) { synchronized (NetworkGrpc.class) { if ((getPingMethod = NetworkGrpc.getPingMethod) == null) { NetworkGrpc.getPingMethod = getPingMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Ping")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.PingRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.NetworkOuterClass.PingResponse.getDefaultInstance())) .setSchemaDescriptor(new NetworkMethodDescriptorSupplier("Ping")) .build(); } } } return getPingMethod; } /** * Creates a new async stub that supports all call types for the service */ public static NetworkStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public NetworkStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkStub(channel, callOptions); } }; return NetworkStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static NetworkBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public NetworkBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkBlockingV2Stub(channel, callOptions); } }; return NetworkBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static NetworkBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public NetworkBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkBlockingStub(channel, callOptions); } }; return NetworkBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static NetworkFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public NetworkFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkFutureStub(channel, callOptions); } }; return NetworkFutureStub.newStub(factory, channel); } /** *
   * Network service provides RPCs for retrieving information about the network.
   * 
*/ public interface AsyncService { /** *
     * GetNetworkInfo retrieves information about the overall network.
     * 
*/ default void getNetworkInfo(pactus.NetworkOuterClass.GetNetworkInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetNetworkInfoMethod(), responseObserver); } /** *
     * ListPeers lists all peers in the network.
     * 
*/ default void listPeers(pactus.NetworkOuterClass.ListPeersRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getListPeersMethod(), responseObserver); } /** *
     * GetNodeInfo retrieves information about a specific node in the network.
     * 
*/ default void getNodeInfo(pactus.NetworkOuterClass.GetNodeInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetNodeInfoMethod(), responseObserver); } /** *
     * Ping provides a simple connectivity test and latency measurement.
     * 
*/ default void ping(pactus.NetworkOuterClass.PingRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getPingMethod(), responseObserver); } } /** * Base class for the server implementation of the service Network. *
   * Network service provides RPCs for retrieving information about the network.
   * 
*/ public static abstract class NetworkImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return NetworkGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service Network. *
   * Network service provides RPCs for retrieving information about the network.
   * 
*/ public static final class NetworkStub extends io.grpc.stub.AbstractAsyncStub { private NetworkStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkStub(channel, callOptions); } /** *
     * GetNetworkInfo retrieves information about the overall network.
     * 
*/ public void getNetworkInfo(pactus.NetworkOuterClass.GetNetworkInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetNetworkInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * ListPeers lists all peers in the network.
     * 
*/ public void listPeers(pactus.NetworkOuterClass.ListPeersRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListPeersMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetNodeInfo retrieves information about a specific node in the network.
     * 
*/ public void getNodeInfo(pactus.NetworkOuterClass.GetNodeInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetNodeInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * Ping provides a simple connectivity test and latency measurement.
     * 
*/ public void ping(pactus.NetworkOuterClass.PingRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getPingMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Network. *
   * Network service provides RPCs for retrieving information about the network.
   * 
*/ public static final class NetworkBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub { private NetworkBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkBlockingV2Stub(channel, callOptions); } /** *
     * GetNetworkInfo retrieves information about the overall network.
     * 
*/ public pactus.NetworkOuterClass.GetNetworkInfoResponse getNetworkInfo(pactus.NetworkOuterClass.GetNetworkInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetNetworkInfoMethod(), getCallOptions(), request); } /** *
     * ListPeers lists all peers in the network.
     * 
*/ public pactus.NetworkOuterClass.ListPeersResponse listPeers(pactus.NetworkOuterClass.ListPeersRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getListPeersMethod(), getCallOptions(), request); } /** *
     * GetNodeInfo retrieves information about a specific node in the network.
     * 
*/ public pactus.NetworkOuterClass.GetNodeInfoResponse getNodeInfo(pactus.NetworkOuterClass.GetNodeInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetNodeInfoMethod(), getCallOptions(), request); } /** *
     * Ping provides a simple connectivity test and latency measurement.
     * 
*/ public pactus.NetworkOuterClass.PingResponse ping(pactus.NetworkOuterClass.PingRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getPingMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Network. *
   * Network service provides RPCs for retrieving information about the network.
   * 
*/ public static final class NetworkBlockingStub extends io.grpc.stub.AbstractBlockingStub { private NetworkBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkBlockingStub(channel, callOptions); } /** *
     * GetNetworkInfo retrieves information about the overall network.
     * 
*/ public pactus.NetworkOuterClass.GetNetworkInfoResponse getNetworkInfo(pactus.NetworkOuterClass.GetNetworkInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetNetworkInfoMethod(), getCallOptions(), request); } /** *
     * ListPeers lists all peers in the network.
     * 
*/ public pactus.NetworkOuterClass.ListPeersResponse listPeers(pactus.NetworkOuterClass.ListPeersRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListPeersMethod(), getCallOptions(), request); } /** *
     * GetNodeInfo retrieves information about a specific node in the network.
     * 
*/ public pactus.NetworkOuterClass.GetNodeInfoResponse getNodeInfo(pactus.NetworkOuterClass.GetNodeInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetNodeInfoMethod(), getCallOptions(), request); } /** *
     * Ping provides a simple connectivity test and latency measurement.
     * 
*/ public pactus.NetworkOuterClass.PingResponse ping(pactus.NetworkOuterClass.PingRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getPingMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service Network. *
   * Network service provides RPCs for retrieving information about the network.
   * 
*/ public static final class NetworkFutureStub extends io.grpc.stub.AbstractFutureStub { private NetworkFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkFutureStub(channel, callOptions); } /** *
     * GetNetworkInfo retrieves information about the overall network.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getNetworkInfo( pactus.NetworkOuterClass.GetNetworkInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetNetworkInfoMethod(), getCallOptions()), request); } /** *
     * ListPeers lists all peers in the network.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture listPeers( pactus.NetworkOuterClass.ListPeersRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListPeersMethod(), getCallOptions()), request); } /** *
     * GetNodeInfo retrieves information about a specific node in the network.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getNodeInfo( pactus.NetworkOuterClass.GetNodeInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetNodeInfoMethod(), getCallOptions()), request); } /** *
     * Ping provides a simple connectivity test and latency measurement.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture ping( pactus.NetworkOuterClass.PingRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getPingMethod(), getCallOptions()), request); } } private static final int METHODID_GET_NETWORK_INFO = 0; private static final int METHODID_LIST_PEERS = 1; private static final int METHODID_GET_NODE_INFO = 2; private static final int METHODID_PING = 3; private static final class MethodHandlers implements io.grpc.stub.ServerCalls.UnaryMethod, io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_GET_NETWORK_INFO: serviceImpl.getNetworkInfo((pactus.NetworkOuterClass.GetNetworkInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_LIST_PEERS: serviceImpl.listPeers((pactus.NetworkOuterClass.ListPeersRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_NODE_INFO: serviceImpl.getNodeInfo((pactus.NetworkOuterClass.GetNodeInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_PING: serviceImpl.ping((pactus.NetworkOuterClass.PingRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver invoke( io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetNetworkInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.NetworkOuterClass.GetNetworkInfoRequest, pactus.NetworkOuterClass.GetNetworkInfoResponse>( service, METHODID_GET_NETWORK_INFO))) .addMethod( getListPeersMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.NetworkOuterClass.ListPeersRequest, pactus.NetworkOuterClass.ListPeersResponse>( service, METHODID_LIST_PEERS))) .addMethod( getGetNodeInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.NetworkOuterClass.GetNodeInfoRequest, pactus.NetworkOuterClass.GetNodeInfoResponse>( service, METHODID_GET_NODE_INFO))) .addMethod( getPingMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.NetworkOuterClass.PingRequest, pactus.NetworkOuterClass.PingResponse>( service, METHODID_PING))) .build(); } private static abstract class NetworkBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { NetworkBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return pactus.NetworkOuterClass.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Network"); } } private static final class NetworkFileDescriptorSupplier extends NetworkBaseDescriptorSupplier { NetworkFileDescriptorSupplier() {} } private static final class NetworkMethodDescriptorSupplier extends NetworkBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; NetworkMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (NetworkGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new NetworkFileDescriptorSupplier()) .addMethod(getGetNetworkInfoMethod()) .addMethod(getListPeersMethod()) .addMethod(getGetNodeInfoMethod()) .addMethod(getPingMethod()) .build(); } } } return result; } } ================================================ FILE: www/grpc/gen/java/pactus/NetworkOuterClass.java ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: network.proto // Protobuf Java Version: 4.33.2 package pactus; @com.google.protobuf.Generated public final class NetworkOuterClass extends com.google.protobuf.GeneratedFile { private NetworkOuterClass() {} static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "NetworkOuterClass"); } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** *
   * Direction represents the connection direction between peers.
   * 
* * Protobuf enum {@code pactus.Direction} */ public enum Direction implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Unknown direction (default value).
     * 
* * DIRECTION_UNKNOWN = 0; */ DIRECTION_UNKNOWN(0), /** *
     * Inbound connection - peer connected to us.
     * 
* * DIRECTION_INBOUND = 1; */ DIRECTION_INBOUND(1), /** *
     * Outbound connection - we connected to peer.
     * 
* * DIRECTION_OUTBOUND = 2; */ DIRECTION_OUTBOUND(2), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "Direction"); } /** *
     * Unknown direction (default value).
     * 
* * DIRECTION_UNKNOWN = 0; */ public static final int DIRECTION_UNKNOWN_VALUE = 0; /** *
     * Inbound connection - peer connected to us.
     * 
* * DIRECTION_INBOUND = 1; */ public static final int DIRECTION_INBOUND_VALUE = 1; /** *
     * Outbound connection - we connected to peer.
     * 
* * DIRECTION_OUTBOUND = 2; */ public static final int DIRECTION_OUTBOUND_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Direction valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static Direction forNumber(int value) { switch (value) { case 0: return DIRECTION_UNKNOWN; case 1: return DIRECTION_INBOUND; case 2: return DIRECTION_OUTBOUND; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Direction> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public Direction findValueByNumber(int number) { return Direction.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.NetworkOuterClass.getDescriptor().getEnumTypes().get(0); } private static final Direction[] VALUES = values(); public static Direction valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private Direction(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.Direction) } public interface GetNetworkInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetNetworkInfoRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for retrieving overall network information.
   * 
* * Protobuf type {@code pactus.GetNetworkInfoRequest} */ public static final class GetNetworkInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetNetworkInfoRequest) GetNetworkInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetNetworkInfoRequest"); } // Use GetNetworkInfoRequest.newBuilder() to construct. private GetNetworkInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetNetworkInfoRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNetworkInfoRequest.class, pactus.NetworkOuterClass.GetNetworkInfoRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.GetNetworkInfoRequest)) { return super.equals(obj); } pactus.NetworkOuterClass.GetNetworkInfoRequest other = (pactus.NetworkOuterClass.GetNetworkInfoRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.GetNetworkInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving overall network information.
     * 
* * Protobuf type {@code pactus.GetNetworkInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetNetworkInfoRequest) pactus.NetworkOuterClass.GetNetworkInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNetworkInfoRequest.class, pactus.NetworkOuterClass.GetNetworkInfoRequest.Builder.class); } // Construct using pactus.NetworkOuterClass.GetNetworkInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoRequest_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoRequest getDefaultInstanceForType() { return pactus.NetworkOuterClass.GetNetworkInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoRequest build() { pactus.NetworkOuterClass.GetNetworkInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoRequest buildPartial() { pactus.NetworkOuterClass.GetNetworkInfoRequest result = new pactus.NetworkOuterClass.GetNetworkInfoRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.GetNetworkInfoRequest) { return mergeFrom((pactus.NetworkOuterClass.GetNetworkInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.GetNetworkInfoRequest other) { if (other == pactus.NetworkOuterClass.GetNetworkInfoRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.GetNetworkInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetNetworkInfoRequest) private static final pactus.NetworkOuterClass.GetNetworkInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.GetNetworkInfoRequest(); } public static pactus.NetworkOuterClass.GetNetworkInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetNetworkInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetNetworkInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetNetworkInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Name of the P2P network.
     * 
* * string network_name = 1 [json_name = "networkName"]; * @return The networkName. */ java.lang.String getNetworkName(); /** *
     * Name of the P2P network.
     * 
* * string network_name = 1 [json_name = "networkName"]; * @return The bytes for networkName. */ com.google.protobuf.ByteString getNetworkNameBytes(); /** *
     * Number of connected peers.
     * 
* * uint32 connected_peers_count = 2 [json_name = "connectedPeersCount"]; * @return The connectedPeersCount. */ int getConnectedPeersCount(); /** *
     * Metrics related to node activity.
     * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; * @return Whether the metricInfo field is set. */ boolean hasMetricInfo(); /** *
     * Metrics related to node activity.
     * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; * @return The metricInfo. */ pactus.NetworkOuterClass.MetricInfo getMetricInfo(); /** *
     * Metrics related to node activity.
     * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ pactus.NetworkOuterClass.MetricInfoOrBuilder getMetricInfoOrBuilder(); } /** *
   * Response message contains information about the overall network.
   * 
* * Protobuf type {@code pactus.GetNetworkInfoResponse} */ public static final class GetNetworkInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetNetworkInfoResponse) GetNetworkInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetNetworkInfoResponse"); } // Use GetNetworkInfoResponse.newBuilder() to construct. private GetNetworkInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetNetworkInfoResponse() { networkName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNetworkInfoResponse.class, pactus.NetworkOuterClass.GetNetworkInfoResponse.Builder.class); } private int bitField0_; public static final int NETWORK_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object networkName_ = ""; /** *
     * Name of the P2P network.
     * 
* * string network_name = 1 [json_name = "networkName"]; * @return The networkName. */ @java.lang.Override public java.lang.String getNetworkName() { java.lang.Object ref = networkName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); networkName_ = s; return s; } } /** *
     * Name of the P2P network.
     * 
* * string network_name = 1 [json_name = "networkName"]; * @return The bytes for networkName. */ @java.lang.Override public com.google.protobuf.ByteString getNetworkNameBytes() { java.lang.Object ref = networkName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); networkName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONNECTED_PEERS_COUNT_FIELD_NUMBER = 2; private int connectedPeersCount_ = 0; /** *
     * Number of connected peers.
     * 
* * uint32 connected_peers_count = 2 [json_name = "connectedPeersCount"]; * @return The connectedPeersCount. */ @java.lang.Override public int getConnectedPeersCount() { return connectedPeersCount_; } public static final int METRIC_INFO_FIELD_NUMBER = 4; private pactus.NetworkOuterClass.MetricInfo metricInfo_; /** *
     * Metrics related to node activity.
     * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; * @return Whether the metricInfo field is set. */ @java.lang.Override public boolean hasMetricInfo() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Metrics related to node activity.
     * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; * @return The metricInfo. */ @java.lang.Override public pactus.NetworkOuterClass.MetricInfo getMetricInfo() { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } /** *
     * Metrics related to node activity.
     * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ @java.lang.Override public pactus.NetworkOuterClass.MetricInfoOrBuilder getMetricInfoOrBuilder() { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(networkName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, networkName_); } if (connectedPeersCount_ != 0) { output.writeUInt32(2, connectedPeersCount_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(4, getMetricInfo()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(networkName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, networkName_); } if (connectedPeersCount_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(2, connectedPeersCount_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, getMetricInfo()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.GetNetworkInfoResponse)) { return super.equals(obj); } pactus.NetworkOuterClass.GetNetworkInfoResponse other = (pactus.NetworkOuterClass.GetNetworkInfoResponse) obj; if (!getNetworkName() .equals(other.getNetworkName())) return false; if (getConnectedPeersCount() != other.getConnectedPeersCount()) return false; if (hasMetricInfo() != other.hasMetricInfo()) return false; if (hasMetricInfo()) { if (!getMetricInfo() .equals(other.getMetricInfo())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NETWORK_NAME_FIELD_NUMBER; hash = (53 * hash) + getNetworkName().hashCode(); hash = (37 * hash) + CONNECTED_PEERS_COUNT_FIELD_NUMBER; hash = (53 * hash) + getConnectedPeersCount(); if (hasMetricInfo()) { hash = (37 * hash) + METRIC_INFO_FIELD_NUMBER; hash = (53 * hash) + getMetricInfo().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.GetNetworkInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains information about the overall network.
     * 
* * Protobuf type {@code pactus.GetNetworkInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetNetworkInfoResponse) pactus.NetworkOuterClass.GetNetworkInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNetworkInfoResponse.class, pactus.NetworkOuterClass.GetNetworkInfoResponse.Builder.class); } // Construct using pactus.NetworkOuterClass.GetNetworkInfoResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetMetricInfoFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; networkName_ = ""; connectedPeersCount_ = 0; metricInfo_ = null; if (metricInfoBuilder_ != null) { metricInfoBuilder_.dispose(); metricInfoBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_GetNetworkInfoResponse_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoResponse getDefaultInstanceForType() { return pactus.NetworkOuterClass.GetNetworkInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoResponse build() { pactus.NetworkOuterClass.GetNetworkInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoResponse buildPartial() { pactus.NetworkOuterClass.GetNetworkInfoResponse result = new pactus.NetworkOuterClass.GetNetworkInfoResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.GetNetworkInfoResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.networkName_ = networkName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.connectedPeersCount_ = connectedPeersCount_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.metricInfo_ = metricInfoBuilder_ == null ? metricInfo_ : metricInfoBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.GetNetworkInfoResponse) { return mergeFrom((pactus.NetworkOuterClass.GetNetworkInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.GetNetworkInfoResponse other) { if (other == pactus.NetworkOuterClass.GetNetworkInfoResponse.getDefaultInstance()) return this; if (!other.getNetworkName().isEmpty()) { networkName_ = other.networkName_; bitField0_ |= 0x00000001; onChanged(); } if (other.getConnectedPeersCount() != 0) { setConnectedPeersCount(other.getConnectedPeersCount()); } if (other.hasMetricInfo()) { mergeMetricInfo(other.getMetricInfo()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { networkName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { connectedPeersCount_ = input.readUInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 34: { input.readMessage( internalGetMetricInfoFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object networkName_ = ""; /** *
       * Name of the P2P network.
       * 
* * string network_name = 1 [json_name = "networkName"]; * @return The networkName. */ public java.lang.String getNetworkName() { java.lang.Object ref = networkName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); networkName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Name of the P2P network.
       * 
* * string network_name = 1 [json_name = "networkName"]; * @return The bytes for networkName. */ public com.google.protobuf.ByteString getNetworkNameBytes() { java.lang.Object ref = networkName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); networkName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Name of the P2P network.
       * 
* * string network_name = 1 [json_name = "networkName"]; * @param value The networkName to set. * @return This builder for chaining. */ public Builder setNetworkName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } networkName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Name of the P2P network.
       * 
* * string network_name = 1 [json_name = "networkName"]; * @return This builder for chaining. */ public Builder clearNetworkName() { networkName_ = getDefaultInstance().getNetworkName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * Name of the P2P network.
       * 
* * string network_name = 1 [json_name = "networkName"]; * @param value The bytes for networkName to set. * @return This builder for chaining. */ public Builder setNetworkNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); networkName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int connectedPeersCount_ ; /** *
       * Number of connected peers.
       * 
* * uint32 connected_peers_count = 2 [json_name = "connectedPeersCount"]; * @return The connectedPeersCount. */ @java.lang.Override public int getConnectedPeersCount() { return connectedPeersCount_; } /** *
       * Number of connected peers.
       * 
* * uint32 connected_peers_count = 2 [json_name = "connectedPeersCount"]; * @param value The connectedPeersCount to set. * @return This builder for chaining. */ public Builder setConnectedPeersCount(int value) { connectedPeersCount_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Number of connected peers.
       * 
* * uint32 connected_peers_count = 2 [json_name = "connectedPeersCount"]; * @return This builder for chaining. */ public Builder clearConnectedPeersCount() { bitField0_ = (bitField0_ & ~0x00000002); connectedPeersCount_ = 0; onChanged(); return this; } private pactus.NetworkOuterClass.MetricInfo metricInfo_; private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.MetricInfo, pactus.NetworkOuterClass.MetricInfo.Builder, pactus.NetworkOuterClass.MetricInfoOrBuilder> metricInfoBuilder_; /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; * @return Whether the metricInfo field is set. */ public boolean hasMetricInfo() { return ((bitField0_ & 0x00000004) != 0); } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; * @return The metricInfo. */ public pactus.NetworkOuterClass.MetricInfo getMetricInfo() { if (metricInfoBuilder_ == null) { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } else { return metricInfoBuilder_.getMessage(); } } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ public Builder setMetricInfo(pactus.NetworkOuterClass.MetricInfo value) { if (metricInfoBuilder_ == null) { if (value == null) { throw new NullPointerException(); } metricInfo_ = value; } else { metricInfoBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ public Builder setMetricInfo( pactus.NetworkOuterClass.MetricInfo.Builder builderForValue) { if (metricInfoBuilder_ == null) { metricInfo_ = builderForValue.build(); } else { metricInfoBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ public Builder mergeMetricInfo(pactus.NetworkOuterClass.MetricInfo value) { if (metricInfoBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && metricInfo_ != null && metricInfo_ != pactus.NetworkOuterClass.MetricInfo.getDefaultInstance()) { getMetricInfoBuilder().mergeFrom(value); } else { metricInfo_ = value; } } else { metricInfoBuilder_.mergeFrom(value); } if (metricInfo_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ public Builder clearMetricInfo() { bitField0_ = (bitField0_ & ~0x00000004); metricInfo_ = null; if (metricInfoBuilder_ != null) { metricInfoBuilder_.dispose(); metricInfoBuilder_ = null; } onChanged(); return this; } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ public pactus.NetworkOuterClass.MetricInfo.Builder getMetricInfoBuilder() { bitField0_ |= 0x00000004; onChanged(); return internalGetMetricInfoFieldBuilder().getBuilder(); } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ public pactus.NetworkOuterClass.MetricInfoOrBuilder getMetricInfoOrBuilder() { if (metricInfoBuilder_ != null) { return metricInfoBuilder_.getMessageOrBuilder(); } else { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } } /** *
       * Metrics related to node activity.
       * 
* * .pactus.MetricInfo metric_info = 4 [json_name = "metricInfo"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.MetricInfo, pactus.NetworkOuterClass.MetricInfo.Builder, pactus.NetworkOuterClass.MetricInfoOrBuilder> internalGetMetricInfoFieldBuilder() { if (metricInfoBuilder_ == null) { metricInfoBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.MetricInfo, pactus.NetworkOuterClass.MetricInfo.Builder, pactus.NetworkOuterClass.MetricInfoOrBuilder>( getMetricInfo(), getParentForChildren(), isClean()); metricInfo_ = null; } return metricInfoBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetNetworkInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetNetworkInfoResponse) private static final pactus.NetworkOuterClass.GetNetworkInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.GetNetworkInfoResponse(); } public static pactus.NetworkOuterClass.GetNetworkInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetNetworkInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.GetNetworkInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListPeersRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListPeersRequest) com.google.protobuf.MessageOrBuilder { /** *
     * If true, includes disconnected peers (default: connected peers only).
     * 
* * bool include_disconnected = 1 [json_name = "includeDisconnected"]; * @return The includeDisconnected. */ boolean getIncludeDisconnected(); } /** *
   * Request message for listing peers.
   * 
* * Protobuf type {@code pactus.ListPeersRequest} */ public static final class ListPeersRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListPeersRequest) ListPeersRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListPeersRequest"); } // Use ListPeersRequest.newBuilder() to construct. private ListPeersRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListPeersRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ListPeersRequest.class, pactus.NetworkOuterClass.ListPeersRequest.Builder.class); } public static final int INCLUDE_DISCONNECTED_FIELD_NUMBER = 1; private boolean includeDisconnected_ = false; /** *
     * If true, includes disconnected peers (default: connected peers only).
     * 
* * bool include_disconnected = 1 [json_name = "includeDisconnected"]; * @return The includeDisconnected. */ @java.lang.Override public boolean getIncludeDisconnected() { return includeDisconnected_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (includeDisconnected_ != false) { output.writeBool(1, includeDisconnected_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (includeDisconnected_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, includeDisconnected_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.ListPeersRequest)) { return super.equals(obj); } pactus.NetworkOuterClass.ListPeersRequest other = (pactus.NetworkOuterClass.ListPeersRequest) obj; if (getIncludeDisconnected() != other.getIncludeDisconnected()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + INCLUDE_DISCONNECTED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIncludeDisconnected()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ListPeersRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ListPeersRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.ListPeersRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for listing peers.
     * 
* * Protobuf type {@code pactus.ListPeersRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListPeersRequest) pactus.NetworkOuterClass.ListPeersRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ListPeersRequest.class, pactus.NetworkOuterClass.ListPeersRequest.Builder.class); } // Construct using pactus.NetworkOuterClass.ListPeersRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; includeDisconnected_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersRequest_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.ListPeersRequest getDefaultInstanceForType() { return pactus.NetworkOuterClass.ListPeersRequest.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.ListPeersRequest build() { pactus.NetworkOuterClass.ListPeersRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.ListPeersRequest buildPartial() { pactus.NetworkOuterClass.ListPeersRequest result = new pactus.NetworkOuterClass.ListPeersRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.ListPeersRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.includeDisconnected_ = includeDisconnected_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.ListPeersRequest) { return mergeFrom((pactus.NetworkOuterClass.ListPeersRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.ListPeersRequest other) { if (other == pactus.NetworkOuterClass.ListPeersRequest.getDefaultInstance()) return this; if (other.getIncludeDisconnected() != false) { setIncludeDisconnected(other.getIncludeDisconnected()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { includeDisconnected_ = input.readBool(); bitField0_ |= 0x00000001; break; } // case 8 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private boolean includeDisconnected_ ; /** *
       * If true, includes disconnected peers (default: connected peers only).
       * 
* * bool include_disconnected = 1 [json_name = "includeDisconnected"]; * @return The includeDisconnected. */ @java.lang.Override public boolean getIncludeDisconnected() { return includeDisconnected_; } /** *
       * If true, includes disconnected peers (default: connected peers only).
       * 
* * bool include_disconnected = 1 [json_name = "includeDisconnected"]; * @param value The includeDisconnected to set. * @return This builder for chaining. */ public Builder setIncludeDisconnected(boolean value) { includeDisconnected_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * If true, includes disconnected peers (default: connected peers only).
       * 
* * bool include_disconnected = 1 [json_name = "includeDisconnected"]; * @return This builder for chaining. */ public Builder clearIncludeDisconnected() { bitField0_ = (bitField0_ & ~0x00000001); includeDisconnected_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ListPeersRequest) } // @@protoc_insertion_point(class_scope:pactus.ListPeersRequest) private static final pactus.NetworkOuterClass.ListPeersRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.ListPeersRequest(); } public static pactus.NetworkOuterClass.ListPeersRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListPeersRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.ListPeersRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListPeersResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListPeersResponse) com.google.protobuf.MessageOrBuilder { /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ java.util.List getPeersList(); /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ pactus.NetworkOuterClass.PeerInfo getPeers(int index); /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ int getPeersCount(); /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ java.util.List getPeersOrBuilderList(); /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ pactus.NetworkOuterClass.PeerInfoOrBuilder getPeersOrBuilder( int index); } /** *
   * Response message for listing peers.
   * 
* * Protobuf type {@code pactus.ListPeersResponse} */ public static final class ListPeersResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListPeersResponse) ListPeersResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListPeersResponse"); } // Use ListPeersResponse.newBuilder() to construct. private ListPeersResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListPeersResponse() { peers_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ListPeersResponse.class, pactus.NetworkOuterClass.ListPeersResponse.Builder.class); } public static final int PEERS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List peers_; /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ @java.lang.Override public java.util.List getPeersList() { return peers_; } /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ @java.lang.Override public java.util.List getPeersOrBuilderList() { return peers_; } /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ @java.lang.Override public int getPeersCount() { return peers_.size(); } /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ @java.lang.Override public pactus.NetworkOuterClass.PeerInfo getPeers(int index) { return peers_.get(index); } /** *
     * List of peers.
     * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ @java.lang.Override public pactus.NetworkOuterClass.PeerInfoOrBuilder getPeersOrBuilder( int index) { return peers_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < peers_.size(); i++) { output.writeMessage(1, peers_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < peers_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, peers_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.ListPeersResponse)) { return super.equals(obj); } pactus.NetworkOuterClass.ListPeersResponse other = (pactus.NetworkOuterClass.ListPeersResponse) obj; if (!getPeersList() .equals(other.getPeersList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getPeersCount() > 0) { hash = (37 * hash) + PEERS_FIELD_NUMBER; hash = (53 * hash) + getPeersList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ListPeersResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ListPeersResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.ListPeersResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message for listing peers.
     * 
* * Protobuf type {@code pactus.ListPeersResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListPeersResponse) pactus.NetworkOuterClass.ListPeersResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ListPeersResponse.class, pactus.NetworkOuterClass.ListPeersResponse.Builder.class); } // Construct using pactus.NetworkOuterClass.ListPeersResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (peersBuilder_ == null) { peers_ = java.util.Collections.emptyList(); } else { peers_ = null; peersBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_ListPeersResponse_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.ListPeersResponse getDefaultInstanceForType() { return pactus.NetworkOuterClass.ListPeersResponse.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.ListPeersResponse build() { pactus.NetworkOuterClass.ListPeersResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.ListPeersResponse buildPartial() { pactus.NetworkOuterClass.ListPeersResponse result = new pactus.NetworkOuterClass.ListPeersResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.NetworkOuterClass.ListPeersResponse result) { if (peersBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { peers_ = java.util.Collections.unmodifiableList(peers_); bitField0_ = (bitField0_ & ~0x00000001); } result.peers_ = peers_; } else { result.peers_ = peersBuilder_.build(); } } private void buildPartial0(pactus.NetworkOuterClass.ListPeersResponse result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.ListPeersResponse) { return mergeFrom((pactus.NetworkOuterClass.ListPeersResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.ListPeersResponse other) { if (other == pactus.NetworkOuterClass.ListPeersResponse.getDefaultInstance()) return this; if (peersBuilder_ == null) { if (!other.peers_.isEmpty()) { if (peers_.isEmpty()) { peers_ = other.peers_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePeersIsMutable(); peers_.addAll(other.peers_); } onChanged(); } } else { if (!other.peers_.isEmpty()) { if (peersBuilder_.isEmpty()) { peersBuilder_.dispose(); peersBuilder_ = null; peers_ = other.peers_; bitField0_ = (bitField0_ & ~0x00000001); peersBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetPeersFieldBuilder() : null; } else { peersBuilder_.addAllMessages(other.peers_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { pactus.NetworkOuterClass.PeerInfo m = input.readMessage( pactus.NetworkOuterClass.PeerInfo.parser(), extensionRegistry); if (peersBuilder_ == null) { ensurePeersIsMutable(); peers_.add(m); } else { peersBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List peers_ = java.util.Collections.emptyList(); private void ensurePeersIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { peers_ = new java.util.ArrayList(peers_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.NetworkOuterClass.PeerInfo, pactus.NetworkOuterClass.PeerInfo.Builder, pactus.NetworkOuterClass.PeerInfoOrBuilder> peersBuilder_; /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public java.util.List getPeersList() { if (peersBuilder_ == null) { return java.util.Collections.unmodifiableList(peers_); } else { return peersBuilder_.getMessageList(); } } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public int getPeersCount() { if (peersBuilder_ == null) { return peers_.size(); } else { return peersBuilder_.getCount(); } } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public pactus.NetworkOuterClass.PeerInfo getPeers(int index) { if (peersBuilder_ == null) { return peers_.get(index); } else { return peersBuilder_.getMessage(index); } } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder setPeers( int index, pactus.NetworkOuterClass.PeerInfo value) { if (peersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePeersIsMutable(); peers_.set(index, value); onChanged(); } else { peersBuilder_.setMessage(index, value); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder setPeers( int index, pactus.NetworkOuterClass.PeerInfo.Builder builderForValue) { if (peersBuilder_ == null) { ensurePeersIsMutable(); peers_.set(index, builderForValue.build()); onChanged(); } else { peersBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder addPeers(pactus.NetworkOuterClass.PeerInfo value) { if (peersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePeersIsMutable(); peers_.add(value); onChanged(); } else { peersBuilder_.addMessage(value); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder addPeers( int index, pactus.NetworkOuterClass.PeerInfo value) { if (peersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePeersIsMutable(); peers_.add(index, value); onChanged(); } else { peersBuilder_.addMessage(index, value); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder addPeers( pactus.NetworkOuterClass.PeerInfo.Builder builderForValue) { if (peersBuilder_ == null) { ensurePeersIsMutable(); peers_.add(builderForValue.build()); onChanged(); } else { peersBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder addPeers( int index, pactus.NetworkOuterClass.PeerInfo.Builder builderForValue) { if (peersBuilder_ == null) { ensurePeersIsMutable(); peers_.add(index, builderForValue.build()); onChanged(); } else { peersBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder addAllPeers( java.lang.Iterable values) { if (peersBuilder_ == null) { ensurePeersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, peers_); onChanged(); } else { peersBuilder_.addAllMessages(values); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder clearPeers() { if (peersBuilder_ == null) { peers_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { peersBuilder_.clear(); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public Builder removePeers(int index) { if (peersBuilder_ == null) { ensurePeersIsMutable(); peers_.remove(index); onChanged(); } else { peersBuilder_.remove(index); } return this; } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public pactus.NetworkOuterClass.PeerInfo.Builder getPeersBuilder( int index) { return internalGetPeersFieldBuilder().getBuilder(index); } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public pactus.NetworkOuterClass.PeerInfoOrBuilder getPeersOrBuilder( int index) { if (peersBuilder_ == null) { return peers_.get(index); } else { return peersBuilder_.getMessageOrBuilder(index); } } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public java.util.List getPeersOrBuilderList() { if (peersBuilder_ != null) { return peersBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(peers_); } } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public pactus.NetworkOuterClass.PeerInfo.Builder addPeersBuilder() { return internalGetPeersFieldBuilder().addBuilder( pactus.NetworkOuterClass.PeerInfo.getDefaultInstance()); } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public pactus.NetworkOuterClass.PeerInfo.Builder addPeersBuilder( int index) { return internalGetPeersFieldBuilder().addBuilder( index, pactus.NetworkOuterClass.PeerInfo.getDefaultInstance()); } /** *
       * List of peers.
       * 
* * repeated .pactus.PeerInfo peers = 1 [json_name = "peers"]; */ public java.util.List getPeersBuilderList() { return internalGetPeersFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.NetworkOuterClass.PeerInfo, pactus.NetworkOuterClass.PeerInfo.Builder, pactus.NetworkOuterClass.PeerInfoOrBuilder> internalGetPeersFieldBuilder() { if (peersBuilder_ == null) { peersBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.NetworkOuterClass.PeerInfo, pactus.NetworkOuterClass.PeerInfo.Builder, pactus.NetworkOuterClass.PeerInfoOrBuilder>( peers_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); peers_ = null; } return peersBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.ListPeersResponse) } // @@protoc_insertion_point(class_scope:pactus.ListPeersResponse) private static final pactus.NetworkOuterClass.ListPeersResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.ListPeersResponse(); } public static pactus.NetworkOuterClass.ListPeersResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListPeersResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.ListPeersResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetNodeInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetNodeInfoRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for retrieving information of the node.
   * 
* * Protobuf type {@code pactus.GetNodeInfoRequest} */ public static final class GetNodeInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetNodeInfoRequest) GetNodeInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetNodeInfoRequest"); } // Use GetNodeInfoRequest.newBuilder() to construct. private GetNodeInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetNodeInfoRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNodeInfoRequest.class, pactus.NetworkOuterClass.GetNodeInfoRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.GetNodeInfoRequest)) { return super.equals(obj); } pactus.NetworkOuterClass.GetNodeInfoRequest other = (pactus.NetworkOuterClass.GetNodeInfoRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNodeInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.GetNodeInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving information of the node.
     * 
* * Protobuf type {@code pactus.GetNodeInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetNodeInfoRequest) pactus.NetworkOuterClass.GetNodeInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNodeInfoRequest.class, pactus.NetworkOuterClass.GetNodeInfoRequest.Builder.class); } // Construct using pactus.NetworkOuterClass.GetNodeInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoRequest_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoRequest getDefaultInstanceForType() { return pactus.NetworkOuterClass.GetNodeInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoRequest build() { pactus.NetworkOuterClass.GetNodeInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoRequest buildPartial() { pactus.NetworkOuterClass.GetNodeInfoRequest result = new pactus.NetworkOuterClass.GetNodeInfoRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.GetNodeInfoRequest) { return mergeFrom((pactus.NetworkOuterClass.GetNodeInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.GetNodeInfoRequest other) { if (other == pactus.NetworkOuterClass.GetNodeInfoRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.GetNodeInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetNodeInfoRequest) private static final pactus.NetworkOuterClass.GetNodeInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.GetNodeInfoRequest(); } public static pactus.NetworkOuterClass.GetNodeInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetNodeInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetNodeInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetNodeInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Moniker or Human-readable name identifying this node in the network.
     * 
* * string moniker = 1 [json_name = "moniker"]; * @return The moniker. */ java.lang.String getMoniker(); /** *
     * Moniker or Human-readable name identifying this node in the network.
     * 
* * string moniker = 1 [json_name = "moniker"]; * @return The bytes for moniker. */ com.google.protobuf.ByteString getMonikerBytes(); /** *
     * Version and agent details of the node.
     * 
* * string agent = 2 [json_name = "agent"]; * @return The agent. */ java.lang.String getAgent(); /** *
     * Version and agent details of the node.
     * 
* * string agent = 2 [json_name = "agent"]; * @return The bytes for agent. */ com.google.protobuf.ByteString getAgentBytes(); /** *
     * Peer ID of the node.
     * 
* * string peer_id = 3 [json_name = "peerId"]; * @return The peerId. */ java.lang.String getPeerId(); /** *
     * Peer ID of the node.
     * 
* * string peer_id = 3 [json_name = "peerId"]; * @return The bytes for peerId. */ com.google.protobuf.ByteString getPeerIdBytes(); /** *
     * Unix timestamp when the node was started (UTC).
     * 
* * uint64 started_at = 4 [json_name = "startedAt"]; * @return The startedAt. */ long getStartedAt(); /** *
     * Reachability status of the node.
     * 
* * string reachability = 5 [json_name = "reachability"]; * @return The reachability. */ java.lang.String getReachability(); /** *
     * Reachability status of the node.
     * 
* * string reachability = 5 [json_name = "reachability"]; * @return The bytes for reachability. */ com.google.protobuf.ByteString getReachabilityBytes(); /** *
     * Bitfield representing the services provided by the node.
     * 
* * int32 services = 6 [json_name = "services"]; * @return The services. */ int getServices(); /** *
     * Names of services provided by the node.
     * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return The servicesNames. */ java.lang.String getServicesNames(); /** *
     * Names of services provided by the node.
     * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return The bytes for servicesNames. */ com.google.protobuf.ByteString getServicesNamesBytes(); /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return A list containing the localAddrs. */ java.util.List getLocalAddrsList(); /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return The count of localAddrs. */ int getLocalAddrsCount(); /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index of the element to return. * @return The localAddrs at the given index. */ java.lang.String getLocalAddrs(int index); /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index of the value to return. * @return The bytes of the localAddrs at the given index. */ com.google.protobuf.ByteString getLocalAddrsBytes(int index); /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return A list containing the protocols. */ java.util.List getProtocolsList(); /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return The count of protocols. */ int getProtocolsCount(); /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index of the element to return. * @return The protocols at the given index. */ java.lang.String getProtocols(int index); /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index of the value to return. * @return The bytes of the protocols at the given index. */ com.google.protobuf.ByteString getProtocolsBytes(int index); /** *
     * Offset between the node's clock and the network's clock (in seconds).
     * 
* * double clock_offset = 13 [json_name = "clockOffset"]; * @return The clockOffset. */ double getClockOffset(); /** *
     * Information about the node's connections.
     * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; * @return Whether the connectionInfo field is set. */ boolean hasConnectionInfo(); /** *
     * Information about the node's connections.
     * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; * @return The connectionInfo. */ pactus.NetworkOuterClass.ConnectionInfo getConnectionInfo(); /** *
     * Information about the node's connections.
     * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ pactus.NetworkOuterClass.ConnectionInfoOrBuilder getConnectionInfoOrBuilder(); /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ java.util.List getZmqPublishersList(); /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ pactus.NetworkOuterClass.ZMQPublisherInfo getZmqPublishers(int index); /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ int getZmqPublishersCount(); /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ java.util.List getZmqPublishersOrBuilderList(); /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder getZmqPublishersOrBuilder( int index); /** *
     * Current Unix timestamp of the node (UTC).
     * 
* * uint64 current_time = 16 [json_name = "currentTime"]; * @return The currentTime. */ long getCurrentTime(); /** *
     * Name of the P2P network.
     * 
* * string network_name = 17 [json_name = "networkName"]; * @return The networkName. */ java.lang.String getNetworkName(); /** *
     * Name of the P2P network.
     * 
* * string network_name = 17 [json_name = "networkName"]; * @return The bytes for networkName. */ com.google.protobuf.ByteString getNetworkNameBytes(); } /** *
   * Response message contains information about a specific node in the network.
   * 
* * Protobuf type {@code pactus.GetNodeInfoResponse} */ public static final class GetNodeInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetNodeInfoResponse) GetNodeInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetNodeInfoResponse"); } // Use GetNodeInfoResponse.newBuilder() to construct. private GetNodeInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetNodeInfoResponse() { moniker_ = ""; agent_ = ""; peerId_ = ""; reachability_ = ""; servicesNames_ = ""; localAddrs_ = com.google.protobuf.LazyStringArrayList.emptyList(); protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); zmqPublishers_ = java.util.Collections.emptyList(); networkName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNodeInfoResponse.class, pactus.NetworkOuterClass.GetNodeInfoResponse.Builder.class); } private int bitField0_; public static final int MONIKER_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object moniker_ = ""; /** *
     * Moniker or Human-readable name identifying this node in the network.
     * 
* * string moniker = 1 [json_name = "moniker"]; * @return The moniker. */ @java.lang.Override public java.lang.String getMoniker() { java.lang.Object ref = moniker_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); moniker_ = s; return s; } } /** *
     * Moniker or Human-readable name identifying this node in the network.
     * 
* * string moniker = 1 [json_name = "moniker"]; * @return The bytes for moniker. */ @java.lang.Override public com.google.protobuf.ByteString getMonikerBytes() { java.lang.Object ref = moniker_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); moniker_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AGENT_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object agent_ = ""; /** *
     * Version and agent details of the node.
     * 
* * string agent = 2 [json_name = "agent"]; * @return The agent. */ @java.lang.Override public java.lang.String getAgent() { java.lang.Object ref = agent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); agent_ = s; return s; } } /** *
     * Version and agent details of the node.
     * 
* * string agent = 2 [json_name = "agent"]; * @return The bytes for agent. */ @java.lang.Override public com.google.protobuf.ByteString getAgentBytes() { java.lang.Object ref = agent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); agent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PEER_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object peerId_ = ""; /** *
     * Peer ID of the node.
     * 
* * string peer_id = 3 [json_name = "peerId"]; * @return The peerId. */ @java.lang.Override public java.lang.String getPeerId() { java.lang.Object ref = peerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); peerId_ = s; return s; } } /** *
     * Peer ID of the node.
     * 
* * string peer_id = 3 [json_name = "peerId"]; * @return The bytes for peerId. */ @java.lang.Override public com.google.protobuf.ByteString getPeerIdBytes() { java.lang.Object ref = peerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); peerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STARTED_AT_FIELD_NUMBER = 4; private long startedAt_ = 0L; /** *
     * Unix timestamp when the node was started (UTC).
     * 
* * uint64 started_at = 4 [json_name = "startedAt"]; * @return The startedAt. */ @java.lang.Override public long getStartedAt() { return startedAt_; } public static final int REACHABILITY_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object reachability_ = ""; /** *
     * Reachability status of the node.
     * 
* * string reachability = 5 [json_name = "reachability"]; * @return The reachability. */ @java.lang.Override public java.lang.String getReachability() { java.lang.Object ref = reachability_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); reachability_ = s; return s; } } /** *
     * Reachability status of the node.
     * 
* * string reachability = 5 [json_name = "reachability"]; * @return The bytes for reachability. */ @java.lang.Override public com.google.protobuf.ByteString getReachabilityBytes() { java.lang.Object ref = reachability_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); reachability_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICES_FIELD_NUMBER = 6; private int services_ = 0; /** *
     * Bitfield representing the services provided by the node.
     * 
* * int32 services = 6 [json_name = "services"]; * @return The services. */ @java.lang.Override public int getServices() { return services_; } public static final int SERVICES_NAMES_FIELD_NUMBER = 7; @SuppressWarnings("serial") private volatile java.lang.Object servicesNames_ = ""; /** *
     * Names of services provided by the node.
     * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return The servicesNames. */ @java.lang.Override public java.lang.String getServicesNames() { java.lang.Object ref = servicesNames_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); servicesNames_ = s; return s; } } /** *
     * Names of services provided by the node.
     * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return The bytes for servicesNames. */ @java.lang.Override public com.google.protobuf.ByteString getServicesNamesBytes() { java.lang.Object ref = servicesNames_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); servicesNames_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LOCAL_ADDRS_FIELD_NUMBER = 8; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList localAddrs_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return A list containing the localAddrs. */ public com.google.protobuf.ProtocolStringList getLocalAddrsList() { return localAddrs_; } /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return The count of localAddrs. */ public int getLocalAddrsCount() { return localAddrs_.size(); } /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index of the element to return. * @return The localAddrs at the given index. */ public java.lang.String getLocalAddrs(int index) { return localAddrs_.get(index); } /** *
     * List of addresses associated with the node.
     * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index of the value to return. * @return The bytes of the localAddrs at the given index. */ public com.google.protobuf.ByteString getLocalAddrsBytes(int index) { return localAddrs_.getByteString(index); } public static final int PROTOCOLS_FIELD_NUMBER = 9; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return A list containing the protocols. */ public com.google.protobuf.ProtocolStringList getProtocolsList() { return protocols_; } /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return The count of protocols. */ public int getProtocolsCount() { return protocols_.size(); } /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index of the element to return. * @return The protocols at the given index. */ public java.lang.String getProtocols(int index) { return protocols_.get(index); } /** *
     * List of protocols supported by the node.
     * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index of the value to return. * @return The bytes of the protocols at the given index. */ public com.google.protobuf.ByteString getProtocolsBytes(int index) { return protocols_.getByteString(index); } public static final int CLOCK_OFFSET_FIELD_NUMBER = 13; private double clockOffset_ = 0D; /** *
     * Offset between the node's clock and the network's clock (in seconds).
     * 
* * double clock_offset = 13 [json_name = "clockOffset"]; * @return The clockOffset. */ @java.lang.Override public double getClockOffset() { return clockOffset_; } public static final int CONNECTION_INFO_FIELD_NUMBER = 14; private pactus.NetworkOuterClass.ConnectionInfo connectionInfo_; /** *
     * Information about the node's connections.
     * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; * @return Whether the connectionInfo field is set. */ @java.lang.Override public boolean hasConnectionInfo() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Information about the node's connections.
     * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; * @return The connectionInfo. */ @java.lang.Override public pactus.NetworkOuterClass.ConnectionInfo getConnectionInfo() { return connectionInfo_ == null ? pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance() : connectionInfo_; } /** *
     * Information about the node's connections.
     * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ @java.lang.Override public pactus.NetworkOuterClass.ConnectionInfoOrBuilder getConnectionInfoOrBuilder() { return connectionInfo_ == null ? pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance() : connectionInfo_; } public static final int ZMQ_PUBLISHERS_FIELD_NUMBER = 15; @SuppressWarnings("serial") private java.util.List zmqPublishers_; /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ @java.lang.Override public java.util.List getZmqPublishersList() { return zmqPublishers_; } /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ @java.lang.Override public java.util.List getZmqPublishersOrBuilderList() { return zmqPublishers_; } /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ @java.lang.Override public int getZmqPublishersCount() { return zmqPublishers_.size(); } /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ @java.lang.Override public pactus.NetworkOuterClass.ZMQPublisherInfo getZmqPublishers(int index) { return zmqPublishers_.get(index); } /** *
     * List of active ZeroMQ publishers.
     * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ @java.lang.Override public pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder getZmqPublishersOrBuilder( int index) { return zmqPublishers_.get(index); } public static final int CURRENT_TIME_FIELD_NUMBER = 16; private long currentTime_ = 0L; /** *
     * Current Unix timestamp of the node (UTC).
     * 
* * uint64 current_time = 16 [json_name = "currentTime"]; * @return The currentTime. */ @java.lang.Override public long getCurrentTime() { return currentTime_; } public static final int NETWORK_NAME_FIELD_NUMBER = 17; @SuppressWarnings("serial") private volatile java.lang.Object networkName_ = ""; /** *
     * Name of the P2P network.
     * 
* * string network_name = 17 [json_name = "networkName"]; * @return The networkName. */ @java.lang.Override public java.lang.String getNetworkName() { java.lang.Object ref = networkName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); networkName_ = s; return s; } } /** *
     * Name of the P2P network.
     * 
* * string network_name = 17 [json_name = "networkName"]; * @return The bytes for networkName. */ @java.lang.Override public com.google.protobuf.ByteString getNetworkNameBytes() { java.lang.Object ref = networkName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); networkName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(moniker_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, moniker_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(agent_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, agent_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(peerId_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, peerId_); } if (startedAt_ != 0L) { output.writeUInt64(4, startedAt_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(reachability_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, reachability_); } if (services_ != 0) { output.writeInt32(6, services_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(servicesNames_)) { com.google.protobuf.GeneratedMessage.writeString(output, 7, servicesNames_); } for (int i = 0; i < localAddrs_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 8, localAddrs_.getRaw(i)); } for (int i = 0; i < protocols_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 9, protocols_.getRaw(i)); } if (java.lang.Double.doubleToRawLongBits(clockOffset_) != 0) { output.writeDouble(13, clockOffset_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(14, getConnectionInfo()); } for (int i = 0; i < zmqPublishers_.size(); i++) { output.writeMessage(15, zmqPublishers_.get(i)); } if (currentTime_ != 0L) { output.writeUInt64(16, currentTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(networkName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 17, networkName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(moniker_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, moniker_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(agent_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, agent_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(peerId_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, peerId_); } if (startedAt_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, startedAt_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(reachability_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, reachability_); } if (services_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(6, services_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(servicesNames_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(7, servicesNames_); } { int dataSize = 0; for (int i = 0; i < localAddrs_.size(); i++) { dataSize += computeStringSizeNoTag(localAddrs_.getRaw(i)); } size += dataSize; size += 1 * getLocalAddrsList().size(); } { int dataSize = 0; for (int i = 0; i < protocols_.size(); i++) { dataSize += computeStringSizeNoTag(protocols_.getRaw(i)); } size += dataSize; size += 1 * getProtocolsList().size(); } if (java.lang.Double.doubleToRawLongBits(clockOffset_) != 0) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(13, clockOffset_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(14, getConnectionInfo()); } for (int i = 0; i < zmqPublishers_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(15, zmqPublishers_.get(i)); } if (currentTime_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(16, currentTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(networkName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(17, networkName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.GetNodeInfoResponse)) { return super.equals(obj); } pactus.NetworkOuterClass.GetNodeInfoResponse other = (pactus.NetworkOuterClass.GetNodeInfoResponse) obj; if (!getMoniker() .equals(other.getMoniker())) return false; if (!getAgent() .equals(other.getAgent())) return false; if (!getPeerId() .equals(other.getPeerId())) return false; if (getStartedAt() != other.getStartedAt()) return false; if (!getReachability() .equals(other.getReachability())) return false; if (getServices() != other.getServices()) return false; if (!getServicesNames() .equals(other.getServicesNames())) return false; if (!getLocalAddrsList() .equals(other.getLocalAddrsList())) return false; if (!getProtocolsList() .equals(other.getProtocolsList())) return false; if (java.lang.Double.doubleToLongBits(getClockOffset()) != java.lang.Double.doubleToLongBits( other.getClockOffset())) return false; if (hasConnectionInfo() != other.hasConnectionInfo()) return false; if (hasConnectionInfo()) { if (!getConnectionInfo() .equals(other.getConnectionInfo())) return false; } if (!getZmqPublishersList() .equals(other.getZmqPublishersList())) return false; if (getCurrentTime() != other.getCurrentTime()) return false; if (!getNetworkName() .equals(other.getNetworkName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + MONIKER_FIELD_NUMBER; hash = (53 * hash) + getMoniker().hashCode(); hash = (37 * hash) + AGENT_FIELD_NUMBER; hash = (53 * hash) + getAgent().hashCode(); hash = (37 * hash) + PEER_ID_FIELD_NUMBER; hash = (53 * hash) + getPeerId().hashCode(); hash = (37 * hash) + STARTED_AT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getStartedAt()); hash = (37 * hash) + REACHABILITY_FIELD_NUMBER; hash = (53 * hash) + getReachability().hashCode(); hash = (37 * hash) + SERVICES_FIELD_NUMBER; hash = (53 * hash) + getServices(); hash = (37 * hash) + SERVICES_NAMES_FIELD_NUMBER; hash = (53 * hash) + getServicesNames().hashCode(); if (getLocalAddrsCount() > 0) { hash = (37 * hash) + LOCAL_ADDRS_FIELD_NUMBER; hash = (53 * hash) + getLocalAddrsList().hashCode(); } if (getProtocolsCount() > 0) { hash = (37 * hash) + PROTOCOLS_FIELD_NUMBER; hash = (53 * hash) + getProtocolsList().hashCode(); } hash = (37 * hash) + CLOCK_OFFSET_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getClockOffset())); if (hasConnectionInfo()) { hash = (37 * hash) + CONNECTION_INFO_FIELD_NUMBER; hash = (53 * hash) + getConnectionInfo().hashCode(); } if (getZmqPublishersCount() > 0) { hash = (37 * hash) + ZMQ_PUBLISHERS_FIELD_NUMBER; hash = (53 * hash) + getZmqPublishersList().hashCode(); } hash = (37 * hash) + CURRENT_TIME_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCurrentTime()); hash = (37 * hash) + NETWORK_NAME_FIELD_NUMBER; hash = (53 * hash) + getNetworkName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.GetNodeInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.GetNodeInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains information about a specific node in the network.
     * 
* * Protobuf type {@code pactus.GetNodeInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetNodeInfoResponse) pactus.NetworkOuterClass.GetNodeInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.GetNodeInfoResponse.class, pactus.NetworkOuterClass.GetNodeInfoResponse.Builder.class); } // Construct using pactus.NetworkOuterClass.GetNodeInfoResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetConnectionInfoFieldBuilder(); internalGetZmqPublishersFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; moniker_ = ""; agent_ = ""; peerId_ = ""; startedAt_ = 0L; reachability_ = ""; services_ = 0; servicesNames_ = ""; localAddrs_ = com.google.protobuf.LazyStringArrayList.emptyList(); protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); clockOffset_ = 0D; connectionInfo_ = null; if (connectionInfoBuilder_ != null) { connectionInfoBuilder_.dispose(); connectionInfoBuilder_ = null; } if (zmqPublishersBuilder_ == null) { zmqPublishers_ = java.util.Collections.emptyList(); } else { zmqPublishers_ = null; zmqPublishersBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000800); currentTime_ = 0L; networkName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_GetNodeInfoResponse_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoResponse getDefaultInstanceForType() { return pactus.NetworkOuterClass.GetNodeInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoResponse build() { pactus.NetworkOuterClass.GetNodeInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoResponse buildPartial() { pactus.NetworkOuterClass.GetNodeInfoResponse result = new pactus.NetworkOuterClass.GetNodeInfoResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.NetworkOuterClass.GetNodeInfoResponse result) { if (zmqPublishersBuilder_ == null) { if (((bitField0_ & 0x00000800) != 0)) { zmqPublishers_ = java.util.Collections.unmodifiableList(zmqPublishers_); bitField0_ = (bitField0_ & ~0x00000800); } result.zmqPublishers_ = zmqPublishers_; } else { result.zmqPublishers_ = zmqPublishersBuilder_.build(); } } private void buildPartial0(pactus.NetworkOuterClass.GetNodeInfoResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.moniker_ = moniker_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.agent_ = agent_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.peerId_ = peerId_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.startedAt_ = startedAt_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.reachability_ = reachability_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.services_ = services_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.servicesNames_ = servicesNames_; } if (((from_bitField0_ & 0x00000080) != 0)) { localAddrs_.makeImmutable(); result.localAddrs_ = localAddrs_; } if (((from_bitField0_ & 0x00000100) != 0)) { protocols_.makeImmutable(); result.protocols_ = protocols_; } if (((from_bitField0_ & 0x00000200) != 0)) { result.clockOffset_ = clockOffset_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000400) != 0)) { result.connectionInfo_ = connectionInfoBuilder_ == null ? connectionInfo_ : connectionInfoBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00001000) != 0)) { result.currentTime_ = currentTime_; } if (((from_bitField0_ & 0x00002000) != 0)) { result.networkName_ = networkName_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.GetNodeInfoResponse) { return mergeFrom((pactus.NetworkOuterClass.GetNodeInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.GetNodeInfoResponse other) { if (other == pactus.NetworkOuterClass.GetNodeInfoResponse.getDefaultInstance()) return this; if (!other.getMoniker().isEmpty()) { moniker_ = other.moniker_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAgent().isEmpty()) { agent_ = other.agent_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getPeerId().isEmpty()) { peerId_ = other.peerId_; bitField0_ |= 0x00000004; onChanged(); } if (other.getStartedAt() != 0L) { setStartedAt(other.getStartedAt()); } if (!other.getReachability().isEmpty()) { reachability_ = other.reachability_; bitField0_ |= 0x00000010; onChanged(); } if (other.getServices() != 0) { setServices(other.getServices()); } if (!other.getServicesNames().isEmpty()) { servicesNames_ = other.servicesNames_; bitField0_ |= 0x00000040; onChanged(); } if (!other.localAddrs_.isEmpty()) { if (localAddrs_.isEmpty()) { localAddrs_ = other.localAddrs_; bitField0_ |= 0x00000080; } else { ensureLocalAddrsIsMutable(); localAddrs_.addAll(other.localAddrs_); } onChanged(); } if (!other.protocols_.isEmpty()) { if (protocols_.isEmpty()) { protocols_ = other.protocols_; bitField0_ |= 0x00000100; } else { ensureProtocolsIsMutable(); protocols_.addAll(other.protocols_); } onChanged(); } if (java.lang.Double.doubleToRawLongBits(other.getClockOffset()) != 0) { setClockOffset(other.getClockOffset()); } if (other.hasConnectionInfo()) { mergeConnectionInfo(other.getConnectionInfo()); } if (zmqPublishersBuilder_ == null) { if (!other.zmqPublishers_.isEmpty()) { if (zmqPublishers_.isEmpty()) { zmqPublishers_ = other.zmqPublishers_; bitField0_ = (bitField0_ & ~0x00000800); } else { ensureZmqPublishersIsMutable(); zmqPublishers_.addAll(other.zmqPublishers_); } onChanged(); } } else { if (!other.zmqPublishers_.isEmpty()) { if (zmqPublishersBuilder_.isEmpty()) { zmqPublishersBuilder_.dispose(); zmqPublishersBuilder_ = null; zmqPublishers_ = other.zmqPublishers_; bitField0_ = (bitField0_ & ~0x00000800); zmqPublishersBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetZmqPublishersFieldBuilder() : null; } else { zmqPublishersBuilder_.addAllMessages(other.zmqPublishers_); } } } if (other.getCurrentTime() != 0L) { setCurrentTime(other.getCurrentTime()); } if (!other.getNetworkName().isEmpty()) { networkName_ = other.networkName_; bitField0_ |= 0x00002000; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { moniker_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { agent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { peerId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { startedAt_ = input.readUInt64(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { reachability_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 case 48: { services_ = input.readInt32(); bitField0_ |= 0x00000020; break; } // case 48 case 58: { servicesNames_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000040; break; } // case 58 case 66: { java.lang.String s = input.readStringRequireUtf8(); ensureLocalAddrsIsMutable(); localAddrs_.add(s); break; } // case 66 case 74: { java.lang.String s = input.readStringRequireUtf8(); ensureProtocolsIsMutable(); protocols_.add(s); break; } // case 74 case 105: { clockOffset_ = input.readDouble(); bitField0_ |= 0x00000200; break; } // case 105 case 114: { input.readMessage( internalGetConnectionInfoFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000400; break; } // case 114 case 122: { pactus.NetworkOuterClass.ZMQPublisherInfo m = input.readMessage( pactus.NetworkOuterClass.ZMQPublisherInfo.parser(), extensionRegistry); if (zmqPublishersBuilder_ == null) { ensureZmqPublishersIsMutable(); zmqPublishers_.add(m); } else { zmqPublishersBuilder_.addMessage(m); } break; } // case 122 case 128: { currentTime_ = input.readUInt64(); bitField0_ |= 0x00001000; break; } // case 128 case 138: { networkName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00002000; break; } // case 138 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object moniker_ = ""; /** *
       * Moniker or Human-readable name identifying this node in the network.
       * 
* * string moniker = 1 [json_name = "moniker"]; * @return The moniker. */ public java.lang.String getMoniker() { java.lang.Object ref = moniker_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); moniker_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Moniker or Human-readable name identifying this node in the network.
       * 
* * string moniker = 1 [json_name = "moniker"]; * @return The bytes for moniker. */ public com.google.protobuf.ByteString getMonikerBytes() { java.lang.Object ref = moniker_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); moniker_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Moniker or Human-readable name identifying this node in the network.
       * 
* * string moniker = 1 [json_name = "moniker"]; * @param value The moniker to set. * @return This builder for chaining. */ public Builder setMoniker( java.lang.String value) { if (value == null) { throw new NullPointerException(); } moniker_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Moniker or Human-readable name identifying this node in the network.
       * 
* * string moniker = 1 [json_name = "moniker"]; * @return This builder for chaining. */ public Builder clearMoniker() { moniker_ = getDefaultInstance().getMoniker(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * Moniker or Human-readable name identifying this node in the network.
       * 
* * string moniker = 1 [json_name = "moniker"]; * @param value The bytes for moniker to set. * @return This builder for chaining. */ public Builder setMonikerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); moniker_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object agent_ = ""; /** *
       * Version and agent details of the node.
       * 
* * string agent = 2 [json_name = "agent"]; * @return The agent. */ public java.lang.String getAgent() { java.lang.Object ref = agent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); agent_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Version and agent details of the node.
       * 
* * string agent = 2 [json_name = "agent"]; * @return The bytes for agent. */ public com.google.protobuf.ByteString getAgentBytes() { java.lang.Object ref = agent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); agent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Version and agent details of the node.
       * 
* * string agent = 2 [json_name = "agent"]; * @param value The agent to set. * @return This builder for chaining. */ public Builder setAgent( java.lang.String value) { if (value == null) { throw new NullPointerException(); } agent_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Version and agent details of the node.
       * 
* * string agent = 2 [json_name = "agent"]; * @return This builder for chaining. */ public Builder clearAgent() { agent_ = getDefaultInstance().getAgent(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Version and agent details of the node.
       * 
* * string agent = 2 [json_name = "agent"]; * @param value The bytes for agent to set. * @return This builder for chaining. */ public Builder setAgentBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); agent_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object peerId_ = ""; /** *
       * Peer ID of the node.
       * 
* * string peer_id = 3 [json_name = "peerId"]; * @return The peerId. */ public java.lang.String getPeerId() { java.lang.Object ref = peerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); peerId_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Peer ID of the node.
       * 
* * string peer_id = 3 [json_name = "peerId"]; * @return The bytes for peerId. */ public com.google.protobuf.ByteString getPeerIdBytes() { java.lang.Object ref = peerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); peerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Peer ID of the node.
       * 
* * string peer_id = 3 [json_name = "peerId"]; * @param value The peerId to set. * @return This builder for chaining. */ public Builder setPeerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } peerId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Peer ID of the node.
       * 
* * string peer_id = 3 [json_name = "peerId"]; * @return This builder for chaining. */ public Builder clearPeerId() { peerId_ = getDefaultInstance().getPeerId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * Peer ID of the node.
       * 
* * string peer_id = 3 [json_name = "peerId"]; * @param value The bytes for peerId to set. * @return This builder for chaining. */ public Builder setPeerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); peerId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private long startedAt_ ; /** *
       * Unix timestamp when the node was started (UTC).
       * 
* * uint64 started_at = 4 [json_name = "startedAt"]; * @return The startedAt. */ @java.lang.Override public long getStartedAt() { return startedAt_; } /** *
       * Unix timestamp when the node was started (UTC).
       * 
* * uint64 started_at = 4 [json_name = "startedAt"]; * @param value The startedAt to set. * @return This builder for chaining. */ public Builder setStartedAt(long value) { startedAt_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * Unix timestamp when the node was started (UTC).
       * 
* * uint64 started_at = 4 [json_name = "startedAt"]; * @return This builder for chaining. */ public Builder clearStartedAt() { bitField0_ = (bitField0_ & ~0x00000008); startedAt_ = 0L; onChanged(); return this; } private java.lang.Object reachability_ = ""; /** *
       * Reachability status of the node.
       * 
* * string reachability = 5 [json_name = "reachability"]; * @return The reachability. */ public java.lang.String getReachability() { java.lang.Object ref = reachability_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); reachability_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Reachability status of the node.
       * 
* * string reachability = 5 [json_name = "reachability"]; * @return The bytes for reachability. */ public com.google.protobuf.ByteString getReachabilityBytes() { java.lang.Object ref = reachability_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); reachability_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Reachability status of the node.
       * 
* * string reachability = 5 [json_name = "reachability"]; * @param value The reachability to set. * @return This builder for chaining. */ public Builder setReachability( java.lang.String value) { if (value == null) { throw new NullPointerException(); } reachability_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * Reachability status of the node.
       * 
* * string reachability = 5 [json_name = "reachability"]; * @return This builder for chaining. */ public Builder clearReachability() { reachability_ = getDefaultInstance().getReachability(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * Reachability status of the node.
       * 
* * string reachability = 5 [json_name = "reachability"]; * @param value The bytes for reachability to set. * @return This builder for chaining. */ public Builder setReachabilityBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); reachability_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } private int services_ ; /** *
       * Bitfield representing the services provided by the node.
       * 
* * int32 services = 6 [json_name = "services"]; * @return The services. */ @java.lang.Override public int getServices() { return services_; } /** *
       * Bitfield representing the services provided by the node.
       * 
* * int32 services = 6 [json_name = "services"]; * @param value The services to set. * @return This builder for chaining. */ public Builder setServices(int value) { services_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * Bitfield representing the services provided by the node.
       * 
* * int32 services = 6 [json_name = "services"]; * @return This builder for chaining. */ public Builder clearServices() { bitField0_ = (bitField0_ & ~0x00000020); services_ = 0; onChanged(); return this; } private java.lang.Object servicesNames_ = ""; /** *
       * Names of services provided by the node.
       * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return The servicesNames. */ public java.lang.String getServicesNames() { java.lang.Object ref = servicesNames_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); servicesNames_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Names of services provided by the node.
       * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return The bytes for servicesNames. */ public com.google.protobuf.ByteString getServicesNamesBytes() { java.lang.Object ref = servicesNames_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); servicesNames_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Names of services provided by the node.
       * 
* * string services_names = 7 [json_name = "servicesNames"]; * @param value The servicesNames to set. * @return This builder for chaining. */ public Builder setServicesNames( java.lang.String value) { if (value == null) { throw new NullPointerException(); } servicesNames_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * Names of services provided by the node.
       * 
* * string services_names = 7 [json_name = "servicesNames"]; * @return This builder for chaining. */ public Builder clearServicesNames() { servicesNames_ = getDefaultInstance().getServicesNames(); bitField0_ = (bitField0_ & ~0x00000040); onChanged(); return this; } /** *
       * Names of services provided by the node.
       * 
* * string services_names = 7 [json_name = "servicesNames"]; * @param value The bytes for servicesNames to set. * @return This builder for chaining. */ public Builder setServicesNamesBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); servicesNames_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList localAddrs_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureLocalAddrsIsMutable() { if (!localAddrs_.isModifiable()) { localAddrs_ = new com.google.protobuf.LazyStringArrayList(localAddrs_); } bitField0_ |= 0x00000080; } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return A list containing the localAddrs. */ public com.google.protobuf.ProtocolStringList getLocalAddrsList() { localAddrs_.makeImmutable(); return localAddrs_; } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return The count of localAddrs. */ public int getLocalAddrsCount() { return localAddrs_.size(); } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index of the element to return. * @return The localAddrs at the given index. */ public java.lang.String getLocalAddrs(int index) { return localAddrs_.get(index); } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index of the value to return. * @return The bytes of the localAddrs at the given index. */ public com.google.protobuf.ByteString getLocalAddrsBytes(int index) { return localAddrs_.getByteString(index); } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param index The index to set the value at. * @param value The localAddrs to set. * @return This builder for chaining. */ public Builder setLocalAddrs( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLocalAddrsIsMutable(); localAddrs_.set(index, value); bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param value The localAddrs to add. * @return This builder for chaining. */ public Builder addLocalAddrs( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLocalAddrsIsMutable(); localAddrs_.add(value); bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param values The localAddrs to add. * @return This builder for chaining. */ public Builder addAllLocalAddrs( java.lang.Iterable values) { ensureLocalAddrsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, localAddrs_); bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @return This builder for chaining. */ public Builder clearLocalAddrs() { localAddrs_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000080);; onChanged(); return this; } /** *
       * List of addresses associated with the node.
       * 
* * repeated string local_addrs = 8 [json_name = "localAddrs"]; * @param value The bytes of the localAddrs to add. * @return This builder for chaining. */ public Builder addLocalAddrsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureLocalAddrsIsMutable(); localAddrs_.add(value); bitField0_ |= 0x00000080; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureProtocolsIsMutable() { if (!protocols_.isModifiable()) { protocols_ = new com.google.protobuf.LazyStringArrayList(protocols_); } bitField0_ |= 0x00000100; } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return A list containing the protocols. */ public com.google.protobuf.ProtocolStringList getProtocolsList() { protocols_.makeImmutable(); return protocols_; } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return The count of protocols. */ public int getProtocolsCount() { return protocols_.size(); } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index of the element to return. * @return The protocols at the given index. */ public java.lang.String getProtocols(int index) { return protocols_.get(index); } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index of the value to return. * @return The bytes of the protocols at the given index. */ public com.google.protobuf.ByteString getProtocolsBytes(int index) { return protocols_.getByteString(index); } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param index The index to set the value at. * @param value The protocols to set. * @return This builder for chaining. */ public Builder setProtocols( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProtocolsIsMutable(); protocols_.set(index, value); bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param value The protocols to add. * @return This builder for chaining. */ public Builder addProtocols( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProtocolsIsMutable(); protocols_.add(value); bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param values The protocols to add. * @return This builder for chaining. */ public Builder addAllProtocols( java.lang.Iterable values) { ensureProtocolsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, protocols_); bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @return This builder for chaining. */ public Builder clearProtocols() { protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000100);; onChanged(); return this; } /** *
       * List of protocols supported by the node.
       * 
* * repeated string protocols = 9 [json_name = "protocols"]; * @param value The bytes of the protocols to add. * @return This builder for chaining. */ public Builder addProtocolsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureProtocolsIsMutable(); protocols_.add(value); bitField0_ |= 0x00000100; onChanged(); return this; } private double clockOffset_ ; /** *
       * Offset between the node's clock and the network's clock (in seconds).
       * 
* * double clock_offset = 13 [json_name = "clockOffset"]; * @return The clockOffset. */ @java.lang.Override public double getClockOffset() { return clockOffset_; } /** *
       * Offset between the node's clock and the network's clock (in seconds).
       * 
* * double clock_offset = 13 [json_name = "clockOffset"]; * @param value The clockOffset to set. * @return This builder for chaining. */ public Builder setClockOffset(double value) { clockOffset_ = value; bitField0_ |= 0x00000200; onChanged(); return this; } /** *
       * Offset between the node's clock and the network's clock (in seconds).
       * 
* * double clock_offset = 13 [json_name = "clockOffset"]; * @return This builder for chaining. */ public Builder clearClockOffset() { bitField0_ = (bitField0_ & ~0x00000200); clockOffset_ = 0D; onChanged(); return this; } private pactus.NetworkOuterClass.ConnectionInfo connectionInfo_; private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.ConnectionInfo, pactus.NetworkOuterClass.ConnectionInfo.Builder, pactus.NetworkOuterClass.ConnectionInfoOrBuilder> connectionInfoBuilder_; /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; * @return Whether the connectionInfo field is set. */ public boolean hasConnectionInfo() { return ((bitField0_ & 0x00000400) != 0); } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; * @return The connectionInfo. */ public pactus.NetworkOuterClass.ConnectionInfo getConnectionInfo() { if (connectionInfoBuilder_ == null) { return connectionInfo_ == null ? pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance() : connectionInfo_; } else { return connectionInfoBuilder_.getMessage(); } } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ public Builder setConnectionInfo(pactus.NetworkOuterClass.ConnectionInfo value) { if (connectionInfoBuilder_ == null) { if (value == null) { throw new NullPointerException(); } connectionInfo_ = value; } else { connectionInfoBuilder_.setMessage(value); } bitField0_ |= 0x00000400; onChanged(); return this; } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ public Builder setConnectionInfo( pactus.NetworkOuterClass.ConnectionInfo.Builder builderForValue) { if (connectionInfoBuilder_ == null) { connectionInfo_ = builderForValue.build(); } else { connectionInfoBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000400; onChanged(); return this; } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ public Builder mergeConnectionInfo(pactus.NetworkOuterClass.ConnectionInfo value) { if (connectionInfoBuilder_ == null) { if (((bitField0_ & 0x00000400) != 0) && connectionInfo_ != null && connectionInfo_ != pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance()) { getConnectionInfoBuilder().mergeFrom(value); } else { connectionInfo_ = value; } } else { connectionInfoBuilder_.mergeFrom(value); } if (connectionInfo_ != null) { bitField0_ |= 0x00000400; onChanged(); } return this; } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ public Builder clearConnectionInfo() { bitField0_ = (bitField0_ & ~0x00000400); connectionInfo_ = null; if (connectionInfoBuilder_ != null) { connectionInfoBuilder_.dispose(); connectionInfoBuilder_ = null; } onChanged(); return this; } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ public pactus.NetworkOuterClass.ConnectionInfo.Builder getConnectionInfoBuilder() { bitField0_ |= 0x00000400; onChanged(); return internalGetConnectionInfoFieldBuilder().getBuilder(); } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ public pactus.NetworkOuterClass.ConnectionInfoOrBuilder getConnectionInfoOrBuilder() { if (connectionInfoBuilder_ != null) { return connectionInfoBuilder_.getMessageOrBuilder(); } else { return connectionInfo_ == null ? pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance() : connectionInfo_; } } /** *
       * Information about the node's connections.
       * 
* * .pactus.ConnectionInfo connection_info = 14 [json_name = "connectionInfo"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.ConnectionInfo, pactus.NetworkOuterClass.ConnectionInfo.Builder, pactus.NetworkOuterClass.ConnectionInfoOrBuilder> internalGetConnectionInfoFieldBuilder() { if (connectionInfoBuilder_ == null) { connectionInfoBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.ConnectionInfo, pactus.NetworkOuterClass.ConnectionInfo.Builder, pactus.NetworkOuterClass.ConnectionInfoOrBuilder>( getConnectionInfo(), getParentForChildren(), isClean()); connectionInfo_ = null; } return connectionInfoBuilder_; } private java.util.List zmqPublishers_ = java.util.Collections.emptyList(); private void ensureZmqPublishersIsMutable() { if (!((bitField0_ & 0x00000800) != 0)) { zmqPublishers_ = new java.util.ArrayList(zmqPublishers_); bitField0_ |= 0x00000800; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.NetworkOuterClass.ZMQPublisherInfo, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder, pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder> zmqPublishersBuilder_; /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public java.util.List getZmqPublishersList() { if (zmqPublishersBuilder_ == null) { return java.util.Collections.unmodifiableList(zmqPublishers_); } else { return zmqPublishersBuilder_.getMessageList(); } } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public int getZmqPublishersCount() { if (zmqPublishersBuilder_ == null) { return zmqPublishers_.size(); } else { return zmqPublishersBuilder_.getCount(); } } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public pactus.NetworkOuterClass.ZMQPublisherInfo getZmqPublishers(int index) { if (zmqPublishersBuilder_ == null) { return zmqPublishers_.get(index); } else { return zmqPublishersBuilder_.getMessage(index); } } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder setZmqPublishers( int index, pactus.NetworkOuterClass.ZMQPublisherInfo value) { if (zmqPublishersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureZmqPublishersIsMutable(); zmqPublishers_.set(index, value); onChanged(); } else { zmqPublishersBuilder_.setMessage(index, value); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder setZmqPublishers( int index, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder builderForValue) { if (zmqPublishersBuilder_ == null) { ensureZmqPublishersIsMutable(); zmqPublishers_.set(index, builderForValue.build()); onChanged(); } else { zmqPublishersBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder addZmqPublishers(pactus.NetworkOuterClass.ZMQPublisherInfo value) { if (zmqPublishersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureZmqPublishersIsMutable(); zmqPublishers_.add(value); onChanged(); } else { zmqPublishersBuilder_.addMessage(value); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder addZmqPublishers( int index, pactus.NetworkOuterClass.ZMQPublisherInfo value) { if (zmqPublishersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureZmqPublishersIsMutable(); zmqPublishers_.add(index, value); onChanged(); } else { zmqPublishersBuilder_.addMessage(index, value); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder addZmqPublishers( pactus.NetworkOuterClass.ZMQPublisherInfo.Builder builderForValue) { if (zmqPublishersBuilder_ == null) { ensureZmqPublishersIsMutable(); zmqPublishers_.add(builderForValue.build()); onChanged(); } else { zmqPublishersBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder addZmqPublishers( int index, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder builderForValue) { if (zmqPublishersBuilder_ == null) { ensureZmqPublishersIsMutable(); zmqPublishers_.add(index, builderForValue.build()); onChanged(); } else { zmqPublishersBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder addAllZmqPublishers( java.lang.Iterable values) { if (zmqPublishersBuilder_ == null) { ensureZmqPublishersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, zmqPublishers_); onChanged(); } else { zmqPublishersBuilder_.addAllMessages(values); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder clearZmqPublishers() { if (zmqPublishersBuilder_ == null) { zmqPublishers_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000800); onChanged(); } else { zmqPublishersBuilder_.clear(); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public Builder removeZmqPublishers(int index) { if (zmqPublishersBuilder_ == null) { ensureZmqPublishersIsMutable(); zmqPublishers_.remove(index); onChanged(); } else { zmqPublishersBuilder_.remove(index); } return this; } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public pactus.NetworkOuterClass.ZMQPublisherInfo.Builder getZmqPublishersBuilder( int index) { return internalGetZmqPublishersFieldBuilder().getBuilder(index); } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder getZmqPublishersOrBuilder( int index) { if (zmqPublishersBuilder_ == null) { return zmqPublishers_.get(index); } else { return zmqPublishersBuilder_.getMessageOrBuilder(index); } } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public java.util.List getZmqPublishersOrBuilderList() { if (zmqPublishersBuilder_ != null) { return zmqPublishersBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(zmqPublishers_); } } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public pactus.NetworkOuterClass.ZMQPublisherInfo.Builder addZmqPublishersBuilder() { return internalGetZmqPublishersFieldBuilder().addBuilder( pactus.NetworkOuterClass.ZMQPublisherInfo.getDefaultInstance()); } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public pactus.NetworkOuterClass.ZMQPublisherInfo.Builder addZmqPublishersBuilder( int index) { return internalGetZmqPublishersFieldBuilder().addBuilder( index, pactus.NetworkOuterClass.ZMQPublisherInfo.getDefaultInstance()); } /** *
       * List of active ZeroMQ publishers.
       * 
* * repeated .pactus.ZMQPublisherInfo zmq_publishers = 15 [json_name = "zmqPublishers"]; */ public java.util.List getZmqPublishersBuilderList() { return internalGetZmqPublishersFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.NetworkOuterClass.ZMQPublisherInfo, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder, pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder> internalGetZmqPublishersFieldBuilder() { if (zmqPublishersBuilder_ == null) { zmqPublishersBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.NetworkOuterClass.ZMQPublisherInfo, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder, pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder>( zmqPublishers_, ((bitField0_ & 0x00000800) != 0), getParentForChildren(), isClean()); zmqPublishers_ = null; } return zmqPublishersBuilder_; } private long currentTime_ ; /** *
       * Current Unix timestamp of the node (UTC).
       * 
* * uint64 current_time = 16 [json_name = "currentTime"]; * @return The currentTime. */ @java.lang.Override public long getCurrentTime() { return currentTime_; } /** *
       * Current Unix timestamp of the node (UTC).
       * 
* * uint64 current_time = 16 [json_name = "currentTime"]; * @param value The currentTime to set. * @return This builder for chaining. */ public Builder setCurrentTime(long value) { currentTime_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } /** *
       * Current Unix timestamp of the node (UTC).
       * 
* * uint64 current_time = 16 [json_name = "currentTime"]; * @return This builder for chaining. */ public Builder clearCurrentTime() { bitField0_ = (bitField0_ & ~0x00001000); currentTime_ = 0L; onChanged(); return this; } private java.lang.Object networkName_ = ""; /** *
       * Name of the P2P network.
       * 
* * string network_name = 17 [json_name = "networkName"]; * @return The networkName. */ public java.lang.String getNetworkName() { java.lang.Object ref = networkName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); networkName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Name of the P2P network.
       * 
* * string network_name = 17 [json_name = "networkName"]; * @return The bytes for networkName. */ public com.google.protobuf.ByteString getNetworkNameBytes() { java.lang.Object ref = networkName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); networkName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Name of the P2P network.
       * 
* * string network_name = 17 [json_name = "networkName"]; * @param value The networkName to set. * @return This builder for chaining. */ public Builder setNetworkName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } networkName_ = value; bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * Name of the P2P network.
       * 
* * string network_name = 17 [json_name = "networkName"]; * @return This builder for chaining. */ public Builder clearNetworkName() { networkName_ = getDefaultInstance().getNetworkName(); bitField0_ = (bitField0_ & ~0x00002000); onChanged(); return this; } /** *
       * Name of the P2P network.
       * 
* * string network_name = 17 [json_name = "networkName"]; * @param value The bytes for networkName to set. * @return This builder for chaining. */ public Builder setNetworkNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); networkName_ = value; bitField0_ |= 0x00002000; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetNodeInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetNodeInfoResponse) private static final pactus.NetworkOuterClass.GetNodeInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.GetNodeInfoResponse(); } public static pactus.NetworkOuterClass.GetNodeInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetNodeInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.GetNodeInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ZMQPublisherInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ZMQPublisherInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The topic associated with the publisher.
     * 
* * string topic = 1 [json_name = "topic"]; * @return The topic. */ java.lang.String getTopic(); /** *
     * The topic associated with the publisher.
     * 
* * string topic = 1 [json_name = "topic"]; * @return The bytes for topic. */ com.google.protobuf.ByteString getTopicBytes(); /** *
     * The address of the publisher.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address of the publisher.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The high-water mark (HWM) for the publisher, indicating the
     * maximum number of messages to queue before dropping older ones.
     * 
* * int32 hwm = 3 [json_name = "hwm"]; * @return The hwm. */ int getHwm(); } /** *
   * ZMQPublisherInfo contains information about a ZeroMQ publisher.
   * 
* * Protobuf type {@code pactus.ZMQPublisherInfo} */ public static final class ZMQPublisherInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ZMQPublisherInfo) ZMQPublisherInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ZMQPublisherInfo"); } // Use ZMQPublisherInfo.newBuilder() to construct. private ZMQPublisherInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ZMQPublisherInfo() { topic_ = ""; address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ZMQPublisherInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ZMQPublisherInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ZMQPublisherInfo.class, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder.class); } public static final int TOPIC_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object topic_ = ""; /** *
     * The topic associated with the publisher.
     * 
* * string topic = 1 [json_name = "topic"]; * @return The topic. */ @java.lang.Override public java.lang.String getTopic() { java.lang.Object ref = topic_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); topic_ = s; return s; } } /** *
     * The topic associated with the publisher.
     * 
* * string topic = 1 [json_name = "topic"]; * @return The bytes for topic. */ @java.lang.Override public com.google.protobuf.ByteString getTopicBytes() { java.lang.Object ref = topic_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); topic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address of the publisher.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address of the publisher.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int HWM_FIELD_NUMBER = 3; private int hwm_ = 0; /** *
     * The high-water mark (HWM) for the publisher, indicating the
     * maximum number of messages to queue before dropping older ones.
     * 
* * int32 hwm = 3 [json_name = "hwm"]; * @return The hwm. */ @java.lang.Override public int getHwm() { return hwm_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(topic_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, topic_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, address_); } if (hwm_ != 0) { output.writeInt32(3, hwm_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(topic_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, topic_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, address_); } if (hwm_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, hwm_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.ZMQPublisherInfo)) { return super.equals(obj); } pactus.NetworkOuterClass.ZMQPublisherInfo other = (pactus.NetworkOuterClass.ZMQPublisherInfo) obj; if (!getTopic() .equals(other.getTopic())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (getHwm() != other.getHwm()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TOPIC_FIELD_NUMBER; hash = (53 * hash) + getTopic().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + HWM_FIELD_NUMBER; hash = (53 * hash) + getHwm(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ZMQPublisherInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.ZMQPublisherInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * ZMQPublisherInfo contains information about a ZeroMQ publisher.
     * 
* * Protobuf type {@code pactus.ZMQPublisherInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ZMQPublisherInfo) pactus.NetworkOuterClass.ZMQPublisherInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ZMQPublisherInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ZMQPublisherInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ZMQPublisherInfo.class, pactus.NetworkOuterClass.ZMQPublisherInfo.Builder.class); } // Construct using pactus.NetworkOuterClass.ZMQPublisherInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; topic_ = ""; address_ = ""; hwm_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_ZMQPublisherInfo_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.ZMQPublisherInfo getDefaultInstanceForType() { return pactus.NetworkOuterClass.ZMQPublisherInfo.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.ZMQPublisherInfo build() { pactus.NetworkOuterClass.ZMQPublisherInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.ZMQPublisherInfo buildPartial() { pactus.NetworkOuterClass.ZMQPublisherInfo result = new pactus.NetworkOuterClass.ZMQPublisherInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.ZMQPublisherInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.topic_ = topic_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.hwm_ = hwm_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.ZMQPublisherInfo) { return mergeFrom((pactus.NetworkOuterClass.ZMQPublisherInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.ZMQPublisherInfo other) { if (other == pactus.NetworkOuterClass.ZMQPublisherInfo.getDefaultInstance()) return this; if (!other.getTopic().isEmpty()) { topic_ = other.topic_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000002; onChanged(); } if (other.getHwm() != 0) { setHwm(other.getHwm()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { topic_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { hwm_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object topic_ = ""; /** *
       * The topic associated with the publisher.
       * 
* * string topic = 1 [json_name = "topic"]; * @return The topic. */ public java.lang.String getTopic() { java.lang.Object ref = topic_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); topic_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The topic associated with the publisher.
       * 
* * string topic = 1 [json_name = "topic"]; * @return The bytes for topic. */ public com.google.protobuf.ByteString getTopicBytes() { java.lang.Object ref = topic_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); topic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The topic associated with the publisher.
       * 
* * string topic = 1 [json_name = "topic"]; * @param value The topic to set. * @return This builder for chaining. */ public Builder setTopic( java.lang.String value) { if (value == null) { throw new NullPointerException(); } topic_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The topic associated with the publisher.
       * 
* * string topic = 1 [json_name = "topic"]; * @return This builder for chaining. */ public Builder clearTopic() { topic_ = getDefaultInstance().getTopic(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The topic associated with the publisher.
       * 
* * string topic = 1 [json_name = "topic"]; * @param value The bytes for topic to set. * @return This builder for chaining. */ public Builder setTopicBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); topic_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address of the publisher.
       * 
* * string address = 2 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the publisher.
       * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the publisher.
       * 
* * string address = 2 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address of the publisher.
       * 
* * string address = 2 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address of the publisher.
       * 
* * string address = 2 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int hwm_ ; /** *
       * The high-water mark (HWM) for the publisher, indicating the
       * maximum number of messages to queue before dropping older ones.
       * 
* * int32 hwm = 3 [json_name = "hwm"]; * @return The hwm. */ @java.lang.Override public int getHwm() { return hwm_; } /** *
       * The high-water mark (HWM) for the publisher, indicating the
       * maximum number of messages to queue before dropping older ones.
       * 
* * int32 hwm = 3 [json_name = "hwm"]; * @param value The hwm to set. * @return This builder for chaining. */ public Builder setHwm(int value) { hwm_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The high-water mark (HWM) for the publisher, indicating the
       * maximum number of messages to queue before dropping older ones.
       * 
* * int32 hwm = 3 [json_name = "hwm"]; * @return This builder for chaining. */ public Builder clearHwm() { bitField0_ = (bitField0_ & ~0x00000004); hwm_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ZMQPublisherInfo) } // @@protoc_insertion_point(class_scope:pactus.ZMQPublisherInfo) private static final pactus.NetworkOuterClass.ZMQPublisherInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.ZMQPublisherInfo(); } public static pactus.NetworkOuterClass.ZMQPublisherInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ZMQPublisherInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.ZMQPublisherInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PeerInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PeerInfo) com.google.protobuf.MessageOrBuilder { /** *
     * Current status of the peer (e.g., connected, disconnected).
     * 
* * int32 status = 1 [json_name = "status"]; * @return The status. */ int getStatus(); /** *
     * Moniker or Human-Readable name of the peer.
     * 
* * string moniker = 2 [json_name = "moniker"]; * @return The moniker. */ java.lang.String getMoniker(); /** *
     * Moniker or Human-Readable name of the peer.
     * 
* * string moniker = 2 [json_name = "moniker"]; * @return The bytes for moniker. */ com.google.protobuf.ByteString getMonikerBytes(); /** *
     * Version and agent details of the peer.
     * 
* * string agent = 3 [json_name = "agent"]; * @return The agent. */ java.lang.String getAgent(); /** *
     * Version and agent details of the peer.
     * 
* * string agent = 3 [json_name = "agent"]; * @return The bytes for agent. */ com.google.protobuf.ByteString getAgentBytes(); /** *
     * Peer ID of the peer in P2P network.
     * 
* * string peer_id = 4 [json_name = "peerId"]; * @return The peerId. */ java.lang.String getPeerId(); /** *
     * Peer ID of the peer in P2P network.
     * 
* * string peer_id = 4 [json_name = "peerId"]; * @return The bytes for peerId. */ com.google.protobuf.ByteString getPeerIdBytes(); /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return A list containing the consensusKeys. */ java.util.List getConsensusKeysList(); /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return The count of consensusKeys. */ int getConsensusKeysCount(); /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index of the element to return. * @return The consensusKeys at the given index. */ java.lang.String getConsensusKeys(int index); /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index of the value to return. * @return The bytes of the consensusKeys at the given index. */ com.google.protobuf.ByteString getConsensusKeysBytes(int index); /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return A list containing the consensusAddresses. */ java.util.List getConsensusAddressesList(); /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return The count of consensusAddresses. */ int getConsensusAddressesCount(); /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index of the element to return. * @return The consensusAddresses at the given index. */ java.lang.String getConsensusAddresses(int index); /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index of the value to return. * @return The bytes of the consensusAddresses at the given index. */ com.google.protobuf.ByteString getConsensusAddressesBytes(int index); /** *
     * Bitfield representing the services provided by the peer.
     * 
* * uint32 services = 7 [json_name = "services"]; * @return The services. */ int getServices(); /** *
     * Hash of the last block the peer knows.
     * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return The lastBlockHash. */ java.lang.String getLastBlockHash(); /** *
     * Hash of the last block the peer knows.
     * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return The bytes for lastBlockHash. */ com.google.protobuf.ByteString getLastBlockHashBytes(); /** *
     * Blockchain height of the peer.
     * 
* * uint32 height = 9 [json_name = "height"]; * @return The height. */ int getHeight(); /** *
     * Unix timestamp of the last bundle sent to the peer (UTC).
     * 
* * int64 last_sent = 10 [json_name = "lastSent"]; * @return The lastSent. */ long getLastSent(); /** *
     * Unix timestamp of the last bundle received from the peer (UTC).
     * 
* * int64 last_received = 11 [json_name = "lastReceived"]; * @return The lastReceived. */ long getLastReceived(); /** *
     * Network address of the peer.
     * 
* * string address = 12 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * Network address of the peer.
     * 
* * string address = 12 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * Connection direction (e.g., inbound, outbound).
     * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ int getDirectionValue(); /** *
     * Connection direction (e.g., inbound, outbound).
     * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return The direction. */ pactus.NetworkOuterClass.Direction getDirection(); /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return A list containing the protocols. */ java.util.List getProtocolsList(); /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return The count of protocols. */ int getProtocolsCount(); /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index of the element to return. * @return The protocols at the given index. */ java.lang.String getProtocols(int index); /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index of the value to return. * @return The bytes of the protocols at the given index. */ com.google.protobuf.ByteString getProtocolsBytes(int index); /** *
     * Total download sessions with the peer.
     * 
* * int32 total_sessions = 15 [json_name = "totalSessions"]; * @return The totalSessions. */ int getTotalSessions(); /** *
     * Completed download sessions with the peer.
     * 
* * int32 completed_sessions = 16 [json_name = "completedSessions"]; * @return The completedSessions. */ int getCompletedSessions(); /** *
     * Metrics related to peer activity.
     * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; * @return Whether the metricInfo field is set. */ boolean hasMetricInfo(); /** *
     * Metrics related to peer activity.
     * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; * @return The metricInfo. */ pactus.NetworkOuterClass.MetricInfo getMetricInfo(); /** *
     * Metrics related to peer activity.
     * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ pactus.NetworkOuterClass.MetricInfoOrBuilder getMetricInfoOrBuilder(); /** *
     * Whether the hello message was sent from the outbound connection.
     * 
* * bool outbound_hello_sent = 18 [json_name = "outboundHelloSent"]; * @return The outboundHelloSent. */ boolean getOutboundHelloSent(); } /** *
   * PeerInfo contains information about a peer in the network.
   * 
* * Protobuf type {@code pactus.PeerInfo} */ public static final class PeerInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PeerInfo) PeerInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PeerInfo"); } // Use PeerInfo.newBuilder() to construct. private PeerInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PeerInfo() { moniker_ = ""; agent_ = ""; peerId_ = ""; consensusKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); consensusAddresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); lastBlockHash_ = ""; address_ = ""; direction_ = 0; protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_PeerInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_PeerInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.PeerInfo.class, pactus.NetworkOuterClass.PeerInfo.Builder.class); } private int bitField0_; public static final int STATUS_FIELD_NUMBER = 1; private int status_ = 0; /** *
     * Current status of the peer (e.g., connected, disconnected).
     * 
* * int32 status = 1 [json_name = "status"]; * @return The status. */ @java.lang.Override public int getStatus() { return status_; } public static final int MONIKER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object moniker_ = ""; /** *
     * Moniker or Human-Readable name of the peer.
     * 
* * string moniker = 2 [json_name = "moniker"]; * @return The moniker. */ @java.lang.Override public java.lang.String getMoniker() { java.lang.Object ref = moniker_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); moniker_ = s; return s; } } /** *
     * Moniker or Human-Readable name of the peer.
     * 
* * string moniker = 2 [json_name = "moniker"]; * @return The bytes for moniker. */ @java.lang.Override public com.google.protobuf.ByteString getMonikerBytes() { java.lang.Object ref = moniker_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); moniker_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AGENT_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object agent_ = ""; /** *
     * Version and agent details of the peer.
     * 
* * string agent = 3 [json_name = "agent"]; * @return The agent. */ @java.lang.Override public java.lang.String getAgent() { java.lang.Object ref = agent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); agent_ = s; return s; } } /** *
     * Version and agent details of the peer.
     * 
* * string agent = 3 [json_name = "agent"]; * @return The bytes for agent. */ @java.lang.Override public com.google.protobuf.ByteString getAgentBytes() { java.lang.Object ref = agent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); agent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PEER_ID_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object peerId_ = ""; /** *
     * Peer ID of the peer in P2P network.
     * 
* * string peer_id = 4 [json_name = "peerId"]; * @return The peerId. */ @java.lang.Override public java.lang.String getPeerId() { java.lang.Object ref = peerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); peerId_ = s; return s; } } /** *
     * Peer ID of the peer in P2P network.
     * 
* * string peer_id = 4 [json_name = "peerId"]; * @return The bytes for peerId. */ @java.lang.Override public com.google.protobuf.ByteString getPeerIdBytes() { java.lang.Object ref = peerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); peerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONSENSUS_KEYS_FIELD_NUMBER = 5; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList consensusKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return A list containing the consensusKeys. */ public com.google.protobuf.ProtocolStringList getConsensusKeysList() { return consensusKeys_; } /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return The count of consensusKeys. */ public int getConsensusKeysCount() { return consensusKeys_.size(); } /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index of the element to return. * @return The consensusKeys at the given index. */ public java.lang.String getConsensusKeys(int index) { return consensusKeys_.get(index); } /** *
     * List of consensus keys used by the peer.
     * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index of the value to return. * @return The bytes of the consensusKeys at the given index. */ public com.google.protobuf.ByteString getConsensusKeysBytes(int index) { return consensusKeys_.getByteString(index); } public static final int CONSENSUS_ADDRESSES_FIELD_NUMBER = 6; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList consensusAddresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return A list containing the consensusAddresses. */ public com.google.protobuf.ProtocolStringList getConsensusAddressesList() { return consensusAddresses_; } /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return The count of consensusAddresses. */ public int getConsensusAddressesCount() { return consensusAddresses_.size(); } /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index of the element to return. * @return The consensusAddresses at the given index. */ public java.lang.String getConsensusAddresses(int index) { return consensusAddresses_.get(index); } /** *
     * List of consensus addresses used by the peer.
     * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index of the value to return. * @return The bytes of the consensusAddresses at the given index. */ public com.google.protobuf.ByteString getConsensusAddressesBytes(int index) { return consensusAddresses_.getByteString(index); } public static final int SERVICES_FIELD_NUMBER = 7; private int services_ = 0; /** *
     * Bitfield representing the services provided by the peer.
     * 
* * uint32 services = 7 [json_name = "services"]; * @return The services. */ @java.lang.Override public int getServices() { return services_; } public static final int LAST_BLOCK_HASH_FIELD_NUMBER = 8; @SuppressWarnings("serial") private volatile java.lang.Object lastBlockHash_ = ""; /** *
     * Hash of the last block the peer knows.
     * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return The lastBlockHash. */ @java.lang.Override public java.lang.String getLastBlockHash() { java.lang.Object ref = lastBlockHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastBlockHash_ = s; return s; } } /** *
     * Hash of the last block the peer knows.
     * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return The bytes for lastBlockHash. */ @java.lang.Override public com.google.protobuf.ByteString getLastBlockHashBytes() { java.lang.Object ref = lastBlockHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lastBlockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int HEIGHT_FIELD_NUMBER = 9; private int height_ = 0; /** *
     * Blockchain height of the peer.
     * 
* * uint32 height = 9 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } public static final int LAST_SENT_FIELD_NUMBER = 10; private long lastSent_ = 0L; /** *
     * Unix timestamp of the last bundle sent to the peer (UTC).
     * 
* * int64 last_sent = 10 [json_name = "lastSent"]; * @return The lastSent. */ @java.lang.Override public long getLastSent() { return lastSent_; } public static final int LAST_RECEIVED_FIELD_NUMBER = 11; private long lastReceived_ = 0L; /** *
     * Unix timestamp of the last bundle received from the peer (UTC).
     * 
* * int64 last_received = 11 [json_name = "lastReceived"]; * @return The lastReceived. */ @java.lang.Override public long getLastReceived() { return lastReceived_; } public static final int ADDRESS_FIELD_NUMBER = 12; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * Network address of the peer.
     * 
* * string address = 12 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * Network address of the peer.
     * 
* * string address = 12 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DIRECTION_FIELD_NUMBER = 13; private int direction_ = 0; /** *
     * Connection direction (e.g., inbound, outbound).
     * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ @java.lang.Override public int getDirectionValue() { return direction_; } /** *
     * Connection direction (e.g., inbound, outbound).
     * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return The direction. */ @java.lang.Override public pactus.NetworkOuterClass.Direction getDirection() { pactus.NetworkOuterClass.Direction result = pactus.NetworkOuterClass.Direction.forNumber(direction_); return result == null ? pactus.NetworkOuterClass.Direction.UNRECOGNIZED : result; } public static final int PROTOCOLS_FIELD_NUMBER = 14; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return A list containing the protocols. */ public com.google.protobuf.ProtocolStringList getProtocolsList() { return protocols_; } /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return The count of protocols. */ public int getProtocolsCount() { return protocols_.size(); } /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index of the element to return. * @return The protocols at the given index. */ public java.lang.String getProtocols(int index) { return protocols_.get(index); } /** *
     * List of protocols supported by the peer.
     * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index of the value to return. * @return The bytes of the protocols at the given index. */ public com.google.protobuf.ByteString getProtocolsBytes(int index) { return protocols_.getByteString(index); } public static final int TOTAL_SESSIONS_FIELD_NUMBER = 15; private int totalSessions_ = 0; /** *
     * Total download sessions with the peer.
     * 
* * int32 total_sessions = 15 [json_name = "totalSessions"]; * @return The totalSessions. */ @java.lang.Override public int getTotalSessions() { return totalSessions_; } public static final int COMPLETED_SESSIONS_FIELD_NUMBER = 16; private int completedSessions_ = 0; /** *
     * Completed download sessions with the peer.
     * 
* * int32 completed_sessions = 16 [json_name = "completedSessions"]; * @return The completedSessions. */ @java.lang.Override public int getCompletedSessions() { return completedSessions_; } public static final int METRIC_INFO_FIELD_NUMBER = 17; private pactus.NetworkOuterClass.MetricInfo metricInfo_; /** *
     * Metrics related to peer activity.
     * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; * @return Whether the metricInfo field is set. */ @java.lang.Override public boolean hasMetricInfo() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Metrics related to peer activity.
     * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; * @return The metricInfo. */ @java.lang.Override public pactus.NetworkOuterClass.MetricInfo getMetricInfo() { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } /** *
     * Metrics related to peer activity.
     * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ @java.lang.Override public pactus.NetworkOuterClass.MetricInfoOrBuilder getMetricInfoOrBuilder() { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } public static final int OUTBOUND_HELLO_SENT_FIELD_NUMBER = 18; private boolean outboundHelloSent_ = false; /** *
     * Whether the hello message was sent from the outbound connection.
     * 
* * bool outbound_hello_sent = 18 [json_name = "outboundHelloSent"]; * @return The outboundHelloSent. */ @java.lang.Override public boolean getOutboundHelloSent() { return outboundHelloSent_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (status_ != 0) { output.writeInt32(1, status_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(moniker_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, moniker_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(agent_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, agent_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(peerId_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, peerId_); } for (int i = 0; i < consensusKeys_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 5, consensusKeys_.getRaw(i)); } for (int i = 0; i < consensusAddresses_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 6, consensusAddresses_.getRaw(i)); } if (services_ != 0) { output.writeUInt32(7, services_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(lastBlockHash_)) { com.google.protobuf.GeneratedMessage.writeString(output, 8, lastBlockHash_); } if (height_ != 0) { output.writeUInt32(9, height_); } if (lastSent_ != 0L) { output.writeInt64(10, lastSent_); } if (lastReceived_ != 0L) { output.writeInt64(11, lastReceived_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 12, address_); } if (direction_ != pactus.NetworkOuterClass.Direction.DIRECTION_UNKNOWN.getNumber()) { output.writeEnum(13, direction_); } for (int i = 0; i < protocols_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 14, protocols_.getRaw(i)); } if (totalSessions_ != 0) { output.writeInt32(15, totalSessions_); } if (completedSessions_ != 0) { output.writeInt32(16, completedSessions_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(17, getMetricInfo()); } if (outboundHelloSent_ != false) { output.writeBool(18, outboundHelloSent_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (status_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, status_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(moniker_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, moniker_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(agent_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, agent_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(peerId_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, peerId_); } { int dataSize = 0; for (int i = 0; i < consensusKeys_.size(); i++) { dataSize += computeStringSizeNoTag(consensusKeys_.getRaw(i)); } size += dataSize; size += 1 * getConsensusKeysList().size(); } { int dataSize = 0; for (int i = 0; i < consensusAddresses_.size(); i++) { dataSize += computeStringSizeNoTag(consensusAddresses_.getRaw(i)); } size += dataSize; size += 1 * getConsensusAddressesList().size(); } if (services_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(7, services_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(lastBlockHash_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(8, lastBlockHash_); } if (height_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(9, height_); } if (lastSent_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(10, lastSent_); } if (lastReceived_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(11, lastReceived_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(12, address_); } if (direction_ != pactus.NetworkOuterClass.Direction.DIRECTION_UNKNOWN.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(13, direction_); } { int dataSize = 0; for (int i = 0; i < protocols_.size(); i++) { dataSize += computeStringSizeNoTag(protocols_.getRaw(i)); } size += dataSize; size += 1 * getProtocolsList().size(); } if (totalSessions_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(15, totalSessions_); } if (completedSessions_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(16, completedSessions_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(17, getMetricInfo()); } if (outboundHelloSent_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(18, outboundHelloSent_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.PeerInfo)) { return super.equals(obj); } pactus.NetworkOuterClass.PeerInfo other = (pactus.NetworkOuterClass.PeerInfo) obj; if (getStatus() != other.getStatus()) return false; if (!getMoniker() .equals(other.getMoniker())) return false; if (!getAgent() .equals(other.getAgent())) return false; if (!getPeerId() .equals(other.getPeerId())) return false; if (!getConsensusKeysList() .equals(other.getConsensusKeysList())) return false; if (!getConsensusAddressesList() .equals(other.getConsensusAddressesList())) return false; if (getServices() != other.getServices()) return false; if (!getLastBlockHash() .equals(other.getLastBlockHash())) return false; if (getHeight() != other.getHeight()) return false; if (getLastSent() != other.getLastSent()) return false; if (getLastReceived() != other.getLastReceived()) return false; if (!getAddress() .equals(other.getAddress())) return false; if (direction_ != other.direction_) return false; if (!getProtocolsList() .equals(other.getProtocolsList())) return false; if (getTotalSessions() != other.getTotalSessions()) return false; if (getCompletedSessions() != other.getCompletedSessions()) return false; if (hasMetricInfo() != other.hasMetricInfo()) return false; if (hasMetricInfo()) { if (!getMetricInfo() .equals(other.getMetricInfo())) return false; } if (getOutboundHelloSent() != other.getOutboundHelloSent()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + getStatus(); hash = (37 * hash) + MONIKER_FIELD_NUMBER; hash = (53 * hash) + getMoniker().hashCode(); hash = (37 * hash) + AGENT_FIELD_NUMBER; hash = (53 * hash) + getAgent().hashCode(); hash = (37 * hash) + PEER_ID_FIELD_NUMBER; hash = (53 * hash) + getPeerId().hashCode(); if (getConsensusKeysCount() > 0) { hash = (37 * hash) + CONSENSUS_KEYS_FIELD_NUMBER; hash = (53 * hash) + getConsensusKeysList().hashCode(); } if (getConsensusAddressesCount() > 0) { hash = (37 * hash) + CONSENSUS_ADDRESSES_FIELD_NUMBER; hash = (53 * hash) + getConsensusAddressesList().hashCode(); } hash = (37 * hash) + SERVICES_FIELD_NUMBER; hash = (53 * hash) + getServices(); hash = (37 * hash) + LAST_BLOCK_HASH_FIELD_NUMBER; hash = (53 * hash) + getLastBlockHash().hashCode(); hash = (37 * hash) + HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getHeight(); hash = (37 * hash) + LAST_SENT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastSent()); hash = (37 * hash) + LAST_RECEIVED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastReceived()); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + DIRECTION_FIELD_NUMBER; hash = (53 * hash) + direction_; if (getProtocolsCount() > 0) { hash = (37 * hash) + PROTOCOLS_FIELD_NUMBER; hash = (53 * hash) + getProtocolsList().hashCode(); } hash = (37 * hash) + TOTAL_SESSIONS_FIELD_NUMBER; hash = (53 * hash) + getTotalSessions(); hash = (37 * hash) + COMPLETED_SESSIONS_FIELD_NUMBER; hash = (53 * hash) + getCompletedSessions(); if (hasMetricInfo()) { hash = (37 * hash) + METRIC_INFO_FIELD_NUMBER; hash = (53 * hash) + getMetricInfo().hashCode(); } hash = (37 * hash) + OUTBOUND_HELLO_SENT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getOutboundHelloSent()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.PeerInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PeerInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PeerInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.PeerInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PeerInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PeerInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.PeerInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * PeerInfo contains information about a peer in the network.
     * 
* * Protobuf type {@code pactus.PeerInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PeerInfo) pactus.NetworkOuterClass.PeerInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_PeerInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_PeerInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.PeerInfo.class, pactus.NetworkOuterClass.PeerInfo.Builder.class); } // Construct using pactus.NetworkOuterClass.PeerInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetMetricInfoFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; status_ = 0; moniker_ = ""; agent_ = ""; peerId_ = ""; consensusKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); consensusAddresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); services_ = 0; lastBlockHash_ = ""; height_ = 0; lastSent_ = 0L; lastReceived_ = 0L; address_ = ""; direction_ = 0; protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); totalSessions_ = 0; completedSessions_ = 0; metricInfo_ = null; if (metricInfoBuilder_ != null) { metricInfoBuilder_.dispose(); metricInfoBuilder_ = null; } outboundHelloSent_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_PeerInfo_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.PeerInfo getDefaultInstanceForType() { return pactus.NetworkOuterClass.PeerInfo.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.PeerInfo build() { pactus.NetworkOuterClass.PeerInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.PeerInfo buildPartial() { pactus.NetworkOuterClass.PeerInfo result = new pactus.NetworkOuterClass.PeerInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.PeerInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.status_ = status_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.moniker_ = moniker_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.agent_ = agent_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.peerId_ = peerId_; } if (((from_bitField0_ & 0x00000010) != 0)) { consensusKeys_.makeImmutable(); result.consensusKeys_ = consensusKeys_; } if (((from_bitField0_ & 0x00000020) != 0)) { consensusAddresses_.makeImmutable(); result.consensusAddresses_ = consensusAddresses_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.services_ = services_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.lastBlockHash_ = lastBlockHash_; } if (((from_bitField0_ & 0x00000100) != 0)) { result.height_ = height_; } if (((from_bitField0_ & 0x00000200) != 0)) { result.lastSent_ = lastSent_; } if (((from_bitField0_ & 0x00000400) != 0)) { result.lastReceived_ = lastReceived_; } if (((from_bitField0_ & 0x00000800) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00001000) != 0)) { result.direction_ = direction_; } if (((from_bitField0_ & 0x00002000) != 0)) { protocols_.makeImmutable(); result.protocols_ = protocols_; } if (((from_bitField0_ & 0x00004000) != 0)) { result.totalSessions_ = totalSessions_; } if (((from_bitField0_ & 0x00008000) != 0)) { result.completedSessions_ = completedSessions_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00010000) != 0)) { result.metricInfo_ = metricInfoBuilder_ == null ? metricInfo_ : metricInfoBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00020000) != 0)) { result.outboundHelloSent_ = outboundHelloSent_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.PeerInfo) { return mergeFrom((pactus.NetworkOuterClass.PeerInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.PeerInfo other) { if (other == pactus.NetworkOuterClass.PeerInfo.getDefaultInstance()) return this; if (other.getStatus() != 0) { setStatus(other.getStatus()); } if (!other.getMoniker().isEmpty()) { moniker_ = other.moniker_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAgent().isEmpty()) { agent_ = other.agent_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getPeerId().isEmpty()) { peerId_ = other.peerId_; bitField0_ |= 0x00000008; onChanged(); } if (!other.consensusKeys_.isEmpty()) { if (consensusKeys_.isEmpty()) { consensusKeys_ = other.consensusKeys_; bitField0_ |= 0x00000010; } else { ensureConsensusKeysIsMutable(); consensusKeys_.addAll(other.consensusKeys_); } onChanged(); } if (!other.consensusAddresses_.isEmpty()) { if (consensusAddresses_.isEmpty()) { consensusAddresses_ = other.consensusAddresses_; bitField0_ |= 0x00000020; } else { ensureConsensusAddressesIsMutable(); consensusAddresses_.addAll(other.consensusAddresses_); } onChanged(); } if (other.getServices() != 0) { setServices(other.getServices()); } if (!other.getLastBlockHash().isEmpty()) { lastBlockHash_ = other.lastBlockHash_; bitField0_ |= 0x00000080; onChanged(); } if (other.getHeight() != 0) { setHeight(other.getHeight()); } if (other.getLastSent() != 0L) { setLastSent(other.getLastSent()); } if (other.getLastReceived() != 0L) { setLastReceived(other.getLastReceived()); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000800; onChanged(); } if (other.direction_ != 0) { setDirectionValue(other.getDirectionValue()); } if (!other.protocols_.isEmpty()) { if (protocols_.isEmpty()) { protocols_ = other.protocols_; bitField0_ |= 0x00002000; } else { ensureProtocolsIsMutable(); protocols_.addAll(other.protocols_); } onChanged(); } if (other.getTotalSessions() != 0) { setTotalSessions(other.getTotalSessions()); } if (other.getCompletedSessions() != 0) { setCompletedSessions(other.getCompletedSessions()); } if (other.hasMetricInfo()) { mergeMetricInfo(other.getMetricInfo()); } if (other.getOutboundHelloSent() != false) { setOutboundHelloSent(other.getOutboundHelloSent()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { status_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { moniker_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { agent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { peerId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 42: { java.lang.String s = input.readStringRequireUtf8(); ensureConsensusKeysIsMutable(); consensusKeys_.add(s); break; } // case 42 case 50: { java.lang.String s = input.readStringRequireUtf8(); ensureConsensusAddressesIsMutable(); consensusAddresses_.add(s); break; } // case 50 case 56: { services_ = input.readUInt32(); bitField0_ |= 0x00000040; break; } // case 56 case 66: { lastBlockHash_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000080; break; } // case 66 case 72: { height_ = input.readUInt32(); bitField0_ |= 0x00000100; break; } // case 72 case 80: { lastSent_ = input.readInt64(); bitField0_ |= 0x00000200; break; } // case 80 case 88: { lastReceived_ = input.readInt64(); bitField0_ |= 0x00000400; break; } // case 88 case 98: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000800; break; } // case 98 case 104: { direction_ = input.readEnum(); bitField0_ |= 0x00001000; break; } // case 104 case 114: { java.lang.String s = input.readStringRequireUtf8(); ensureProtocolsIsMutable(); protocols_.add(s); break; } // case 114 case 120: { totalSessions_ = input.readInt32(); bitField0_ |= 0x00004000; break; } // case 120 case 128: { completedSessions_ = input.readInt32(); bitField0_ |= 0x00008000; break; } // case 128 case 138: { input.readMessage( internalGetMetricInfoFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00010000; break; } // case 138 case 144: { outboundHelloSent_ = input.readBool(); bitField0_ |= 0x00020000; break; } // case 144 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int status_ ; /** *
       * Current status of the peer (e.g., connected, disconnected).
       * 
* * int32 status = 1 [json_name = "status"]; * @return The status. */ @java.lang.Override public int getStatus() { return status_; } /** *
       * Current status of the peer (e.g., connected, disconnected).
       * 
* * int32 status = 1 [json_name = "status"]; * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(int value) { status_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Current status of the peer (e.g., connected, disconnected).
       * 
* * int32 status = 1 [json_name = "status"]; * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000001); status_ = 0; onChanged(); return this; } private java.lang.Object moniker_ = ""; /** *
       * Moniker or Human-Readable name of the peer.
       * 
* * string moniker = 2 [json_name = "moniker"]; * @return The moniker. */ public java.lang.String getMoniker() { java.lang.Object ref = moniker_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); moniker_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Moniker or Human-Readable name of the peer.
       * 
* * string moniker = 2 [json_name = "moniker"]; * @return The bytes for moniker. */ public com.google.protobuf.ByteString getMonikerBytes() { java.lang.Object ref = moniker_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); moniker_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Moniker or Human-Readable name of the peer.
       * 
* * string moniker = 2 [json_name = "moniker"]; * @param value The moniker to set. * @return This builder for chaining. */ public Builder setMoniker( java.lang.String value) { if (value == null) { throw new NullPointerException(); } moniker_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Moniker or Human-Readable name of the peer.
       * 
* * string moniker = 2 [json_name = "moniker"]; * @return This builder for chaining. */ public Builder clearMoniker() { moniker_ = getDefaultInstance().getMoniker(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Moniker or Human-Readable name of the peer.
       * 
* * string moniker = 2 [json_name = "moniker"]; * @param value The bytes for moniker to set. * @return This builder for chaining. */ public Builder setMonikerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); moniker_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object agent_ = ""; /** *
       * Version and agent details of the peer.
       * 
* * string agent = 3 [json_name = "agent"]; * @return The agent. */ public java.lang.String getAgent() { java.lang.Object ref = agent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); agent_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Version and agent details of the peer.
       * 
* * string agent = 3 [json_name = "agent"]; * @return The bytes for agent. */ public com.google.protobuf.ByteString getAgentBytes() { java.lang.Object ref = agent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); agent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Version and agent details of the peer.
       * 
* * string agent = 3 [json_name = "agent"]; * @param value The agent to set. * @return This builder for chaining. */ public Builder setAgent( java.lang.String value) { if (value == null) { throw new NullPointerException(); } agent_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Version and agent details of the peer.
       * 
* * string agent = 3 [json_name = "agent"]; * @return This builder for chaining. */ public Builder clearAgent() { agent_ = getDefaultInstance().getAgent(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * Version and agent details of the peer.
       * 
* * string agent = 3 [json_name = "agent"]; * @param value The bytes for agent to set. * @return This builder for chaining. */ public Builder setAgentBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); agent_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object peerId_ = ""; /** *
       * Peer ID of the peer in P2P network.
       * 
* * string peer_id = 4 [json_name = "peerId"]; * @return The peerId. */ public java.lang.String getPeerId() { java.lang.Object ref = peerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); peerId_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Peer ID of the peer in P2P network.
       * 
* * string peer_id = 4 [json_name = "peerId"]; * @return The bytes for peerId. */ public com.google.protobuf.ByteString getPeerIdBytes() { java.lang.Object ref = peerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); peerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Peer ID of the peer in P2P network.
       * 
* * string peer_id = 4 [json_name = "peerId"]; * @param value The peerId to set. * @return This builder for chaining. */ public Builder setPeerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } peerId_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * Peer ID of the peer in P2P network.
       * 
* * string peer_id = 4 [json_name = "peerId"]; * @return This builder for chaining. */ public Builder clearPeerId() { peerId_ = getDefaultInstance().getPeerId(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * Peer ID of the peer in P2P network.
       * 
* * string peer_id = 4 [json_name = "peerId"]; * @param value The bytes for peerId to set. * @return This builder for chaining. */ public Builder setPeerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); peerId_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList consensusKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureConsensusKeysIsMutable() { if (!consensusKeys_.isModifiable()) { consensusKeys_ = new com.google.protobuf.LazyStringArrayList(consensusKeys_); } bitField0_ |= 0x00000010; } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return A list containing the consensusKeys. */ public com.google.protobuf.ProtocolStringList getConsensusKeysList() { consensusKeys_.makeImmutable(); return consensusKeys_; } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return The count of consensusKeys. */ public int getConsensusKeysCount() { return consensusKeys_.size(); } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index of the element to return. * @return The consensusKeys at the given index. */ public java.lang.String getConsensusKeys(int index) { return consensusKeys_.get(index); } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index of the value to return. * @return The bytes of the consensusKeys at the given index. */ public com.google.protobuf.ByteString getConsensusKeysBytes(int index) { return consensusKeys_.getByteString(index); } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param index The index to set the value at. * @param value The consensusKeys to set. * @return This builder for chaining. */ public Builder setConsensusKeys( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureConsensusKeysIsMutable(); consensusKeys_.set(index, value); bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param value The consensusKeys to add. * @return This builder for chaining. */ public Builder addConsensusKeys( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureConsensusKeysIsMutable(); consensusKeys_.add(value); bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param values The consensusKeys to add. * @return This builder for chaining. */ public Builder addAllConsensusKeys( java.lang.Iterable values) { ensureConsensusKeysIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, consensusKeys_); bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @return This builder for chaining. */ public Builder clearConsensusKeys() { consensusKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000010);; onChanged(); return this; } /** *
       * List of consensus keys used by the peer.
       * 
* * repeated string consensus_keys = 5 [json_name = "consensusKeys"]; * @param value The bytes of the consensusKeys to add. * @return This builder for chaining. */ public Builder addConsensusKeysBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureConsensusKeysIsMutable(); consensusKeys_.add(value); bitField0_ |= 0x00000010; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList consensusAddresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureConsensusAddressesIsMutable() { if (!consensusAddresses_.isModifiable()) { consensusAddresses_ = new com.google.protobuf.LazyStringArrayList(consensusAddresses_); } bitField0_ |= 0x00000020; } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return A list containing the consensusAddresses. */ public com.google.protobuf.ProtocolStringList getConsensusAddressesList() { consensusAddresses_.makeImmutable(); return consensusAddresses_; } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return The count of consensusAddresses. */ public int getConsensusAddressesCount() { return consensusAddresses_.size(); } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index of the element to return. * @return The consensusAddresses at the given index. */ public java.lang.String getConsensusAddresses(int index) { return consensusAddresses_.get(index); } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index of the value to return. * @return The bytes of the consensusAddresses at the given index. */ public com.google.protobuf.ByteString getConsensusAddressesBytes(int index) { return consensusAddresses_.getByteString(index); } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param index The index to set the value at. * @param value The consensusAddresses to set. * @return This builder for chaining. */ public Builder setConsensusAddresses( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureConsensusAddressesIsMutable(); consensusAddresses_.set(index, value); bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param value The consensusAddresses to add. * @return This builder for chaining. */ public Builder addConsensusAddresses( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureConsensusAddressesIsMutable(); consensusAddresses_.add(value); bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param values The consensusAddresses to add. * @return This builder for chaining. */ public Builder addAllConsensusAddresses( java.lang.Iterable values) { ensureConsensusAddressesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, consensusAddresses_); bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @return This builder for chaining. */ public Builder clearConsensusAddresses() { consensusAddresses_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000020);; onChanged(); return this; } /** *
       * List of consensus addresses used by the peer.
       * 
* * repeated string consensus_addresses = 6 [json_name = "consensusAddresses"]; * @param value The bytes of the consensusAddresses to add. * @return This builder for chaining. */ public Builder addConsensusAddressesBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureConsensusAddressesIsMutable(); consensusAddresses_.add(value); bitField0_ |= 0x00000020; onChanged(); return this; } private int services_ ; /** *
       * Bitfield representing the services provided by the peer.
       * 
* * uint32 services = 7 [json_name = "services"]; * @return The services. */ @java.lang.Override public int getServices() { return services_; } /** *
       * Bitfield representing the services provided by the peer.
       * 
* * uint32 services = 7 [json_name = "services"]; * @param value The services to set. * @return This builder for chaining. */ public Builder setServices(int value) { services_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * Bitfield representing the services provided by the peer.
       * 
* * uint32 services = 7 [json_name = "services"]; * @return This builder for chaining. */ public Builder clearServices() { bitField0_ = (bitField0_ & ~0x00000040); services_ = 0; onChanged(); return this; } private java.lang.Object lastBlockHash_ = ""; /** *
       * Hash of the last block the peer knows.
       * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return The lastBlockHash. */ public java.lang.String getLastBlockHash() { java.lang.Object ref = lastBlockHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastBlockHash_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Hash of the last block the peer knows.
       * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return The bytes for lastBlockHash. */ public com.google.protobuf.ByteString getLastBlockHashBytes() { java.lang.Object ref = lastBlockHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lastBlockHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Hash of the last block the peer knows.
       * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @param value The lastBlockHash to set. * @return This builder for chaining. */ public Builder setLastBlockHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } lastBlockHash_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * Hash of the last block the peer knows.
       * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @return This builder for chaining. */ public Builder clearLastBlockHash() { lastBlockHash_ = getDefaultInstance().getLastBlockHash(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); return this; } /** *
       * Hash of the last block the peer knows.
       * 
* * string last_block_hash = 8 [json_name = "lastBlockHash"]; * @param value The bytes for lastBlockHash to set. * @return This builder for chaining. */ public Builder setLastBlockHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); lastBlockHash_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } private int height_ ; /** *
       * Blockchain height of the peer.
       * 
* * uint32 height = 9 [json_name = "height"]; * @return The height. */ @java.lang.Override public int getHeight() { return height_; } /** *
       * Blockchain height of the peer.
       * 
* * uint32 height = 9 [json_name = "height"]; * @param value The height to set. * @return This builder for chaining. */ public Builder setHeight(int value) { height_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * Blockchain height of the peer.
       * 
* * uint32 height = 9 [json_name = "height"]; * @return This builder for chaining. */ public Builder clearHeight() { bitField0_ = (bitField0_ & ~0x00000100); height_ = 0; onChanged(); return this; } private long lastSent_ ; /** *
       * Unix timestamp of the last bundle sent to the peer (UTC).
       * 
* * int64 last_sent = 10 [json_name = "lastSent"]; * @return The lastSent. */ @java.lang.Override public long getLastSent() { return lastSent_; } /** *
       * Unix timestamp of the last bundle sent to the peer (UTC).
       * 
* * int64 last_sent = 10 [json_name = "lastSent"]; * @param value The lastSent to set. * @return This builder for chaining. */ public Builder setLastSent(long value) { lastSent_ = value; bitField0_ |= 0x00000200; onChanged(); return this; } /** *
       * Unix timestamp of the last bundle sent to the peer (UTC).
       * 
* * int64 last_sent = 10 [json_name = "lastSent"]; * @return This builder for chaining. */ public Builder clearLastSent() { bitField0_ = (bitField0_ & ~0x00000200); lastSent_ = 0L; onChanged(); return this; } private long lastReceived_ ; /** *
       * Unix timestamp of the last bundle received from the peer (UTC).
       * 
* * int64 last_received = 11 [json_name = "lastReceived"]; * @return The lastReceived. */ @java.lang.Override public long getLastReceived() { return lastReceived_; } /** *
       * Unix timestamp of the last bundle received from the peer (UTC).
       * 
* * int64 last_received = 11 [json_name = "lastReceived"]; * @param value The lastReceived to set. * @return This builder for chaining. */ public Builder setLastReceived(long value) { lastReceived_ = value; bitField0_ |= 0x00000400; onChanged(); return this; } /** *
       * Unix timestamp of the last bundle received from the peer (UTC).
       * 
* * int64 last_received = 11 [json_name = "lastReceived"]; * @return This builder for chaining. */ public Builder clearLastReceived() { bitField0_ = (bitField0_ & ~0x00000400); lastReceived_ = 0L; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * Network address of the peer.
       * 
* * string address = 12 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Network address of the peer.
       * 
* * string address = 12 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Network address of the peer.
       * 
* * string address = 12 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000800; onChanged(); return this; } /** *
       * Network address of the peer.
       * 
* * string address = 12 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000800); onChanged(); return this; } /** *
       * Network address of the peer.
       * 
* * string address = 12 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000800; onChanged(); return this; } private int direction_ = 0; /** *
       * Connection direction (e.g., inbound, outbound).
       * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ @java.lang.Override public int getDirectionValue() { return direction_; } /** *
       * Connection direction (e.g., inbound, outbound).
       * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @param value The enum numeric value on the wire for direction to set. * @return This builder for chaining. */ public Builder setDirectionValue(int value) { direction_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } /** *
       * Connection direction (e.g., inbound, outbound).
       * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return The direction. */ @java.lang.Override public pactus.NetworkOuterClass.Direction getDirection() { pactus.NetworkOuterClass.Direction result = pactus.NetworkOuterClass.Direction.forNumber(direction_); return result == null ? pactus.NetworkOuterClass.Direction.UNRECOGNIZED : result; } /** *
       * Connection direction (e.g., inbound, outbound).
       * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @param value The direction to set. * @return This builder for chaining. */ public Builder setDirection(pactus.NetworkOuterClass.Direction value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00001000; direction_ = value.getNumber(); onChanged(); return this; } /** *
       * Connection direction (e.g., inbound, outbound).
       * 
* * .pactus.Direction direction = 13 [json_name = "direction"]; * @return This builder for chaining. */ public Builder clearDirection() { bitField0_ = (bitField0_ & ~0x00001000); direction_ = 0; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureProtocolsIsMutable() { if (!protocols_.isModifiable()) { protocols_ = new com.google.protobuf.LazyStringArrayList(protocols_); } bitField0_ |= 0x00002000; } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return A list containing the protocols. */ public com.google.protobuf.ProtocolStringList getProtocolsList() { protocols_.makeImmutable(); return protocols_; } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return The count of protocols. */ public int getProtocolsCount() { return protocols_.size(); } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index of the element to return. * @return The protocols at the given index. */ public java.lang.String getProtocols(int index) { return protocols_.get(index); } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index of the value to return. * @return The bytes of the protocols at the given index. */ public com.google.protobuf.ByteString getProtocolsBytes(int index) { return protocols_.getByteString(index); } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param index The index to set the value at. * @param value The protocols to set. * @return This builder for chaining. */ public Builder setProtocols( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProtocolsIsMutable(); protocols_.set(index, value); bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param value The protocols to add. * @return This builder for chaining. */ public Builder addProtocols( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProtocolsIsMutable(); protocols_.add(value); bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param values The protocols to add. * @return This builder for chaining. */ public Builder addAllProtocols( java.lang.Iterable values) { ensureProtocolsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, protocols_); bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @return This builder for chaining. */ public Builder clearProtocols() { protocols_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00002000);; onChanged(); return this; } /** *
       * List of protocols supported by the peer.
       * 
* * repeated string protocols = 14 [json_name = "protocols"]; * @param value The bytes of the protocols to add. * @return This builder for chaining. */ public Builder addProtocolsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureProtocolsIsMutable(); protocols_.add(value); bitField0_ |= 0x00002000; onChanged(); return this; } private int totalSessions_ ; /** *
       * Total download sessions with the peer.
       * 
* * int32 total_sessions = 15 [json_name = "totalSessions"]; * @return The totalSessions. */ @java.lang.Override public int getTotalSessions() { return totalSessions_; } /** *
       * Total download sessions with the peer.
       * 
* * int32 total_sessions = 15 [json_name = "totalSessions"]; * @param value The totalSessions to set. * @return This builder for chaining. */ public Builder setTotalSessions(int value) { totalSessions_ = value; bitField0_ |= 0x00004000; onChanged(); return this; } /** *
       * Total download sessions with the peer.
       * 
* * int32 total_sessions = 15 [json_name = "totalSessions"]; * @return This builder for chaining. */ public Builder clearTotalSessions() { bitField0_ = (bitField0_ & ~0x00004000); totalSessions_ = 0; onChanged(); return this; } private int completedSessions_ ; /** *
       * Completed download sessions with the peer.
       * 
* * int32 completed_sessions = 16 [json_name = "completedSessions"]; * @return The completedSessions. */ @java.lang.Override public int getCompletedSessions() { return completedSessions_; } /** *
       * Completed download sessions with the peer.
       * 
* * int32 completed_sessions = 16 [json_name = "completedSessions"]; * @param value The completedSessions to set. * @return This builder for chaining. */ public Builder setCompletedSessions(int value) { completedSessions_ = value; bitField0_ |= 0x00008000; onChanged(); return this; } /** *
       * Completed download sessions with the peer.
       * 
* * int32 completed_sessions = 16 [json_name = "completedSessions"]; * @return This builder for chaining. */ public Builder clearCompletedSessions() { bitField0_ = (bitField0_ & ~0x00008000); completedSessions_ = 0; onChanged(); return this; } private pactus.NetworkOuterClass.MetricInfo metricInfo_; private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.MetricInfo, pactus.NetworkOuterClass.MetricInfo.Builder, pactus.NetworkOuterClass.MetricInfoOrBuilder> metricInfoBuilder_; /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; * @return Whether the metricInfo field is set. */ public boolean hasMetricInfo() { return ((bitField0_ & 0x00010000) != 0); } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; * @return The metricInfo. */ public pactus.NetworkOuterClass.MetricInfo getMetricInfo() { if (metricInfoBuilder_ == null) { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } else { return metricInfoBuilder_.getMessage(); } } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ public Builder setMetricInfo(pactus.NetworkOuterClass.MetricInfo value) { if (metricInfoBuilder_ == null) { if (value == null) { throw new NullPointerException(); } metricInfo_ = value; } else { metricInfoBuilder_.setMessage(value); } bitField0_ |= 0x00010000; onChanged(); return this; } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ public Builder setMetricInfo( pactus.NetworkOuterClass.MetricInfo.Builder builderForValue) { if (metricInfoBuilder_ == null) { metricInfo_ = builderForValue.build(); } else { metricInfoBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00010000; onChanged(); return this; } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ public Builder mergeMetricInfo(pactus.NetworkOuterClass.MetricInfo value) { if (metricInfoBuilder_ == null) { if (((bitField0_ & 0x00010000) != 0) && metricInfo_ != null && metricInfo_ != pactus.NetworkOuterClass.MetricInfo.getDefaultInstance()) { getMetricInfoBuilder().mergeFrom(value); } else { metricInfo_ = value; } } else { metricInfoBuilder_.mergeFrom(value); } if (metricInfo_ != null) { bitField0_ |= 0x00010000; onChanged(); } return this; } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ public Builder clearMetricInfo() { bitField0_ = (bitField0_ & ~0x00010000); metricInfo_ = null; if (metricInfoBuilder_ != null) { metricInfoBuilder_.dispose(); metricInfoBuilder_ = null; } onChanged(); return this; } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ public pactus.NetworkOuterClass.MetricInfo.Builder getMetricInfoBuilder() { bitField0_ |= 0x00010000; onChanged(); return internalGetMetricInfoFieldBuilder().getBuilder(); } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ public pactus.NetworkOuterClass.MetricInfoOrBuilder getMetricInfoOrBuilder() { if (metricInfoBuilder_ != null) { return metricInfoBuilder_.getMessageOrBuilder(); } else { return metricInfo_ == null ? pactus.NetworkOuterClass.MetricInfo.getDefaultInstance() : metricInfo_; } } /** *
       * Metrics related to peer activity.
       * 
* * .pactus.MetricInfo metric_info = 17 [json_name = "metricInfo"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.MetricInfo, pactus.NetworkOuterClass.MetricInfo.Builder, pactus.NetworkOuterClass.MetricInfoOrBuilder> internalGetMetricInfoFieldBuilder() { if (metricInfoBuilder_ == null) { metricInfoBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.MetricInfo, pactus.NetworkOuterClass.MetricInfo.Builder, pactus.NetworkOuterClass.MetricInfoOrBuilder>( getMetricInfo(), getParentForChildren(), isClean()); metricInfo_ = null; } return metricInfoBuilder_; } private boolean outboundHelloSent_ ; /** *
       * Whether the hello message was sent from the outbound connection.
       * 
* * bool outbound_hello_sent = 18 [json_name = "outboundHelloSent"]; * @return The outboundHelloSent. */ @java.lang.Override public boolean getOutboundHelloSent() { return outboundHelloSent_; } /** *
       * Whether the hello message was sent from the outbound connection.
       * 
* * bool outbound_hello_sent = 18 [json_name = "outboundHelloSent"]; * @param value The outboundHelloSent to set. * @return This builder for chaining. */ public Builder setOutboundHelloSent(boolean value) { outboundHelloSent_ = value; bitField0_ |= 0x00020000; onChanged(); return this; } /** *
       * Whether the hello message was sent from the outbound connection.
       * 
* * bool outbound_hello_sent = 18 [json_name = "outboundHelloSent"]; * @return This builder for chaining. */ public Builder clearOutboundHelloSent() { bitField0_ = (bitField0_ & ~0x00020000); outboundHelloSent_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PeerInfo) } // @@protoc_insertion_point(class_scope:pactus.PeerInfo) private static final pactus.NetworkOuterClass.PeerInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.PeerInfo(); } public static pactus.NetworkOuterClass.PeerInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PeerInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.PeerInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ConnectionInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ConnectionInfo) com.google.protobuf.MessageOrBuilder { /** *
     * Total number of connections.
     * 
* * uint64 connections = 1 [json_name = "connections"]; * @return The connections. */ long getConnections(); /** *
     * Number of inbound connections.
     * 
* * uint64 inbound_connections = 2 [json_name = "inboundConnections"]; * @return The inboundConnections. */ long getInboundConnections(); /** *
     * Number of outbound connections.
     * 
* * uint64 outbound_connections = 3 [json_name = "outboundConnections"]; * @return The outboundConnections. */ long getOutboundConnections(); } /** *
   * ConnectionInfo contains information about the node's connections.
   * 
* * Protobuf type {@code pactus.ConnectionInfo} */ public static final class ConnectionInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ConnectionInfo) ConnectionInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ConnectionInfo"); } // Use ConnectionInfo.newBuilder() to construct. private ConnectionInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ConnectionInfo() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ConnectionInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ConnectionInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ConnectionInfo.class, pactus.NetworkOuterClass.ConnectionInfo.Builder.class); } public static final int CONNECTIONS_FIELD_NUMBER = 1; private long connections_ = 0L; /** *
     * Total number of connections.
     * 
* * uint64 connections = 1 [json_name = "connections"]; * @return The connections. */ @java.lang.Override public long getConnections() { return connections_; } public static final int INBOUND_CONNECTIONS_FIELD_NUMBER = 2; private long inboundConnections_ = 0L; /** *
     * Number of inbound connections.
     * 
* * uint64 inbound_connections = 2 [json_name = "inboundConnections"]; * @return The inboundConnections. */ @java.lang.Override public long getInboundConnections() { return inboundConnections_; } public static final int OUTBOUND_CONNECTIONS_FIELD_NUMBER = 3; private long outboundConnections_ = 0L; /** *
     * Number of outbound connections.
     * 
* * uint64 outbound_connections = 3 [json_name = "outboundConnections"]; * @return The outboundConnections. */ @java.lang.Override public long getOutboundConnections() { return outboundConnections_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (connections_ != 0L) { output.writeUInt64(1, connections_); } if (inboundConnections_ != 0L) { output.writeUInt64(2, inboundConnections_); } if (outboundConnections_ != 0L) { output.writeUInt64(3, outboundConnections_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (connections_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, connections_); } if (inboundConnections_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(2, inboundConnections_); } if (outboundConnections_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, outboundConnections_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.ConnectionInfo)) { return super.equals(obj); } pactus.NetworkOuterClass.ConnectionInfo other = (pactus.NetworkOuterClass.ConnectionInfo) obj; if (getConnections() != other.getConnections()) return false; if (getInboundConnections() != other.getInboundConnections()) return false; if (getOutboundConnections() != other.getOutboundConnections()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CONNECTIONS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getConnections()); hash = (37 * hash) + INBOUND_CONNECTIONS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getInboundConnections()); hash = (37 * hash) + OUTBOUND_CONNECTIONS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getOutboundConnections()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ConnectionInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ConnectionInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.ConnectionInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.ConnectionInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * ConnectionInfo contains information about the node's connections.
     * 
* * Protobuf type {@code pactus.ConnectionInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ConnectionInfo) pactus.NetworkOuterClass.ConnectionInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_ConnectionInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_ConnectionInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.ConnectionInfo.class, pactus.NetworkOuterClass.ConnectionInfo.Builder.class); } // Construct using pactus.NetworkOuterClass.ConnectionInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; connections_ = 0L; inboundConnections_ = 0L; outboundConnections_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_ConnectionInfo_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.ConnectionInfo getDefaultInstanceForType() { return pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.ConnectionInfo build() { pactus.NetworkOuterClass.ConnectionInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.ConnectionInfo buildPartial() { pactus.NetworkOuterClass.ConnectionInfo result = new pactus.NetworkOuterClass.ConnectionInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.ConnectionInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.connections_ = connections_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.inboundConnections_ = inboundConnections_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.outboundConnections_ = outboundConnections_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.ConnectionInfo) { return mergeFrom((pactus.NetworkOuterClass.ConnectionInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.ConnectionInfo other) { if (other == pactus.NetworkOuterClass.ConnectionInfo.getDefaultInstance()) return this; if (other.getConnections() != 0L) { setConnections(other.getConnections()); } if (other.getInboundConnections() != 0L) { setInboundConnections(other.getInboundConnections()); } if (other.getOutboundConnections() != 0L) { setOutboundConnections(other.getOutboundConnections()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { connections_ = input.readUInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { inboundConnections_ = input.readUInt64(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { outboundConnections_ = input.readUInt64(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private long connections_ ; /** *
       * Total number of connections.
       * 
* * uint64 connections = 1 [json_name = "connections"]; * @return The connections. */ @java.lang.Override public long getConnections() { return connections_; } /** *
       * Total number of connections.
       * 
* * uint64 connections = 1 [json_name = "connections"]; * @param value The connections to set. * @return This builder for chaining. */ public Builder setConnections(long value) { connections_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Total number of connections.
       * 
* * uint64 connections = 1 [json_name = "connections"]; * @return This builder for chaining. */ public Builder clearConnections() { bitField0_ = (bitField0_ & ~0x00000001); connections_ = 0L; onChanged(); return this; } private long inboundConnections_ ; /** *
       * Number of inbound connections.
       * 
* * uint64 inbound_connections = 2 [json_name = "inboundConnections"]; * @return The inboundConnections. */ @java.lang.Override public long getInboundConnections() { return inboundConnections_; } /** *
       * Number of inbound connections.
       * 
* * uint64 inbound_connections = 2 [json_name = "inboundConnections"]; * @param value The inboundConnections to set. * @return This builder for chaining. */ public Builder setInboundConnections(long value) { inboundConnections_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Number of inbound connections.
       * 
* * uint64 inbound_connections = 2 [json_name = "inboundConnections"]; * @return This builder for chaining. */ public Builder clearInboundConnections() { bitField0_ = (bitField0_ & ~0x00000002); inboundConnections_ = 0L; onChanged(); return this; } private long outboundConnections_ ; /** *
       * Number of outbound connections.
       * 
* * uint64 outbound_connections = 3 [json_name = "outboundConnections"]; * @return The outboundConnections. */ @java.lang.Override public long getOutboundConnections() { return outboundConnections_; } /** *
       * Number of outbound connections.
       * 
* * uint64 outbound_connections = 3 [json_name = "outboundConnections"]; * @param value The outboundConnections to set. * @return This builder for chaining. */ public Builder setOutboundConnections(long value) { outboundConnections_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Number of outbound connections.
       * 
* * uint64 outbound_connections = 3 [json_name = "outboundConnections"]; * @return This builder for chaining. */ public Builder clearOutboundConnections() { bitField0_ = (bitField0_ & ~0x00000004); outboundConnections_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ConnectionInfo) } // @@protoc_insertion_point(class_scope:pactus.ConnectionInfo) private static final pactus.NetworkOuterClass.ConnectionInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.ConnectionInfo(); } public static pactus.NetworkOuterClass.ConnectionInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ConnectionInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.ConnectionInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MetricInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.MetricInfo) com.google.protobuf.MessageOrBuilder { /** *
     * Total number of invalid bundles.
     * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; * @return Whether the totalInvalid field is set. */ boolean hasTotalInvalid(); /** *
     * Total number of invalid bundles.
     * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; * @return The totalInvalid. */ pactus.NetworkOuterClass.CounterInfo getTotalInvalid(); /** *
     * Total number of invalid bundles.
     * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalInvalidOrBuilder(); /** *
     * Total number of bundles sent.
     * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; * @return Whether the totalSent field is set. */ boolean hasTotalSent(); /** *
     * Total number of bundles sent.
     * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; * @return The totalSent. */ pactus.NetworkOuterClass.CounterInfo getTotalSent(); /** *
     * Total number of bundles sent.
     * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalSentOrBuilder(); /** *
     * Total number of bundles received.
     * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; * @return Whether the totalReceived field is set. */ boolean hasTotalReceived(); /** *
     * Total number of bundles received.
     * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; * @return The totalReceived. */ pactus.NetworkOuterClass.CounterInfo getTotalReceived(); /** *
     * Total number of bundles received.
     * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalReceivedOrBuilder(); /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ int getMessageSentCount(); /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ boolean containsMessageSent( int key); /** * Use {@link #getMessageSentMap()} instead. */ @java.lang.Deprecated java.util.Map getMessageSent(); /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ java.util.Map getMessageSentMap(); /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ /* nullable */ pactus.NetworkOuterClass.CounterInfo getMessageSentOrDefault( int key, /* nullable */ pactus.NetworkOuterClass.CounterInfo defaultValue); /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ pactus.NetworkOuterClass.CounterInfo getMessageSentOrThrow( int key); /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ int getMessageReceivedCount(); /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ boolean containsMessageReceived( int key); /** * Use {@link #getMessageReceivedMap()} instead. */ @java.lang.Deprecated java.util.Map getMessageReceived(); /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ java.util.Map getMessageReceivedMap(); /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ /* nullable */ pactus.NetworkOuterClass.CounterInfo getMessageReceivedOrDefault( int key, /* nullable */ pactus.NetworkOuterClass.CounterInfo defaultValue); /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ pactus.NetworkOuterClass.CounterInfo getMessageReceivedOrThrow( int key); } /** *
   * MetricInfo contains metrics data regarding network activity.
   * 
* * Protobuf type {@code pactus.MetricInfo} */ public static final class MetricInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.MetricInfo) MetricInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "MetricInfo"); } // Use MetricInfo.newBuilder() to construct. private MetricInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private MetricInfo() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 4: return internalGetMessageSent(); case 5: return internalGetMessageReceived(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.MetricInfo.class, pactus.NetworkOuterClass.MetricInfo.Builder.class); } private int bitField0_; public static final int TOTAL_INVALID_FIELD_NUMBER = 1; private pactus.NetworkOuterClass.CounterInfo totalInvalid_; /** *
     * Total number of invalid bundles.
     * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; * @return Whether the totalInvalid field is set. */ @java.lang.Override public boolean hasTotalInvalid() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Total number of invalid bundles.
     * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; * @return The totalInvalid. */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getTotalInvalid() { return totalInvalid_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalInvalid_; } /** *
     * Total number of invalid bundles.
     * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalInvalidOrBuilder() { return totalInvalid_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalInvalid_; } public static final int TOTAL_SENT_FIELD_NUMBER = 2; private pactus.NetworkOuterClass.CounterInfo totalSent_; /** *
     * Total number of bundles sent.
     * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; * @return Whether the totalSent field is set. */ @java.lang.Override public boolean hasTotalSent() { return ((bitField0_ & 0x00000002) != 0); } /** *
     * Total number of bundles sent.
     * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; * @return The totalSent. */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getTotalSent() { return totalSent_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalSent_; } /** *
     * Total number of bundles sent.
     * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalSentOrBuilder() { return totalSent_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalSent_; } public static final int TOTAL_RECEIVED_FIELD_NUMBER = 3; private pactus.NetworkOuterClass.CounterInfo totalReceived_; /** *
     * Total number of bundles received.
     * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; * @return Whether the totalReceived field is set. */ @java.lang.Override public boolean hasTotalReceived() { return ((bitField0_ & 0x00000004) != 0); } /** *
     * Total number of bundles received.
     * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; * @return The totalReceived. */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getTotalReceived() { return totalReceived_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalReceived_; } /** *
     * Total number of bundles received.
     * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalReceivedOrBuilder() { return totalReceived_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalReceived_; } public static final int MESSAGE_SENT_FIELD_NUMBER = 4; private static final class MessageSentDefaultEntryHolder { static final com.google.protobuf.MapEntry< java.lang.Integer, pactus.NetworkOuterClass.CounterInfo> defaultEntry = com.google.protobuf.MapEntry .newDefaultInstance( pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_MessageSentEntry_descriptor, com.google.protobuf.WireFormat.FieldType.INT32, 0, com.google.protobuf.WireFormat.FieldType.MESSAGE, pactus.NetworkOuterClass.CounterInfo.getDefaultInstance()); } @SuppressWarnings("serial") private com.google.protobuf.MapField< java.lang.Integer, pactus.NetworkOuterClass.CounterInfo> messageSent_; private com.google.protobuf.MapField internalGetMessageSent() { if (messageSent_ == null) { return com.google.protobuf.MapField.emptyMapField( MessageSentDefaultEntryHolder.defaultEntry); } return messageSent_; } public int getMessageSentCount() { return internalGetMessageSent().getMap().size(); } /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public boolean containsMessageSent( int key) { return internalGetMessageSent().getMap().containsKey(key); } /** * Use {@link #getMessageSentMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map getMessageSent() { return getMessageSentMap(); } /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public java.util.Map getMessageSentMap() { return internalGetMessageSent().getMap(); } /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public /* nullable */ pactus.NetworkOuterClass.CounterInfo getMessageSentOrDefault( int key, /* nullable */ pactus.NetworkOuterClass.CounterInfo defaultValue) { java.util.Map map = internalGetMessageSent().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** *
     * Number of sent bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getMessageSentOrThrow( int key) { java.util.Map map = internalGetMessageSent().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public static final int MESSAGE_RECEIVED_FIELD_NUMBER = 5; private static final class MessageReceivedDefaultEntryHolder { static final com.google.protobuf.MapEntry< java.lang.Integer, pactus.NetworkOuterClass.CounterInfo> defaultEntry = com.google.protobuf.MapEntry .newDefaultInstance( pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_MessageReceivedEntry_descriptor, com.google.protobuf.WireFormat.FieldType.INT32, 0, com.google.protobuf.WireFormat.FieldType.MESSAGE, pactus.NetworkOuterClass.CounterInfo.getDefaultInstance()); } @SuppressWarnings("serial") private com.google.protobuf.MapField< java.lang.Integer, pactus.NetworkOuterClass.CounterInfo> messageReceived_; private com.google.protobuf.MapField internalGetMessageReceived() { if (messageReceived_ == null) { return com.google.protobuf.MapField.emptyMapField( MessageReceivedDefaultEntryHolder.defaultEntry); } return messageReceived_; } public int getMessageReceivedCount() { return internalGetMessageReceived().getMap().size(); } /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public boolean containsMessageReceived( int key) { return internalGetMessageReceived().getMap().containsKey(key); } /** * Use {@link #getMessageReceivedMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map getMessageReceived() { return getMessageReceivedMap(); } /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public java.util.Map getMessageReceivedMap() { return internalGetMessageReceived().getMap(); } /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public /* nullable */ pactus.NetworkOuterClass.CounterInfo getMessageReceivedOrDefault( int key, /* nullable */ pactus.NetworkOuterClass.CounterInfo defaultValue) { java.util.Map map = internalGetMessageReceived().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** *
     * Number of received bundles categorized by message type.
     * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getMessageReceivedOrThrow( int key) { java.util.Map map = internalGetMessageReceived().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getTotalInvalid()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getTotalSent()); } if (((bitField0_ & 0x00000004) != 0)) { output.writeMessage(3, getTotalReceived()); } com.google.protobuf.GeneratedMessage .serializeIntegerMapTo( output, internalGetMessageSent(), MessageSentDefaultEntryHolder.defaultEntry, 4); com.google.protobuf.GeneratedMessage .serializeIntegerMapTo( output, internalGetMessageReceived(), MessageReceivedDefaultEntryHolder.defaultEntry, 5); getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getTotalInvalid()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getTotalSent()); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, getTotalReceived()); } for (java.util.Map.Entry entry : internalGetMessageSent().getMap().entrySet()) { com.google.protobuf.MapEntry messageSent__ = MessageSentDefaultEntryHolder.defaultEntry.newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, messageSent__); } for (java.util.Map.Entry entry : internalGetMessageReceived().getMap().entrySet()) { com.google.protobuf.MapEntry messageReceived__ = MessageReceivedDefaultEntryHolder.defaultEntry.newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, messageReceived__); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.MetricInfo)) { return super.equals(obj); } pactus.NetworkOuterClass.MetricInfo other = (pactus.NetworkOuterClass.MetricInfo) obj; if (hasTotalInvalid() != other.hasTotalInvalid()) return false; if (hasTotalInvalid()) { if (!getTotalInvalid() .equals(other.getTotalInvalid())) return false; } if (hasTotalSent() != other.hasTotalSent()) return false; if (hasTotalSent()) { if (!getTotalSent() .equals(other.getTotalSent())) return false; } if (hasTotalReceived() != other.hasTotalReceived()) return false; if (hasTotalReceived()) { if (!getTotalReceived() .equals(other.getTotalReceived())) return false; } if (!internalGetMessageSent().equals( other.internalGetMessageSent())) return false; if (!internalGetMessageReceived().equals( other.internalGetMessageReceived())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasTotalInvalid()) { hash = (37 * hash) + TOTAL_INVALID_FIELD_NUMBER; hash = (53 * hash) + getTotalInvalid().hashCode(); } if (hasTotalSent()) { hash = (37 * hash) + TOTAL_SENT_FIELD_NUMBER; hash = (53 * hash) + getTotalSent().hashCode(); } if (hasTotalReceived()) { hash = (37 * hash) + TOTAL_RECEIVED_FIELD_NUMBER; hash = (53 * hash) + getTotalReceived().hashCode(); } if (!internalGetMessageSent().getMap().isEmpty()) { hash = (37 * hash) + MESSAGE_SENT_FIELD_NUMBER; hash = (53 * hash) + internalGetMessageSent().hashCode(); } if (!internalGetMessageReceived().getMap().isEmpty()) { hash = (37 * hash) + MESSAGE_RECEIVED_FIELD_NUMBER; hash = (53 * hash) + internalGetMessageReceived().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.MetricInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.MetricInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.MetricInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.MetricInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.MetricInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.MetricInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.MetricInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MetricInfo contains metrics data regarding network activity.
     * 
* * Protobuf type {@code pactus.MetricInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.MetricInfo) pactus.NetworkOuterClass.MetricInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 4: return internalGetMessageSent(); case 5: return internalGetMessageReceived(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 4: return internalGetMutableMessageSent(); case 5: return internalGetMutableMessageReceived(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.MetricInfo.class, pactus.NetworkOuterClass.MetricInfo.Builder.class); } // Construct using pactus.NetworkOuterClass.MetricInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetTotalInvalidFieldBuilder(); internalGetTotalSentFieldBuilder(); internalGetTotalReceivedFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; totalInvalid_ = null; if (totalInvalidBuilder_ != null) { totalInvalidBuilder_.dispose(); totalInvalidBuilder_ = null; } totalSent_ = null; if (totalSentBuilder_ != null) { totalSentBuilder_.dispose(); totalSentBuilder_ = null; } totalReceived_ = null; if (totalReceivedBuilder_ != null) { totalReceivedBuilder_.dispose(); totalReceivedBuilder_ = null; } internalGetMutableMessageSent().clear(); internalGetMutableMessageReceived().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_MetricInfo_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.MetricInfo getDefaultInstanceForType() { return pactus.NetworkOuterClass.MetricInfo.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.MetricInfo build() { pactus.NetworkOuterClass.MetricInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.MetricInfo buildPartial() { pactus.NetworkOuterClass.MetricInfo result = new pactus.NetworkOuterClass.MetricInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.MetricInfo result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.totalInvalid_ = totalInvalidBuilder_ == null ? totalInvalid_ : totalInvalidBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.totalSent_ = totalSentBuilder_ == null ? totalSent_ : totalSentBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.totalReceived_ = totalReceivedBuilder_ == null ? totalReceived_ : totalReceivedBuilder_.build(); to_bitField0_ |= 0x00000004; } if (((from_bitField0_ & 0x00000008) != 0)) { result.messageSent_ = internalGetMessageSent().build(MessageSentDefaultEntryHolder.defaultEntry); } if (((from_bitField0_ & 0x00000010) != 0)) { result.messageReceived_ = internalGetMessageReceived().build(MessageReceivedDefaultEntryHolder.defaultEntry); } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.MetricInfo) { return mergeFrom((pactus.NetworkOuterClass.MetricInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.MetricInfo other) { if (other == pactus.NetworkOuterClass.MetricInfo.getDefaultInstance()) return this; if (other.hasTotalInvalid()) { mergeTotalInvalid(other.getTotalInvalid()); } if (other.hasTotalSent()) { mergeTotalSent(other.getTotalSent()); } if (other.hasTotalReceived()) { mergeTotalReceived(other.getTotalReceived()); } internalGetMutableMessageSent().mergeFrom( other.internalGetMessageSent()); bitField0_ |= 0x00000008; internalGetMutableMessageReceived().mergeFrom( other.internalGetMessageReceived()); bitField0_ |= 0x00000010; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( internalGetTotalInvalidFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( internalGetTotalSentFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage( internalGetTotalReceivedFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 case 34: { com.google.protobuf.MapEntry messageSent__ = input.readMessage( MessageSentDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableMessageSent().ensureBuilderMap().put( messageSent__.getKey(), messageSent__.getValue()); bitField0_ |= 0x00000008; break; } // case 34 case 42: { com.google.protobuf.MapEntry messageReceived__ = input.readMessage( MessageReceivedDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableMessageReceived().ensureBuilderMap().put( messageReceived__.getKey(), messageReceived__.getValue()); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private pactus.NetworkOuterClass.CounterInfo totalInvalid_; private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder> totalInvalidBuilder_; /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; * @return Whether the totalInvalid field is set. */ public boolean hasTotalInvalid() { return ((bitField0_ & 0x00000001) != 0); } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; * @return The totalInvalid. */ public pactus.NetworkOuterClass.CounterInfo getTotalInvalid() { if (totalInvalidBuilder_ == null) { return totalInvalid_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalInvalid_; } else { return totalInvalidBuilder_.getMessage(); } } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ public Builder setTotalInvalid(pactus.NetworkOuterClass.CounterInfo value) { if (totalInvalidBuilder_ == null) { if (value == null) { throw new NullPointerException(); } totalInvalid_ = value; } else { totalInvalidBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ public Builder setTotalInvalid( pactus.NetworkOuterClass.CounterInfo.Builder builderForValue) { if (totalInvalidBuilder_ == null) { totalInvalid_ = builderForValue.build(); } else { totalInvalidBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ public Builder mergeTotalInvalid(pactus.NetworkOuterClass.CounterInfo value) { if (totalInvalidBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && totalInvalid_ != null && totalInvalid_ != pactus.NetworkOuterClass.CounterInfo.getDefaultInstance()) { getTotalInvalidBuilder().mergeFrom(value); } else { totalInvalid_ = value; } } else { totalInvalidBuilder_.mergeFrom(value); } if (totalInvalid_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ public Builder clearTotalInvalid() { bitField0_ = (bitField0_ & ~0x00000001); totalInvalid_ = null; if (totalInvalidBuilder_ != null) { totalInvalidBuilder_.dispose(); totalInvalidBuilder_ = null; } onChanged(); return this; } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ public pactus.NetworkOuterClass.CounterInfo.Builder getTotalInvalidBuilder() { bitField0_ |= 0x00000001; onChanged(); return internalGetTotalInvalidFieldBuilder().getBuilder(); } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ public pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalInvalidOrBuilder() { if (totalInvalidBuilder_ != null) { return totalInvalidBuilder_.getMessageOrBuilder(); } else { return totalInvalid_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalInvalid_; } } /** *
       * Total number of invalid bundles.
       * 
* * .pactus.CounterInfo total_invalid = 1 [json_name = "totalInvalid"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder> internalGetTotalInvalidFieldBuilder() { if (totalInvalidBuilder_ == null) { totalInvalidBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder>( getTotalInvalid(), getParentForChildren(), isClean()); totalInvalid_ = null; } return totalInvalidBuilder_; } private pactus.NetworkOuterClass.CounterInfo totalSent_; private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder> totalSentBuilder_; /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; * @return Whether the totalSent field is set. */ public boolean hasTotalSent() { return ((bitField0_ & 0x00000002) != 0); } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; * @return The totalSent. */ public pactus.NetworkOuterClass.CounterInfo getTotalSent() { if (totalSentBuilder_ == null) { return totalSent_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalSent_; } else { return totalSentBuilder_.getMessage(); } } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ public Builder setTotalSent(pactus.NetworkOuterClass.CounterInfo value) { if (totalSentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } totalSent_ = value; } else { totalSentBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ public Builder setTotalSent( pactus.NetworkOuterClass.CounterInfo.Builder builderForValue) { if (totalSentBuilder_ == null) { totalSent_ = builderForValue.build(); } else { totalSentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ public Builder mergeTotalSent(pactus.NetworkOuterClass.CounterInfo value) { if (totalSentBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && totalSent_ != null && totalSent_ != pactus.NetworkOuterClass.CounterInfo.getDefaultInstance()) { getTotalSentBuilder().mergeFrom(value); } else { totalSent_ = value; } } else { totalSentBuilder_.mergeFrom(value); } if (totalSent_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ public Builder clearTotalSent() { bitField0_ = (bitField0_ & ~0x00000002); totalSent_ = null; if (totalSentBuilder_ != null) { totalSentBuilder_.dispose(); totalSentBuilder_ = null; } onChanged(); return this; } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ public pactus.NetworkOuterClass.CounterInfo.Builder getTotalSentBuilder() { bitField0_ |= 0x00000002; onChanged(); return internalGetTotalSentFieldBuilder().getBuilder(); } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ public pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalSentOrBuilder() { if (totalSentBuilder_ != null) { return totalSentBuilder_.getMessageOrBuilder(); } else { return totalSent_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalSent_; } } /** *
       * Total number of bundles sent.
       * 
* * .pactus.CounterInfo total_sent = 2 [json_name = "totalSent"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder> internalGetTotalSentFieldBuilder() { if (totalSentBuilder_ == null) { totalSentBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder>( getTotalSent(), getParentForChildren(), isClean()); totalSent_ = null; } return totalSentBuilder_; } private pactus.NetworkOuterClass.CounterInfo totalReceived_; private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder> totalReceivedBuilder_; /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; * @return Whether the totalReceived field is set. */ public boolean hasTotalReceived() { return ((bitField0_ & 0x00000004) != 0); } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; * @return The totalReceived. */ public pactus.NetworkOuterClass.CounterInfo getTotalReceived() { if (totalReceivedBuilder_ == null) { return totalReceived_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalReceived_; } else { return totalReceivedBuilder_.getMessage(); } } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ public Builder setTotalReceived(pactus.NetworkOuterClass.CounterInfo value) { if (totalReceivedBuilder_ == null) { if (value == null) { throw new NullPointerException(); } totalReceived_ = value; } else { totalReceivedBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ public Builder setTotalReceived( pactus.NetworkOuterClass.CounterInfo.Builder builderForValue) { if (totalReceivedBuilder_ == null) { totalReceived_ = builderForValue.build(); } else { totalReceivedBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ public Builder mergeTotalReceived(pactus.NetworkOuterClass.CounterInfo value) { if (totalReceivedBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && totalReceived_ != null && totalReceived_ != pactus.NetworkOuterClass.CounterInfo.getDefaultInstance()) { getTotalReceivedBuilder().mergeFrom(value); } else { totalReceived_ = value; } } else { totalReceivedBuilder_.mergeFrom(value); } if (totalReceived_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ public Builder clearTotalReceived() { bitField0_ = (bitField0_ & ~0x00000004); totalReceived_ = null; if (totalReceivedBuilder_ != null) { totalReceivedBuilder_.dispose(); totalReceivedBuilder_ = null; } onChanged(); return this; } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ public pactus.NetworkOuterClass.CounterInfo.Builder getTotalReceivedBuilder() { bitField0_ |= 0x00000004; onChanged(); return internalGetTotalReceivedFieldBuilder().getBuilder(); } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ public pactus.NetworkOuterClass.CounterInfoOrBuilder getTotalReceivedOrBuilder() { if (totalReceivedBuilder_ != null) { return totalReceivedBuilder_.getMessageOrBuilder(); } else { return totalReceived_ == null ? pactus.NetworkOuterClass.CounterInfo.getDefaultInstance() : totalReceived_; } } /** *
       * Total number of bundles received.
       * 
* * .pactus.CounterInfo total_received = 3 [json_name = "totalReceived"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder> internalGetTotalReceivedFieldBuilder() { if (totalReceivedBuilder_ == null) { totalReceivedBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder, pactus.NetworkOuterClass.CounterInfoOrBuilder>( getTotalReceived(), getParentForChildren(), isClean()); totalReceived_ = null; } return totalReceivedBuilder_; } private static final class MessageSentConverter implements com.google.protobuf.MapFieldBuilder.Converter { @java.lang.Override public pactus.NetworkOuterClass.CounterInfo build(pactus.NetworkOuterClass.CounterInfoOrBuilder val) { if (val instanceof pactus.NetworkOuterClass.CounterInfo) { return (pactus.NetworkOuterClass.CounterInfo) val; } return ((pactus.NetworkOuterClass.CounterInfo.Builder) val).build(); } @java.lang.Override public com.google.protobuf.MapEntry defaultEntry() { return MessageSentDefaultEntryHolder.defaultEntry; } }; private static final MessageSentConverter messageSentConverter = new MessageSentConverter(); private com.google.protobuf.MapFieldBuilder< java.lang.Integer, pactus.NetworkOuterClass.CounterInfoOrBuilder, pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder> messageSent_; private com.google.protobuf.MapFieldBuilder internalGetMessageSent() { if (messageSent_ == null) { return new com.google.protobuf.MapFieldBuilder<>(messageSentConverter); } return messageSent_; } private com.google.protobuf.MapFieldBuilder internalGetMutableMessageSent() { if (messageSent_ == null) { messageSent_ = new com.google.protobuf.MapFieldBuilder<>(messageSentConverter); } bitField0_ |= 0x00000008; onChanged(); return messageSent_; } public int getMessageSentCount() { return internalGetMessageSent().ensureBuilderMap().size(); } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public boolean containsMessageSent( int key) { return internalGetMessageSent().ensureBuilderMap().containsKey(key); } /** * Use {@link #getMessageSentMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map getMessageSent() { return getMessageSentMap(); } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public java.util.Map getMessageSentMap() { return internalGetMessageSent().getImmutableMap(); } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public /* nullable */ pactus.NetworkOuterClass.CounterInfo getMessageSentOrDefault( int key, /* nullable */ pactus.NetworkOuterClass.CounterInfo defaultValue) { java.util.Map map = internalGetMutableMessageSent().ensureBuilderMap(); return map.containsKey(key) ? messageSentConverter.build(map.get(key)) : defaultValue; } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getMessageSentOrThrow( int key) { java.util.Map map = internalGetMutableMessageSent().ensureBuilderMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return messageSentConverter.build(map.get(key)); } public Builder clearMessageSent() { bitField0_ = (bitField0_ & ~0x00000008); internalGetMutableMessageSent().clear(); return this; } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ public Builder removeMessageSent( int key) { internalGetMutableMessageSent().ensureBuilderMap() .remove(key); return this; } /** * Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map getMutableMessageSent() { bitField0_ |= 0x00000008; return internalGetMutableMessageSent().ensureMessageMap(); } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ public Builder putMessageSent( int key, pactus.NetworkOuterClass.CounterInfo value) { if (value == null) { throw new NullPointerException("map value"); } internalGetMutableMessageSent().ensureBuilderMap() .put(key, value); bitField0_ |= 0x00000008; return this; } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ public Builder putAllMessageSent( java.util.Map values) { for (java.util.Map.Entry e : values.entrySet()) { if (e.getKey() == null || e.getValue() == null) { throw new NullPointerException(); } } internalGetMutableMessageSent().ensureBuilderMap() .putAll(values); bitField0_ |= 0x00000008; return this; } /** *
       * Number of sent bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_sent = 4 [json_name = "messageSent"]; */ public pactus.NetworkOuterClass.CounterInfo.Builder putMessageSentBuilderIfAbsent( int key) { java.util.Map builderMap = internalGetMutableMessageSent().ensureBuilderMap(); pactus.NetworkOuterClass.CounterInfoOrBuilder entry = builderMap.get(key); if (entry == null) { entry = pactus.NetworkOuterClass.CounterInfo.newBuilder(); builderMap.put(key, entry); } if (entry instanceof pactus.NetworkOuterClass.CounterInfo) { entry = ((pactus.NetworkOuterClass.CounterInfo) entry).toBuilder(); builderMap.put(key, entry); } return (pactus.NetworkOuterClass.CounterInfo.Builder) entry; } private static final class MessageReceivedConverter implements com.google.protobuf.MapFieldBuilder.Converter { @java.lang.Override public pactus.NetworkOuterClass.CounterInfo build(pactus.NetworkOuterClass.CounterInfoOrBuilder val) { if (val instanceof pactus.NetworkOuterClass.CounterInfo) { return (pactus.NetworkOuterClass.CounterInfo) val; } return ((pactus.NetworkOuterClass.CounterInfo.Builder) val).build(); } @java.lang.Override public com.google.protobuf.MapEntry defaultEntry() { return MessageReceivedDefaultEntryHolder.defaultEntry; } }; private static final MessageReceivedConverter messageReceivedConverter = new MessageReceivedConverter(); private com.google.protobuf.MapFieldBuilder< java.lang.Integer, pactus.NetworkOuterClass.CounterInfoOrBuilder, pactus.NetworkOuterClass.CounterInfo, pactus.NetworkOuterClass.CounterInfo.Builder> messageReceived_; private com.google.protobuf.MapFieldBuilder internalGetMessageReceived() { if (messageReceived_ == null) { return new com.google.protobuf.MapFieldBuilder<>(messageReceivedConverter); } return messageReceived_; } private com.google.protobuf.MapFieldBuilder internalGetMutableMessageReceived() { if (messageReceived_ == null) { messageReceived_ = new com.google.protobuf.MapFieldBuilder<>(messageReceivedConverter); } bitField0_ |= 0x00000010; onChanged(); return messageReceived_; } public int getMessageReceivedCount() { return internalGetMessageReceived().ensureBuilderMap().size(); } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public boolean containsMessageReceived( int key) { return internalGetMessageReceived().ensureBuilderMap().containsKey(key); } /** * Use {@link #getMessageReceivedMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map getMessageReceived() { return getMessageReceivedMap(); } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public java.util.Map getMessageReceivedMap() { return internalGetMessageReceived().getImmutableMap(); } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public /* nullable */ pactus.NetworkOuterClass.CounterInfo getMessageReceivedOrDefault( int key, /* nullable */ pactus.NetworkOuterClass.CounterInfo defaultValue) { java.util.Map map = internalGetMutableMessageReceived().ensureBuilderMap(); return map.containsKey(key) ? messageReceivedConverter.build(map.get(key)) : defaultValue; } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getMessageReceivedOrThrow( int key) { java.util.Map map = internalGetMutableMessageReceived().ensureBuilderMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return messageReceivedConverter.build(map.get(key)); } public Builder clearMessageReceived() { bitField0_ = (bitField0_ & ~0x00000010); internalGetMutableMessageReceived().clear(); return this; } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ public Builder removeMessageReceived( int key) { internalGetMutableMessageReceived().ensureBuilderMap() .remove(key); return this; } /** * Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map getMutableMessageReceived() { bitField0_ |= 0x00000010; return internalGetMutableMessageReceived().ensureMessageMap(); } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ public Builder putMessageReceived( int key, pactus.NetworkOuterClass.CounterInfo value) { if (value == null) { throw new NullPointerException("map value"); } internalGetMutableMessageReceived().ensureBuilderMap() .put(key, value); bitField0_ |= 0x00000010; return this; } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ public Builder putAllMessageReceived( java.util.Map values) { for (java.util.Map.Entry e : values.entrySet()) { if (e.getKey() == null || e.getValue() == null) { throw new NullPointerException(); } } internalGetMutableMessageReceived().ensureBuilderMap() .putAll(values); bitField0_ |= 0x00000010; return this; } /** *
       * Number of received bundles categorized by message type.
       * 
* * map<int32, .pactus.CounterInfo> message_received = 5 [json_name = "messageReceived"]; */ public pactus.NetworkOuterClass.CounterInfo.Builder putMessageReceivedBuilderIfAbsent( int key) { java.util.Map builderMap = internalGetMutableMessageReceived().ensureBuilderMap(); pactus.NetworkOuterClass.CounterInfoOrBuilder entry = builderMap.get(key); if (entry == null) { entry = pactus.NetworkOuterClass.CounterInfo.newBuilder(); builderMap.put(key, entry); } if (entry instanceof pactus.NetworkOuterClass.CounterInfo) { entry = ((pactus.NetworkOuterClass.CounterInfo) entry).toBuilder(); builderMap.put(key, entry); } return (pactus.NetworkOuterClass.CounterInfo.Builder) entry; } // @@protoc_insertion_point(builder_scope:pactus.MetricInfo) } // @@protoc_insertion_point(class_scope:pactus.MetricInfo) private static final pactus.NetworkOuterClass.MetricInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.MetricInfo(); } public static pactus.NetworkOuterClass.MetricInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MetricInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.MetricInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CounterInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CounterInfo) com.google.protobuf.MessageOrBuilder { /** *
     * Total number of bytes.
     * 
* * uint64 bytes = 1 [json_name = "bytes"]; * @return The bytes. */ long getBytes(); /** *
     * Total number of bundles.
     * 
* * uint64 bundles = 2 [json_name = "bundles"]; * @return The bundles. */ long getBundles(); } /** *
   * CounterInfo holds counter data regarding byte and bundle counts.
   * 
* * Protobuf type {@code pactus.CounterInfo} */ public static final class CounterInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CounterInfo) CounterInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CounterInfo"); } // Use CounterInfo.newBuilder() to construct. private CounterInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CounterInfo() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_CounterInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_CounterInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.CounterInfo.class, pactus.NetworkOuterClass.CounterInfo.Builder.class); } public static final int BYTES_FIELD_NUMBER = 1; private long bytes_ = 0L; /** *
     * Total number of bytes.
     * 
* * uint64 bytes = 1 [json_name = "bytes"]; * @return The bytes. */ @java.lang.Override public long getBytes() { return bytes_; } public static final int BUNDLES_FIELD_NUMBER = 2; private long bundles_ = 0L; /** *
     * Total number of bundles.
     * 
* * uint64 bundles = 2 [json_name = "bundles"]; * @return The bundles. */ @java.lang.Override public long getBundles() { return bundles_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (bytes_ != 0L) { output.writeUInt64(1, bytes_); } if (bundles_ != 0L) { output.writeUInt64(2, bundles_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (bytes_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, bytes_); } if (bundles_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(2, bundles_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.CounterInfo)) { return super.equals(obj); } pactus.NetworkOuterClass.CounterInfo other = (pactus.NetworkOuterClass.CounterInfo) obj; if (getBytes() != other.getBytes()) return false; if (getBundles() != other.getBundles()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + BYTES_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getBytes()); hash = (37 * hash) + BUNDLES_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getBundles()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.CounterInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.CounterInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.CounterInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.CounterInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.CounterInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.CounterInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.CounterInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * CounterInfo holds counter data regarding byte and bundle counts.
     * 
* * Protobuf type {@code pactus.CounterInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CounterInfo) pactus.NetworkOuterClass.CounterInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_CounterInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_CounterInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.CounterInfo.class, pactus.NetworkOuterClass.CounterInfo.Builder.class); } // Construct using pactus.NetworkOuterClass.CounterInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; bytes_ = 0L; bundles_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_CounterInfo_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getDefaultInstanceForType() { return pactus.NetworkOuterClass.CounterInfo.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.CounterInfo build() { pactus.NetworkOuterClass.CounterInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.CounterInfo buildPartial() { pactus.NetworkOuterClass.CounterInfo result = new pactus.NetworkOuterClass.CounterInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.NetworkOuterClass.CounterInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.bytes_ = bytes_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.bundles_ = bundles_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.CounterInfo) { return mergeFrom((pactus.NetworkOuterClass.CounterInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.CounterInfo other) { if (other == pactus.NetworkOuterClass.CounterInfo.getDefaultInstance()) return this; if (other.getBytes() != 0L) { setBytes(other.getBytes()); } if (other.getBundles() != 0L) { setBundles(other.getBundles()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { bytes_ = input.readUInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { bundles_ = input.readUInt64(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private long bytes_ ; /** *
       * Total number of bytes.
       * 
* * uint64 bytes = 1 [json_name = "bytes"]; * @return The bytes. */ @java.lang.Override public long getBytes() { return bytes_; } /** *
       * Total number of bytes.
       * 
* * uint64 bytes = 1 [json_name = "bytes"]; * @param value The bytes to set. * @return This builder for chaining. */ public Builder setBytes(long value) { bytes_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Total number of bytes.
       * 
* * uint64 bytes = 1 [json_name = "bytes"]; * @return This builder for chaining. */ public Builder clearBytes() { bitField0_ = (bitField0_ & ~0x00000001); bytes_ = 0L; onChanged(); return this; } private long bundles_ ; /** *
       * Total number of bundles.
       * 
* * uint64 bundles = 2 [json_name = "bundles"]; * @return The bundles. */ @java.lang.Override public long getBundles() { return bundles_; } /** *
       * Total number of bundles.
       * 
* * uint64 bundles = 2 [json_name = "bundles"]; * @param value The bundles to set. * @return This builder for chaining. */ public Builder setBundles(long value) { bundles_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Total number of bundles.
       * 
* * uint64 bundles = 2 [json_name = "bundles"]; * @return This builder for chaining. */ public Builder clearBundles() { bitField0_ = (bitField0_ & ~0x00000002); bundles_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CounterInfo) } // @@protoc_insertion_point(class_scope:pactus.CounterInfo) private static final pactus.NetworkOuterClass.CounterInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.CounterInfo(); } public static pactus.NetworkOuterClass.CounterInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CounterInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.CounterInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PingRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PingRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for ping - intentionally empty for measuring round-trip time.
   * 
* * Protobuf type {@code pactus.PingRequest} */ public static final class PingRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PingRequest) PingRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PingRequest"); } // Use PingRequest.newBuilder() to construct. private PingRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PingRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_PingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_PingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.PingRequest.class, pactus.NetworkOuterClass.PingRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.PingRequest)) { return super.equals(obj); } pactus.NetworkOuterClass.PingRequest other = (pactus.NetworkOuterClass.PingRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.PingRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PingRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PingRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PingRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PingRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PingRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PingRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PingRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.PingRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PingRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.PingRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PingRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.PingRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for ping - intentionally empty for measuring round-trip time.
     * 
* * Protobuf type {@code pactus.PingRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PingRequest) pactus.NetworkOuterClass.PingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_PingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_PingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.PingRequest.class, pactus.NetworkOuterClass.PingRequest.Builder.class); } // Construct using pactus.NetworkOuterClass.PingRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_PingRequest_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.PingRequest getDefaultInstanceForType() { return pactus.NetworkOuterClass.PingRequest.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.PingRequest build() { pactus.NetworkOuterClass.PingRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.PingRequest buildPartial() { pactus.NetworkOuterClass.PingRequest result = new pactus.NetworkOuterClass.PingRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.PingRequest) { return mergeFrom((pactus.NetworkOuterClass.PingRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.PingRequest other) { if (other == pactus.NetworkOuterClass.PingRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.PingRequest) } // @@protoc_insertion_point(class_scope:pactus.PingRequest) private static final pactus.NetworkOuterClass.PingRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.PingRequest(); } public static pactus.NetworkOuterClass.PingRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PingRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.PingRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PingResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PingResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * Response message for ping - intentionally empty for measuring round-trip time.
   * 
* * Protobuf type {@code pactus.PingResponse} */ public static final class PingResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PingResponse) PingResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PingResponse"); } // Use PingResponse.newBuilder() to construct. private PingResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PingResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_PingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_PingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.PingResponse.class, pactus.NetworkOuterClass.PingResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.NetworkOuterClass.PingResponse)) { return super.equals(obj); } pactus.NetworkOuterClass.PingResponse other = (pactus.NetworkOuterClass.PingResponse) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.NetworkOuterClass.PingResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PingResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PingResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PingResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PingResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.NetworkOuterClass.PingResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.NetworkOuterClass.PingResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PingResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.PingResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PingResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.NetworkOuterClass.PingResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.NetworkOuterClass.PingResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.NetworkOuterClass.PingResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message for ping - intentionally empty for measuring round-trip time.
     * 
* * Protobuf type {@code pactus.PingResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PingResponse) pactus.NetworkOuterClass.PingResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.NetworkOuterClass.internal_static_pactus_PingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.NetworkOuterClass.internal_static_pactus_PingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.NetworkOuterClass.PingResponse.class, pactus.NetworkOuterClass.PingResponse.Builder.class); } // Construct using pactus.NetworkOuterClass.PingResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.NetworkOuterClass.internal_static_pactus_PingResponse_descriptor; } @java.lang.Override public pactus.NetworkOuterClass.PingResponse getDefaultInstanceForType() { return pactus.NetworkOuterClass.PingResponse.getDefaultInstance(); } @java.lang.Override public pactus.NetworkOuterClass.PingResponse build() { pactus.NetworkOuterClass.PingResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.NetworkOuterClass.PingResponse buildPartial() { pactus.NetworkOuterClass.PingResponse result = new pactus.NetworkOuterClass.PingResponse(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.NetworkOuterClass.PingResponse) { return mergeFrom((pactus.NetworkOuterClass.PingResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.NetworkOuterClass.PingResponse other) { if (other == pactus.NetworkOuterClass.PingResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.PingResponse) } // @@protoc_insertion_point(class_scope:pactus.PingResponse) private static final pactus.NetworkOuterClass.PingResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.NetworkOuterClass.PingResponse(); } public static pactus.NetworkOuterClass.PingResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PingResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.NetworkOuterClass.PingResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetNetworkInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetNetworkInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetNetworkInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetNetworkInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListPeersRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListPeersRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListPeersResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListPeersResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetNodeInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetNodeInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetNodeInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetNodeInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ZMQPublisherInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ZMQPublisherInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PeerInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PeerInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ConnectionInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ConnectionInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_MetricInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_MetricInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_MetricInfo_MessageSentEntry_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_MetricInfo_MessageSentEntry_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_MetricInfo_MessageReceivedEntry_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_MetricInfo_MessageReceivedEntry_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CounterInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CounterInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PingRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PingRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PingResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PingResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\rnetwork.proto\022\006pactus\"\027\n\025GetNetworkInf" + "oRequest\"\244\001\n\026GetNetworkInfoResponse\022!\n\014n" + "etwork_name\030\001 \001(\tR\013networkName\0222\n\025connec" + "ted_peers_count\030\002 \001(\rR\023connectedPeersCou" + "nt\0223\n\013metric_info\030\004 \001(\0132\022.pactus.MetricI" + "nfoR\nmetricInfo\"E\n\020ListPeersRequest\0221\n\024i" + "nclude_disconnected\030\001 \001(\010R\023includeDiscon" + "nected\";\n\021ListPeersResponse\022&\n\005peers\030\001 \003" + "(\0132\020.pactus.PeerInfoR\005peers\"\024\n\022GetNodeIn" + "foRequest\"\216\004\n\023GetNodeInfoResponse\022\030\n\007mon" + "iker\030\001 \001(\tR\007moniker\022\024\n\005agent\030\002 \001(\tR\005agen" + "t\022\027\n\007peer_id\030\003 \001(\tR\006peerId\022\035\n\nstarted_at" + "\030\004 \001(\004R\tstartedAt\022\"\n\014reachability\030\005 \001(\tR" + "\014reachability\022\032\n\010services\030\006 \001(\005R\010service" + "s\022%\n\016services_names\030\007 \001(\tR\rservicesNames" + "\022\037\n\013local_addrs\030\010 \003(\tR\nlocalAddrs\022\034\n\tpro" + "tocols\030\t \003(\tR\tprotocols\022!\n\014clock_offset\030" + "\r \001(\001R\013clockOffset\022?\n\017connection_info\030\016 " + "\001(\0132\026.pactus.ConnectionInfoR\016connectionI" + "nfo\022?\n\016zmq_publishers\030\017 \003(\0132\030.pactus.ZMQ" + "PublisherInfoR\rzmqPublishers\022!\n\014current_" + "time\030\020 \001(\004R\013currentTime\022!\n\014network_name\030" + "\021 \001(\tR\013networkName\"T\n\020ZMQPublisherInfo\022\024" + "\n\005topic\030\001 \001(\tR\005topic\022\030\n\007address\030\002 \001(\tR\007a" + "ddress\022\020\n\003hwm\030\003 \001(\005R\003hwm\"\205\005\n\010PeerInfo\022\026\n" + "\006status\030\001 \001(\005R\006status\022\030\n\007moniker\030\002 \001(\tR\007" + "moniker\022\024\n\005agent\030\003 \001(\tR\005agent\022\027\n\007peer_id" + "\030\004 \001(\tR\006peerId\022%\n\016consensus_keys\030\005 \003(\tR\r" + "consensusKeys\022/\n\023consensus_addresses\030\006 \003" + "(\tR\022consensusAddresses\022\032\n\010services\030\007 \001(\r" + "R\010services\022&\n\017last_block_hash\030\010 \001(\tR\rlas" + "tBlockHash\022\026\n\006height\030\t \001(\rR\006height\022\033\n\tla" + "st_sent\030\n \001(\003R\010lastSent\022#\n\rlast_received" + "\030\013 \001(\003R\014lastReceived\022\030\n\007address\030\014 \001(\tR\007a" + "ddress\022/\n\tdirection\030\r \001(\0162\021.pactus.Direc" + "tionR\tdirection\022\034\n\tprotocols\030\016 \003(\tR\tprot" + "ocols\022%\n\016total_sessions\030\017 \001(\005R\rtotalSess" + "ions\022-\n\022completed_sessions\030\020 \001(\005R\021comple" + "tedSessions\0223\n\013metric_info\030\021 \001(\0132\022.pactu" + "s.MetricInfoR\nmetricInfo\022.\n\023outbound_hel" + "lo_sent\030\022 \001(\010R\021outboundHelloSent\"\226\001\n\016Con" + "nectionInfo\022 \n\013connections\030\001 \001(\004R\013connec" + "tions\022/\n\023inbound_connections\030\002 \001(\004R\022inbo" + "undConnections\0221\n\024outbound_connections\030\003" + " \001(\004R\023outboundConnections\"\200\004\n\nMetricInfo" + "\0228\n\rtotal_invalid\030\001 \001(\0132\023.pactus.Counter" + "InfoR\014totalInvalid\0222\n\ntotal_sent\030\002 \001(\0132\023" + ".pactus.CounterInfoR\ttotalSent\022:\n\016total_" + "received\030\003 \001(\0132\023.pactus.CounterInfoR\rtot" + "alReceived\022F\n\014message_sent\030\004 \003(\0132#.pactu" + "s.MetricInfo.MessageSentEntryR\013messageSe" + "nt\022R\n\020message_received\030\005 \003(\0132\'.pactus.Me" + "tricInfo.MessageReceivedEntryR\017messageRe" + "ceived\032S\n\020MessageSentEntry\022\020\n\003key\030\001 \001(\005R" + "\003key\022)\n\005value\030\002 \001(\0132\023.pactus.CounterInfo" + "R\005value:\0028\001\032W\n\024MessageReceivedEntry\022\020\n\003k" + "ey\030\001 \001(\005R\003key\022)\n\005value\030\002 \001(\0132\023.pactus.Co" + "unterInfoR\005value:\0028\001\"=\n\013CounterInfo\022\024\n\005b" + "ytes\030\001 \001(\004R\005bytes\022\030\n\007bundles\030\002 \001(\004R\007bund" + "les\"\r\n\013PingRequest\"\016\n\014PingResponse*Q\n\tDi" + "rection\022\025\n\021DIRECTION_UNKNOWN\020\000\022\025\n\021DIRECT" + "ION_INBOUND\020\001\022\026\n\022DIRECTION_OUTBOUND\020\0022\227\002" + "\n\007Network\022O\n\016GetNetworkInfo\022\035.pactus.Get" + "NetworkInfoRequest\032\036.pactus.GetNetworkIn" + "foResponse\022@\n\tListPeers\022\030.pactus.ListPee" + "rsRequest\032\031.pactus.ListPeersResponse\022F\n\013" + "GetNodeInfo\022\032.pactus.GetNodeInfoRequest\032" + "\033.pactus.GetNodeInfoResponse\0221\n\004Ping\022\023.p" + "actus.PingRequest\032\024.pactus.PingResponseB" + ":\n\006pactusZ0github.com/pactus-project/pac" + "tus/www/grpc/pactusb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_pactus_GetNetworkInfoRequest_descriptor = getDescriptor().getMessageType(0); internal_static_pactus_GetNetworkInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetNetworkInfoRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_GetNetworkInfoResponse_descriptor = getDescriptor().getMessageType(1); internal_static_pactus_GetNetworkInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetNetworkInfoResponse_descriptor, new java.lang.String[] { "NetworkName", "ConnectedPeersCount", "MetricInfo", }); internal_static_pactus_ListPeersRequest_descriptor = getDescriptor().getMessageType(2); internal_static_pactus_ListPeersRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListPeersRequest_descriptor, new java.lang.String[] { "IncludeDisconnected", }); internal_static_pactus_ListPeersResponse_descriptor = getDescriptor().getMessageType(3); internal_static_pactus_ListPeersResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListPeersResponse_descriptor, new java.lang.String[] { "Peers", }); internal_static_pactus_GetNodeInfoRequest_descriptor = getDescriptor().getMessageType(4); internal_static_pactus_GetNodeInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetNodeInfoRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_GetNodeInfoResponse_descriptor = getDescriptor().getMessageType(5); internal_static_pactus_GetNodeInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetNodeInfoResponse_descriptor, new java.lang.String[] { "Moniker", "Agent", "PeerId", "StartedAt", "Reachability", "Services", "ServicesNames", "LocalAddrs", "Protocols", "ClockOffset", "ConnectionInfo", "ZmqPublishers", "CurrentTime", "NetworkName", }); internal_static_pactus_ZMQPublisherInfo_descriptor = getDescriptor().getMessageType(6); internal_static_pactus_ZMQPublisherInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ZMQPublisherInfo_descriptor, new java.lang.String[] { "Topic", "Address", "Hwm", }); internal_static_pactus_PeerInfo_descriptor = getDescriptor().getMessageType(7); internal_static_pactus_PeerInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PeerInfo_descriptor, new java.lang.String[] { "Status", "Moniker", "Agent", "PeerId", "ConsensusKeys", "ConsensusAddresses", "Services", "LastBlockHash", "Height", "LastSent", "LastReceived", "Address", "Direction", "Protocols", "TotalSessions", "CompletedSessions", "MetricInfo", "OutboundHelloSent", }); internal_static_pactus_ConnectionInfo_descriptor = getDescriptor().getMessageType(8); internal_static_pactus_ConnectionInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ConnectionInfo_descriptor, new java.lang.String[] { "Connections", "InboundConnections", "OutboundConnections", }); internal_static_pactus_MetricInfo_descriptor = getDescriptor().getMessageType(9); internal_static_pactus_MetricInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_MetricInfo_descriptor, new java.lang.String[] { "TotalInvalid", "TotalSent", "TotalReceived", "MessageSent", "MessageReceived", }); internal_static_pactus_MetricInfo_MessageSentEntry_descriptor = internal_static_pactus_MetricInfo_descriptor.getNestedType(0); internal_static_pactus_MetricInfo_MessageSentEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_MetricInfo_MessageSentEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_pactus_MetricInfo_MessageReceivedEntry_descriptor = internal_static_pactus_MetricInfo_descriptor.getNestedType(1); internal_static_pactus_MetricInfo_MessageReceivedEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_MetricInfo_MessageReceivedEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_pactus_CounterInfo_descriptor = getDescriptor().getMessageType(10); internal_static_pactus_CounterInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CounterInfo_descriptor, new java.lang.String[] { "Bytes", "Bundles", }); internal_static_pactus_PingRequest_descriptor = getDescriptor().getMessageType(11); internal_static_pactus_PingRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PingRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_PingResponse_descriptor = getDescriptor().getMessageType(12); internal_static_pactus_PingResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PingResponse_descriptor, new java.lang.String[] { }); descriptor.resolveAllFeaturesImmutable(); } // @@protoc_insertion_point(outer_class_scope) } ================================================ FILE: www/grpc/gen/java/pactus/TransactionGrpc.java ================================================ package pactus; import static io.grpc.MethodDescriptor.generateFullMethodName; /** *
 * Transaction service defines various RPC methods for interacting with transactions.
 * 
*/ @io.grpc.stub.annotations.GrpcGenerated public final class TransactionGrpc { private TransactionGrpc() {} public static final java.lang.String SERVICE_NAME = "pactus.Transaction"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor getGetTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetTransaction", requestType = pactus.TransactionOuterClass.GetTransactionRequest.class, responseType = pactus.TransactionOuterClass.GetTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetTransactionMethod() { io.grpc.MethodDescriptor getGetTransactionMethod; if ((getGetTransactionMethod = TransactionGrpc.getGetTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getGetTransactionMethod = TransactionGrpc.getGetTransactionMethod) == null) { TransactionGrpc.getGetTransactionMethod = getGetTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("GetTransaction")) .build(); } } } return getGetTransactionMethod; } private static volatile io.grpc.MethodDescriptor getCalculateFeeMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CalculateFee", requestType = pactus.TransactionOuterClass.CalculateFeeRequest.class, responseType = pactus.TransactionOuterClass.CalculateFeeResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getCalculateFeeMethod() { io.grpc.MethodDescriptor getCalculateFeeMethod; if ((getCalculateFeeMethod = TransactionGrpc.getCalculateFeeMethod) == null) { synchronized (TransactionGrpc.class) { if ((getCalculateFeeMethod = TransactionGrpc.getCalculateFeeMethod) == null) { TransactionGrpc.getCalculateFeeMethod = getCalculateFeeMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CalculateFee")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.CalculateFeeRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.CalculateFeeResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("CalculateFee")) .build(); } } } return getCalculateFeeMethod; } private static volatile io.grpc.MethodDescriptor getBroadcastTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "BroadcastTransaction", requestType = pactus.TransactionOuterClass.BroadcastTransactionRequest.class, responseType = pactus.TransactionOuterClass.BroadcastTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getBroadcastTransactionMethod() { io.grpc.MethodDescriptor getBroadcastTransactionMethod; if ((getBroadcastTransactionMethod = TransactionGrpc.getBroadcastTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getBroadcastTransactionMethod = TransactionGrpc.getBroadcastTransactionMethod) == null) { TransactionGrpc.getBroadcastTransactionMethod = getBroadcastTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "BroadcastTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.BroadcastTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.BroadcastTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("BroadcastTransaction")) .build(); } } } return getBroadcastTransactionMethod; } private static volatile io.grpc.MethodDescriptor getGetRawTransferTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetRawTransferTransaction", requestType = pactus.TransactionOuterClass.GetRawTransferTransactionRequest.class, responseType = pactus.TransactionOuterClass.GetRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetRawTransferTransactionMethod() { io.grpc.MethodDescriptor getGetRawTransferTransactionMethod; if ((getGetRawTransferTransactionMethod = TransactionGrpc.getGetRawTransferTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getGetRawTransferTransactionMethod = TransactionGrpc.getGetRawTransferTransactionMethod) == null) { TransactionGrpc.getGetRawTransferTransactionMethod = getGetRawTransferTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetRawTransferTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawTransferTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("GetRawTransferTransaction")) .build(); } } } return getGetRawTransferTransactionMethod; } private static volatile io.grpc.MethodDescriptor getGetRawBondTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetRawBondTransaction", requestType = pactus.TransactionOuterClass.GetRawBondTransactionRequest.class, responseType = pactus.TransactionOuterClass.GetRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetRawBondTransactionMethod() { io.grpc.MethodDescriptor getGetRawBondTransactionMethod; if ((getGetRawBondTransactionMethod = TransactionGrpc.getGetRawBondTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getGetRawBondTransactionMethod = TransactionGrpc.getGetRawBondTransactionMethod) == null) { TransactionGrpc.getGetRawBondTransactionMethod = getGetRawBondTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetRawBondTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawBondTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("GetRawBondTransaction")) .build(); } } } return getGetRawBondTransactionMethod; } private static volatile io.grpc.MethodDescriptor getGetRawUnbondTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetRawUnbondTransaction", requestType = pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.class, responseType = pactus.TransactionOuterClass.GetRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetRawUnbondTransactionMethod() { io.grpc.MethodDescriptor getGetRawUnbondTransactionMethod; if ((getGetRawUnbondTransactionMethod = TransactionGrpc.getGetRawUnbondTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getGetRawUnbondTransactionMethod = TransactionGrpc.getGetRawUnbondTransactionMethod) == null) { TransactionGrpc.getGetRawUnbondTransactionMethod = getGetRawUnbondTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetRawUnbondTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("GetRawUnbondTransaction")) .build(); } } } return getGetRawUnbondTransactionMethod; } private static volatile io.grpc.MethodDescriptor getGetRawWithdrawTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetRawWithdrawTransaction", requestType = pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.class, responseType = pactus.TransactionOuterClass.GetRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetRawWithdrawTransactionMethod() { io.grpc.MethodDescriptor getGetRawWithdrawTransactionMethod; if ((getGetRawWithdrawTransactionMethod = TransactionGrpc.getGetRawWithdrawTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getGetRawWithdrawTransactionMethod = TransactionGrpc.getGetRawWithdrawTransactionMethod) == null) { TransactionGrpc.getGetRawWithdrawTransactionMethod = getGetRawWithdrawTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetRawWithdrawTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("GetRawWithdrawTransaction")) .build(); } } } return getGetRawWithdrawTransactionMethod; } private static volatile io.grpc.MethodDescriptor getGetRawBatchTransferTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetRawBatchTransferTransaction", requestType = pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.class, responseType = pactus.TransactionOuterClass.GetRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetRawBatchTransferTransactionMethod() { io.grpc.MethodDescriptor getGetRawBatchTransferTransactionMethod; if ((getGetRawBatchTransferTransactionMethod = TransactionGrpc.getGetRawBatchTransferTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getGetRawBatchTransferTransactionMethod = TransactionGrpc.getGetRawBatchTransferTransactionMethod) == null) { TransactionGrpc.getGetRawBatchTransferTransactionMethod = getGetRawBatchTransferTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetRawBatchTransferTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("GetRawBatchTransferTransaction")) .build(); } } } return getGetRawBatchTransferTransactionMethod; } private static volatile io.grpc.MethodDescriptor getDecodeRawTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "DecodeRawTransaction", requestType = pactus.TransactionOuterClass.DecodeRawTransactionRequest.class, responseType = pactus.TransactionOuterClass.DecodeRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getDecodeRawTransactionMethod() { io.grpc.MethodDescriptor getDecodeRawTransactionMethod; if ((getDecodeRawTransactionMethod = TransactionGrpc.getDecodeRawTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getDecodeRawTransactionMethod = TransactionGrpc.getDecodeRawTransactionMethod) == null) { TransactionGrpc.getDecodeRawTransactionMethod = getDecodeRawTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "DecodeRawTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.DecodeRawTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.DecodeRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("DecodeRawTransaction")) .build(); } } } return getDecodeRawTransactionMethod; } private static volatile io.grpc.MethodDescriptor getCheckTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CheckTransaction", requestType = pactus.TransactionOuterClass.CheckTransactionRequest.class, responseType = pactus.TransactionOuterClass.CheckTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getCheckTransactionMethod() { io.grpc.MethodDescriptor getCheckTransactionMethod; if ((getCheckTransactionMethod = TransactionGrpc.getCheckTransactionMethod) == null) { synchronized (TransactionGrpc.class) { if ((getCheckTransactionMethod = TransactionGrpc.getCheckTransactionMethod) == null) { TransactionGrpc.getCheckTransactionMethod = getCheckTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CheckTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.CheckTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.TransactionOuterClass.CheckTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new TransactionMethodDescriptorSupplier("CheckTransaction")) .build(); } } } return getCheckTransactionMethod; } /** * Creates a new async stub that supports all call types for the service */ public static TransactionStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public TransactionStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionStub(channel, callOptions); } }; return TransactionStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static TransactionBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public TransactionBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionBlockingV2Stub(channel, callOptions); } }; return TransactionBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static TransactionBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public TransactionBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionBlockingStub(channel, callOptions); } }; return TransactionBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static TransactionFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public TransactionFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionFutureStub(channel, callOptions); } }; return TransactionFutureStub.newStub(factory, channel); } /** *
   * Transaction service defines various RPC methods for interacting with transactions.
   * 
*/ public interface AsyncService { /** *
     * GetTransaction retrieves transaction details based on the provided request parameters.
     * 
*/ default void getTransaction(pactus.TransactionOuterClass.GetTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetTransactionMethod(), responseObserver); } /** *
     * CalculateFee calculates the transaction fee based on the specified amount and payload type.
     * 
*/ default void calculateFee(pactus.TransactionOuterClass.CalculateFeeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCalculateFeeMethod(), responseObserver); } /** *
     * BroadcastTransaction broadcasts a signed transaction to the network.
     * 
*/ default void broadcastTransaction(pactus.TransactionOuterClass.BroadcastTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getBroadcastTransactionMethod(), responseObserver); } /** *
     * GetRawTransferTransaction retrieves raw details of a transfer transaction.
     * 
*/ default void getRawTransferTransaction(pactus.TransactionOuterClass.GetRawTransferTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetRawTransferTransactionMethod(), responseObserver); } /** *
     * GetRawBondTransaction retrieves raw details of a bond transaction.
     * 
*/ default void getRawBondTransaction(pactus.TransactionOuterClass.GetRawBondTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetRawBondTransactionMethod(), responseObserver); } /** *
     * GetRawUnbondTransaction retrieves raw details of an unbond transaction.
     * 
*/ default void getRawUnbondTransaction(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetRawUnbondTransactionMethod(), responseObserver); } /** *
     * GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.
     * 
*/ default void getRawWithdrawTransaction(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetRawWithdrawTransactionMethod(), responseObserver); } /** *
     * GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.
     * 
*/ default void getRawBatchTransferTransaction(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetRawBatchTransferTransactionMethod(), responseObserver); } /** *
     * DecodeRawTransaction accepts raw transaction and returns decoded transaction.
     * 
*/ default void decodeRawTransaction(pactus.TransactionOuterClass.DecodeRawTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getDecodeRawTransactionMethod(), responseObserver); } /** *
     * CheckTransaction checks if the transaction is valid and can be included in the blockchain.
     * 
*/ default void checkTransaction(pactus.TransactionOuterClass.CheckTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCheckTransactionMethod(), responseObserver); } } /** * Base class for the server implementation of the service Transaction. *
   * Transaction service defines various RPC methods for interacting with transactions.
   * 
*/ public static abstract class TransactionImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return TransactionGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service Transaction. *
   * Transaction service defines various RPC methods for interacting with transactions.
   * 
*/ public static final class TransactionStub extends io.grpc.stub.AbstractAsyncStub { private TransactionStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TransactionStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionStub(channel, callOptions); } /** *
     * GetTransaction retrieves transaction details based on the provided request parameters.
     * 
*/ public void getTransaction(pactus.TransactionOuterClass.GetTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * CalculateFee calculates the transaction fee based on the specified amount and payload type.
     * 
*/ public void calculateFee(pactus.TransactionOuterClass.CalculateFeeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCalculateFeeMethod(), getCallOptions()), request, responseObserver); } /** *
     * BroadcastTransaction broadcasts a signed transaction to the network.
     * 
*/ public void broadcastTransaction(pactus.TransactionOuterClass.BroadcastTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getBroadcastTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetRawTransferTransaction retrieves raw details of a transfer transaction.
     * 
*/ public void getRawTransferTransaction(pactus.TransactionOuterClass.GetRawTransferTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetRawTransferTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetRawBondTransaction retrieves raw details of a bond transaction.
     * 
*/ public void getRawBondTransaction(pactus.TransactionOuterClass.GetRawBondTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetRawBondTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetRawUnbondTransaction retrieves raw details of an unbond transaction.
     * 
*/ public void getRawUnbondTransaction(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetRawUnbondTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.
     * 
*/ public void getRawWithdrawTransaction(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetRawWithdrawTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.
     * 
*/ public void getRawBatchTransferTransaction(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetRawBatchTransferTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * DecodeRawTransaction accepts raw transaction and returns decoded transaction.
     * 
*/ public void decodeRawTransaction(pactus.TransactionOuterClass.DecodeRawTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getDecodeRawTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * CheckTransaction checks if the transaction is valid and can be included in the blockchain.
     * 
*/ public void checkTransaction(pactus.TransactionOuterClass.CheckTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCheckTransactionMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Transaction. *
   * Transaction service defines various RPC methods for interacting with transactions.
   * 
*/ public static final class TransactionBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub { private TransactionBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TransactionBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionBlockingV2Stub(channel, callOptions); } /** *
     * GetTransaction retrieves transaction details based on the provided request parameters.
     * 
*/ public pactus.TransactionOuterClass.GetTransactionResponse getTransaction(pactus.TransactionOuterClass.GetTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetTransactionMethod(), getCallOptions(), request); } /** *
     * CalculateFee calculates the transaction fee based on the specified amount and payload type.
     * 
*/ public pactus.TransactionOuterClass.CalculateFeeResponse calculateFee(pactus.TransactionOuterClass.CalculateFeeRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getCalculateFeeMethod(), getCallOptions(), request); } /** *
     * BroadcastTransaction broadcasts a signed transaction to the network.
     * 
*/ public pactus.TransactionOuterClass.BroadcastTransactionResponse broadcastTransaction(pactus.TransactionOuterClass.BroadcastTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getBroadcastTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawTransferTransaction retrieves raw details of a transfer transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawTransferTransaction(pactus.TransactionOuterClass.GetRawTransferTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetRawTransferTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawBondTransaction retrieves raw details of a bond transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawBondTransaction(pactus.TransactionOuterClass.GetRawBondTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetRawBondTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawUnbondTransaction retrieves raw details of an unbond transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawUnbondTransaction(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetRawUnbondTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawWithdrawTransaction(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetRawWithdrawTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawBatchTransferTransaction(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetRawBatchTransferTransactionMethod(), getCallOptions(), request); } /** *
     * DecodeRawTransaction accepts raw transaction and returns decoded transaction.
     * 
*/ public pactus.TransactionOuterClass.DecodeRawTransactionResponse decodeRawTransaction(pactus.TransactionOuterClass.DecodeRawTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getDecodeRawTransactionMethod(), getCallOptions(), request); } /** *
     * CheckTransaction checks if the transaction is valid and can be included in the blockchain.
     * 
*/ public pactus.TransactionOuterClass.CheckTransactionResponse checkTransaction(pactus.TransactionOuterClass.CheckTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getCheckTransactionMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Transaction. *
   * Transaction service defines various RPC methods for interacting with transactions.
   * 
*/ public static final class TransactionBlockingStub extends io.grpc.stub.AbstractBlockingStub { private TransactionBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TransactionBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionBlockingStub(channel, callOptions); } /** *
     * GetTransaction retrieves transaction details based on the provided request parameters.
     * 
*/ public pactus.TransactionOuterClass.GetTransactionResponse getTransaction(pactus.TransactionOuterClass.GetTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetTransactionMethod(), getCallOptions(), request); } /** *
     * CalculateFee calculates the transaction fee based on the specified amount and payload type.
     * 
*/ public pactus.TransactionOuterClass.CalculateFeeResponse calculateFee(pactus.TransactionOuterClass.CalculateFeeRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCalculateFeeMethod(), getCallOptions(), request); } /** *
     * BroadcastTransaction broadcasts a signed transaction to the network.
     * 
*/ public pactus.TransactionOuterClass.BroadcastTransactionResponse broadcastTransaction(pactus.TransactionOuterClass.BroadcastTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getBroadcastTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawTransferTransaction retrieves raw details of a transfer transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawTransferTransaction(pactus.TransactionOuterClass.GetRawTransferTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetRawTransferTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawBondTransaction retrieves raw details of a bond transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawBondTransaction(pactus.TransactionOuterClass.GetRawBondTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetRawBondTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawUnbondTransaction retrieves raw details of an unbond transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawUnbondTransaction(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetRawUnbondTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawWithdrawTransaction(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetRawWithdrawTransactionMethod(), getCallOptions(), request); } /** *
     * GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.
     * 
*/ public pactus.TransactionOuterClass.GetRawTransactionResponse getRawBatchTransferTransaction(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetRawBatchTransferTransactionMethod(), getCallOptions(), request); } /** *
     * DecodeRawTransaction accepts raw transaction and returns decoded transaction.
     * 
*/ public pactus.TransactionOuterClass.DecodeRawTransactionResponse decodeRawTransaction(pactus.TransactionOuterClass.DecodeRawTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDecodeRawTransactionMethod(), getCallOptions(), request); } /** *
     * CheckTransaction checks if the transaction is valid and can be included in the blockchain.
     * 
*/ public pactus.TransactionOuterClass.CheckTransactionResponse checkTransaction(pactus.TransactionOuterClass.CheckTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCheckTransactionMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service Transaction. *
   * Transaction service defines various RPC methods for interacting with transactions.
   * 
*/ public static final class TransactionFutureStub extends io.grpc.stub.AbstractFutureStub { private TransactionFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TransactionFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TransactionFutureStub(channel, callOptions); } /** *
     * GetTransaction retrieves transaction details based on the provided request parameters.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getTransaction( pactus.TransactionOuterClass.GetTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetTransactionMethod(), getCallOptions()), request); } /** *
     * CalculateFee calculates the transaction fee based on the specified amount and payload type.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture calculateFee( pactus.TransactionOuterClass.CalculateFeeRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCalculateFeeMethod(), getCallOptions()), request); } /** *
     * BroadcastTransaction broadcasts a signed transaction to the network.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture broadcastTransaction( pactus.TransactionOuterClass.BroadcastTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getBroadcastTransactionMethod(), getCallOptions()), request); } /** *
     * GetRawTransferTransaction retrieves raw details of a transfer transaction.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getRawTransferTransaction( pactus.TransactionOuterClass.GetRawTransferTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetRawTransferTransactionMethod(), getCallOptions()), request); } /** *
     * GetRawBondTransaction retrieves raw details of a bond transaction.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getRawBondTransaction( pactus.TransactionOuterClass.GetRawBondTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetRawBondTransactionMethod(), getCallOptions()), request); } /** *
     * GetRawUnbondTransaction retrieves raw details of an unbond transaction.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getRawUnbondTransaction( pactus.TransactionOuterClass.GetRawUnbondTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetRawUnbondTransactionMethod(), getCallOptions()), request); } /** *
     * GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getRawWithdrawTransaction( pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetRawWithdrawTransactionMethod(), getCallOptions()), request); } /** *
     * GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getRawBatchTransferTransaction( pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetRawBatchTransferTransactionMethod(), getCallOptions()), request); } /** *
     * DecodeRawTransaction accepts raw transaction and returns decoded transaction.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture decodeRawTransaction( pactus.TransactionOuterClass.DecodeRawTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getDecodeRawTransactionMethod(), getCallOptions()), request); } /** *
     * CheckTransaction checks if the transaction is valid and can be included in the blockchain.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture checkTransaction( pactus.TransactionOuterClass.CheckTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCheckTransactionMethod(), getCallOptions()), request); } } private static final int METHODID_GET_TRANSACTION = 0; private static final int METHODID_CALCULATE_FEE = 1; private static final int METHODID_BROADCAST_TRANSACTION = 2; private static final int METHODID_GET_RAW_TRANSFER_TRANSACTION = 3; private static final int METHODID_GET_RAW_BOND_TRANSACTION = 4; private static final int METHODID_GET_RAW_UNBOND_TRANSACTION = 5; private static final int METHODID_GET_RAW_WITHDRAW_TRANSACTION = 6; private static final int METHODID_GET_RAW_BATCH_TRANSFER_TRANSACTION = 7; private static final int METHODID_DECODE_RAW_TRANSACTION = 8; private static final int METHODID_CHECK_TRANSACTION = 9; private static final class MethodHandlers implements io.grpc.stub.ServerCalls.UnaryMethod, io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_GET_TRANSACTION: serviceImpl.getTransaction((pactus.TransactionOuterClass.GetTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_CALCULATE_FEE: serviceImpl.calculateFee((pactus.TransactionOuterClass.CalculateFeeRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_BROADCAST_TRANSACTION: serviceImpl.broadcastTransaction((pactus.TransactionOuterClass.BroadcastTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_RAW_TRANSFER_TRANSACTION: serviceImpl.getRawTransferTransaction((pactus.TransactionOuterClass.GetRawTransferTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_RAW_BOND_TRANSACTION: serviceImpl.getRawBondTransaction((pactus.TransactionOuterClass.GetRawBondTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_RAW_UNBOND_TRANSACTION: serviceImpl.getRawUnbondTransaction((pactus.TransactionOuterClass.GetRawUnbondTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_RAW_WITHDRAW_TRANSACTION: serviceImpl.getRawWithdrawTransaction((pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_RAW_BATCH_TRANSFER_TRANSACTION: serviceImpl.getRawBatchTransferTransaction((pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_DECODE_RAW_TRANSACTION: serviceImpl.decodeRawTransaction((pactus.TransactionOuterClass.DecodeRawTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_CHECK_TRANSACTION: serviceImpl.checkTransaction((pactus.TransactionOuterClass.CheckTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver invoke( io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.GetTransactionRequest, pactus.TransactionOuterClass.GetTransactionResponse>( service, METHODID_GET_TRANSACTION))) .addMethod( getCalculateFeeMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.CalculateFeeRequest, pactus.TransactionOuterClass.CalculateFeeResponse>( service, METHODID_CALCULATE_FEE))) .addMethod( getBroadcastTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.BroadcastTransactionRequest, pactus.TransactionOuterClass.BroadcastTransactionResponse>( service, METHODID_BROADCAST_TRANSACTION))) .addMethod( getGetRawTransferTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.GetRawTransferTransactionRequest, pactus.TransactionOuterClass.GetRawTransactionResponse>( service, METHODID_GET_RAW_TRANSFER_TRANSACTION))) .addMethod( getGetRawBondTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.GetRawBondTransactionRequest, pactus.TransactionOuterClass.GetRawTransactionResponse>( service, METHODID_GET_RAW_BOND_TRANSACTION))) .addMethod( getGetRawUnbondTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.GetRawUnbondTransactionRequest, pactus.TransactionOuterClass.GetRawTransactionResponse>( service, METHODID_GET_RAW_UNBOND_TRANSACTION))) .addMethod( getGetRawWithdrawTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest, pactus.TransactionOuterClass.GetRawTransactionResponse>( service, METHODID_GET_RAW_WITHDRAW_TRANSACTION))) .addMethod( getGetRawBatchTransferTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest, pactus.TransactionOuterClass.GetRawTransactionResponse>( service, METHODID_GET_RAW_BATCH_TRANSFER_TRANSACTION))) .addMethod( getDecodeRawTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.DecodeRawTransactionRequest, pactus.TransactionOuterClass.DecodeRawTransactionResponse>( service, METHODID_DECODE_RAW_TRANSACTION))) .addMethod( getCheckTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.TransactionOuterClass.CheckTransactionRequest, pactus.TransactionOuterClass.CheckTransactionResponse>( service, METHODID_CHECK_TRANSACTION))) .build(); } private static abstract class TransactionBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { TransactionBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return pactus.TransactionOuterClass.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Transaction"); } } private static final class TransactionFileDescriptorSupplier extends TransactionBaseDescriptorSupplier { TransactionFileDescriptorSupplier() {} } private static final class TransactionMethodDescriptorSupplier extends TransactionBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; TransactionMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (TransactionGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new TransactionFileDescriptorSupplier()) .addMethod(getGetTransactionMethod()) .addMethod(getCalculateFeeMethod()) .addMethod(getBroadcastTransactionMethod()) .addMethod(getGetRawTransferTransactionMethod()) .addMethod(getGetRawBondTransactionMethod()) .addMethod(getGetRawUnbondTransactionMethod()) .addMethod(getGetRawWithdrawTransactionMethod()) .addMethod(getGetRawBatchTransferTransactionMethod()) .addMethod(getDecodeRawTransactionMethod()) .addMethod(getCheckTransactionMethod()) .build(); } } } return result; } } ================================================ FILE: www/grpc/gen/java/pactus/TransactionOuterClass.java ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: transaction.proto // Protobuf Java Version: 4.33.2 package pactus; @com.google.protobuf.Generated public final class TransactionOuterClass extends com.google.protobuf.GeneratedFile { private TransactionOuterClass() {} static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "TransactionOuterClass"); } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** *
   * Enumeration for different types of transaction payloads.
   * 
* * Protobuf enum {@code pactus.PayloadType} */ public enum PayloadType implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Unspecified payload type.
     * 
* * PAYLOAD_TYPE_UNSPECIFIED = 0; */ PAYLOAD_TYPE_UNSPECIFIED(0), /** *
     * Transfer payload type.
     * 
* * PAYLOAD_TYPE_TRANSFER = 1; */ PAYLOAD_TYPE_TRANSFER(1), /** *
     * Bond payload type.
     * 
* * PAYLOAD_TYPE_BOND = 2; */ PAYLOAD_TYPE_BOND(2), /** *
     * Sortition payload type.
     * 
* * PAYLOAD_TYPE_SORTITION = 3; */ PAYLOAD_TYPE_SORTITION(3), /** *
     * Unbond payload type.
     * 
* * PAYLOAD_TYPE_UNBOND = 4; */ PAYLOAD_TYPE_UNBOND(4), /** *
     * Withdraw payload type.
     * 
* * PAYLOAD_TYPE_WITHDRAW = 5; */ PAYLOAD_TYPE_WITHDRAW(5), /** *
     * Batch transfer payload type.
     * 
* * PAYLOAD_TYPE_BATCH_TRANSFER = 6; */ PAYLOAD_TYPE_BATCH_TRANSFER(6), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadType"); } /** *
     * Unspecified payload type.
     * 
* * PAYLOAD_TYPE_UNSPECIFIED = 0; */ public static final int PAYLOAD_TYPE_UNSPECIFIED_VALUE = 0; /** *
     * Transfer payload type.
     * 
* * PAYLOAD_TYPE_TRANSFER = 1; */ public static final int PAYLOAD_TYPE_TRANSFER_VALUE = 1; /** *
     * Bond payload type.
     * 
* * PAYLOAD_TYPE_BOND = 2; */ public static final int PAYLOAD_TYPE_BOND_VALUE = 2; /** *
     * Sortition payload type.
     * 
* * PAYLOAD_TYPE_SORTITION = 3; */ public static final int PAYLOAD_TYPE_SORTITION_VALUE = 3; /** *
     * Unbond payload type.
     * 
* * PAYLOAD_TYPE_UNBOND = 4; */ public static final int PAYLOAD_TYPE_UNBOND_VALUE = 4; /** *
     * Withdraw payload type.
     * 
* * PAYLOAD_TYPE_WITHDRAW = 5; */ public static final int PAYLOAD_TYPE_WITHDRAW_VALUE = 5; /** *
     * Batch transfer payload type.
     * 
* * PAYLOAD_TYPE_BATCH_TRANSFER = 6; */ public static final int PAYLOAD_TYPE_BATCH_TRANSFER_VALUE = 6; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static PayloadType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static PayloadType forNumber(int value) { switch (value) { case 0: return PAYLOAD_TYPE_UNSPECIFIED; case 1: return PAYLOAD_TYPE_TRANSFER; case 2: return PAYLOAD_TYPE_BOND; case 3: return PAYLOAD_TYPE_SORTITION; case 4: return PAYLOAD_TYPE_UNBOND; case 5: return PAYLOAD_TYPE_WITHDRAW; case 6: return PAYLOAD_TYPE_BATCH_TRANSFER; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< PayloadType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public PayloadType findValueByNumber(int number) { return PayloadType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.TransactionOuterClass.getDescriptor().getEnumTypes().get(0); } private static final PayloadType[] VALUES = values(); public static PayloadType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private PayloadType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.PayloadType) } /** *
   * Enumeration for verbosity levels when requesting transaction details.
   * 
* * Protobuf enum {@code pactus.TransactionVerbosity} */ public enum TransactionVerbosity implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Request transaction data only.
     * 
* * TRANSACTION_VERBOSITY_DATA = 0; */ TRANSACTION_VERBOSITY_DATA(0), /** *
     * Request detailed transaction information.
     * 
* * TRANSACTION_VERBOSITY_INFO = 1; */ TRANSACTION_VERBOSITY_INFO(1), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "TransactionVerbosity"); } /** *
     * Request transaction data only.
     * 
* * TRANSACTION_VERBOSITY_DATA = 0; */ public static final int TRANSACTION_VERBOSITY_DATA_VALUE = 0; /** *
     * Request detailed transaction information.
     * 
* * TRANSACTION_VERBOSITY_INFO = 1; */ public static final int TRANSACTION_VERBOSITY_INFO_VALUE = 1; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TransactionVerbosity valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static TransactionVerbosity forNumber(int value) { switch (value) { case 0: return TRANSACTION_VERBOSITY_DATA; case 1: return TRANSACTION_VERBOSITY_INFO; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< TransactionVerbosity> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public TransactionVerbosity findValueByNumber(int number) { return TransactionVerbosity.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.TransactionOuterClass.getDescriptor().getEnumTypes().get(1); } private static final TransactionVerbosity[] VALUES = values(); public static TransactionVerbosity valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TransactionVerbosity(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.TransactionVerbosity) } public interface GetTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The unique ID of the transaction to retrieve.
     * 
* * string id = 1 [json_name = "id"]; * @return The id. */ java.lang.String getId(); /** *
     * The unique ID of the transaction to retrieve.
     * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ com.google.protobuf.ByteString getIdBytes(); /** *
     * The verbosity level for transaction details.
     * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The enum numeric value on the wire for verbosity. */ int getVerbosityValue(); /** *
     * The verbosity level for transaction details.
     * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The verbosity. */ pactus.TransactionOuterClass.TransactionVerbosity getVerbosity(); } /** *
   * Request message for retrieving transaction details.
   * 
* * Protobuf type {@code pactus.GetTransactionRequest} */ public static final class GetTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTransactionRequest) GetTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTransactionRequest"); } // Use GetTransactionRequest.newBuilder() to construct. private GetTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTransactionRequest() { id_ = ""; verbosity_ = 0; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetTransactionRequest.class, pactus.TransactionOuterClass.GetTransactionRequest.Builder.class); } public static final int ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object id_ = ""; /** *
     * The unique ID of the transaction to retrieve.
     * 
* * string id = 1 [json_name = "id"]; * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** *
     * The unique ID of the transaction to retrieve.
     * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERBOSITY_FIELD_NUMBER = 2; private int verbosity_ = 0; /** *
     * The verbosity level for transaction details.
     * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The enum numeric value on the wire for verbosity. */ @java.lang.Override public int getVerbosityValue() { return verbosity_; } /** *
     * The verbosity level for transaction details.
     * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The verbosity. */ @java.lang.Override public pactus.TransactionOuterClass.TransactionVerbosity getVerbosity() { pactus.TransactionOuterClass.TransactionVerbosity result = pactus.TransactionOuterClass.TransactionVerbosity.forNumber(verbosity_); return result == null ? pactus.TransactionOuterClass.TransactionVerbosity.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, id_); } if (verbosity_ != pactus.TransactionOuterClass.TransactionVerbosity.TRANSACTION_VERBOSITY_DATA.getNumber()) { output.writeEnum(2, verbosity_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, id_); } if (verbosity_ != pactus.TransactionOuterClass.TransactionVerbosity.TRANSACTION_VERBOSITY_DATA.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, verbosity_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.GetTransactionRequest other = (pactus.TransactionOuterClass.GetTransactionRequest) obj; if (!getId() .equals(other.getId())) return false; if (verbosity_ != other.verbosity_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (37 * hash) + VERBOSITY_FIELD_NUMBER; hash = (53 * hash) + verbosity_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving transaction details.
     * 
* * Protobuf type {@code pactus.GetTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTransactionRequest) pactus.TransactionOuterClass.GetTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetTransactionRequest.class, pactus.TransactionOuterClass.GetTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.GetTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; id_ = ""; verbosity_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionRequest build() { pactus.TransactionOuterClass.GetTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionRequest buildPartial() { pactus.TransactionOuterClass.GetTransactionRequest result = new pactus.TransactionOuterClass.GetTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.id_ = id_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.verbosity_ = verbosity_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.GetTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetTransactionRequest other) { if (other == pactus.TransactionOuterClass.GetTransactionRequest.getDefaultInstance()) return this; if (!other.getId().isEmpty()) { id_ = other.id_; bitField0_ |= 0x00000001; onChanged(); } if (other.verbosity_ != 0) { setVerbosityValue(other.getVerbosityValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { id_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { verbosity_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object id_ = ""; /** *
       * The unique ID of the transaction to retrieve.
       * 
* * string id = 1 [json_name = "id"]; * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The unique ID of the transaction to retrieve.
       * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The unique ID of the transaction to retrieve.
       * 
* * string id = 1 [json_name = "id"]; * @param value The id to set. * @return This builder for chaining. */ public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The unique ID of the transaction to retrieve.
       * 
* * string id = 1 [json_name = "id"]; * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The unique ID of the transaction to retrieve.
       * 
* * string id = 1 [json_name = "id"]; * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int verbosity_ = 0; /** *
       * The verbosity level for transaction details.
       * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The enum numeric value on the wire for verbosity. */ @java.lang.Override public int getVerbosityValue() { return verbosity_; } /** *
       * The verbosity level for transaction details.
       * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @param value The enum numeric value on the wire for verbosity to set. * @return This builder for chaining. */ public Builder setVerbosityValue(int value) { verbosity_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The verbosity level for transaction details.
       * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return The verbosity. */ @java.lang.Override public pactus.TransactionOuterClass.TransactionVerbosity getVerbosity() { pactus.TransactionOuterClass.TransactionVerbosity result = pactus.TransactionOuterClass.TransactionVerbosity.forNumber(verbosity_); return result == null ? pactus.TransactionOuterClass.TransactionVerbosity.UNRECOGNIZED : result; } /** *
       * The verbosity level for transaction details.
       * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @param value The verbosity to set. * @return This builder for chaining. */ public Builder setVerbosity(pactus.TransactionOuterClass.TransactionVerbosity value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; verbosity_ = value.getNumber(); onChanged(); return this; } /** *
       * The verbosity level for transaction details.
       * 
* * .pactus.TransactionVerbosity verbosity = 2 [json_name = "verbosity"]; * @return This builder for chaining. */ public Builder clearVerbosity() { bitField0_ = (bitField0_ & ~0x00000002); verbosity_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.GetTransactionRequest) private static final pactus.TransactionOuterClass.GetTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetTransactionRequest(); } public static pactus.TransactionOuterClass.GetTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTransactionResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTransactionResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The height of the block containing the transaction.
     * 
* * uint32 block_height = 1 [json_name = "blockHeight"]; * @return The blockHeight. */ int getBlockHeight(); /** *
     * The UNIX timestamp of the block containing the transaction.
     * 
* * uint32 block_time = 2 [json_name = "blockTime"]; * @return The blockTime. */ int getBlockTime(); /** *
     * Detailed information about the transaction.
     * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; * @return Whether the transaction field is set. */ boolean hasTransaction(); /** *
     * Detailed information about the transaction.
     * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; * @return The transaction. */ pactus.TransactionOuterClass.TransactionInfo getTransaction(); /** *
     * Detailed information about the transaction.
     * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ pactus.TransactionOuterClass.TransactionInfoOrBuilder getTransactionOrBuilder(); } /** *
   * Response message contains details of a transaction.
   * 
* * Protobuf type {@code pactus.GetTransactionResponse} */ public static final class GetTransactionResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTransactionResponse) GetTransactionResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTransactionResponse"); } // Use GetTransactionResponse.newBuilder() to construct. private GetTransactionResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTransactionResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetTransactionResponse.class, pactus.TransactionOuterClass.GetTransactionResponse.Builder.class); } private int bitField0_; public static final int BLOCK_HEIGHT_FIELD_NUMBER = 1; private int blockHeight_ = 0; /** *
     * The height of the block containing the transaction.
     * 
* * uint32 block_height = 1 [json_name = "blockHeight"]; * @return The blockHeight. */ @java.lang.Override public int getBlockHeight() { return blockHeight_; } public static final int BLOCK_TIME_FIELD_NUMBER = 2; private int blockTime_ = 0; /** *
     * The UNIX timestamp of the block containing the transaction.
     * 
* * uint32 block_time = 2 [json_name = "blockTime"]; * @return The blockTime. */ @java.lang.Override public int getBlockTime() { return blockTime_; } public static final int TRANSACTION_FIELD_NUMBER = 3; private pactus.TransactionOuterClass.TransactionInfo transaction_; /** *
     * Detailed information about the transaction.
     * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; * @return Whether the transaction field is set. */ @java.lang.Override public boolean hasTransaction() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Detailed information about the transaction.
     * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; * @return The transaction. */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo getTransaction() { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } /** *
     * Detailed information about the transaction.
     * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTransactionOrBuilder() { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (blockHeight_ != 0) { output.writeUInt32(1, blockHeight_); } if (blockTime_ != 0) { output.writeUInt32(2, blockTime_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getTransaction()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (blockHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, blockHeight_); } if (blockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(2, blockTime_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, getTransaction()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetTransactionResponse)) { return super.equals(obj); } pactus.TransactionOuterClass.GetTransactionResponse other = (pactus.TransactionOuterClass.GetTransactionResponse) obj; if (getBlockHeight() != other.getBlockHeight()) return false; if (getBlockTime() != other.getBlockTime()) return false; if (hasTransaction() != other.hasTransaction()) return false; if (hasTransaction()) { if (!getTransaction() .equals(other.getTransaction())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + BLOCK_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getBlockHeight(); hash = (37 * hash) + BLOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getBlockTime(); if (hasTransaction()) { hash = (37 * hash) + TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getTransaction().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetTransactionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetTransactionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains details of a transaction.
     * 
* * Protobuf type {@code pactus.GetTransactionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTransactionResponse) pactus.TransactionOuterClass.GetTransactionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetTransactionResponse.class, pactus.TransactionOuterClass.GetTransactionResponse.Builder.class); } // Construct using pactus.TransactionOuterClass.GetTransactionResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetTransactionFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; blockHeight_ = 0; blockTime_ = 0; transaction_ = null; if (transactionBuilder_ != null) { transactionBuilder_.dispose(); transactionBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetTransactionResponse_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionResponse getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetTransactionResponse.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionResponse build() { pactus.TransactionOuterClass.GetTransactionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionResponse buildPartial() { pactus.TransactionOuterClass.GetTransactionResponse result = new pactus.TransactionOuterClass.GetTransactionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetTransactionResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.blockHeight_ = blockHeight_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.blockTime_ = blockTime_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.transaction_ = transactionBuilder_ == null ? transaction_ : transactionBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetTransactionResponse) { return mergeFrom((pactus.TransactionOuterClass.GetTransactionResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetTransactionResponse other) { if (other == pactus.TransactionOuterClass.GetTransactionResponse.getDefaultInstance()) return this; if (other.getBlockHeight() != 0) { setBlockHeight(other.getBlockHeight()); } if (other.getBlockTime() != 0) { setBlockTime(other.getBlockTime()); } if (other.hasTransaction()) { mergeTransaction(other.getTransaction()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { blockHeight_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { blockTime_ = input.readUInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { input.readMessage( internalGetTransactionFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int blockHeight_ ; /** *
       * The height of the block containing the transaction.
       * 
* * uint32 block_height = 1 [json_name = "blockHeight"]; * @return The blockHeight. */ @java.lang.Override public int getBlockHeight() { return blockHeight_; } /** *
       * The height of the block containing the transaction.
       * 
* * uint32 block_height = 1 [json_name = "blockHeight"]; * @param value The blockHeight to set. * @return This builder for chaining. */ public Builder setBlockHeight(int value) { blockHeight_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The height of the block containing the transaction.
       * 
* * uint32 block_height = 1 [json_name = "blockHeight"]; * @return This builder for chaining. */ public Builder clearBlockHeight() { bitField0_ = (bitField0_ & ~0x00000001); blockHeight_ = 0; onChanged(); return this; } private int blockTime_ ; /** *
       * The UNIX timestamp of the block containing the transaction.
       * 
* * uint32 block_time = 2 [json_name = "blockTime"]; * @return The blockTime. */ @java.lang.Override public int getBlockTime() { return blockTime_; } /** *
       * The UNIX timestamp of the block containing the transaction.
       * 
* * uint32 block_time = 2 [json_name = "blockTime"]; * @param value The blockTime to set. * @return This builder for chaining. */ public Builder setBlockTime(int value) { blockTime_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The UNIX timestamp of the block containing the transaction.
       * 
* * uint32 block_time = 2 [json_name = "blockTime"]; * @return This builder for chaining. */ public Builder clearBlockTime() { bitField0_ = (bitField0_ & ~0x00000002); blockTime_ = 0; onChanged(); return this; } private pactus.TransactionOuterClass.TransactionInfo transaction_; private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> transactionBuilder_; /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; * @return Whether the transaction field is set. */ public boolean hasTransaction() { return ((bitField0_ & 0x00000004) != 0); } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; * @return The transaction. */ public pactus.TransactionOuterClass.TransactionInfo getTransaction() { if (transactionBuilder_ == null) { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } else { return transactionBuilder_.getMessage(); } } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ public Builder setTransaction(pactus.TransactionOuterClass.TransactionInfo value) { if (transactionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } transaction_ = value; } else { transactionBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ public Builder setTransaction( pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (transactionBuilder_ == null) { transaction_ = builderForValue.build(); } else { transactionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ public Builder mergeTransaction(pactus.TransactionOuterClass.TransactionInfo value) { if (transactionBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && transaction_ != null && transaction_ != pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()) { getTransactionBuilder().mergeFrom(value); } else { transaction_ = value; } } else { transactionBuilder_.mergeFrom(value); } if (transaction_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ public Builder clearTransaction() { bitField0_ = (bitField0_ & ~0x00000004); transaction_ = null; if (transactionBuilder_ != null) { transactionBuilder_.dispose(); transactionBuilder_ = null; } onChanged(); return this; } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder getTransactionBuilder() { bitField0_ |= 0x00000004; onChanged(); return internalGetTransactionFieldBuilder().getBuilder(); } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTransactionOrBuilder() { if (transactionBuilder_ != null) { return transactionBuilder_.getMessageOrBuilder(); } else { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } } /** *
       * Detailed information about the transaction.
       * 
* * .pactus.TransactionInfo transaction = 3 [json_name = "transaction"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> internalGetTransactionFieldBuilder() { if (transactionBuilder_ == null) { transactionBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder>( getTransaction(), getParentForChildren(), isClean()); transaction_ = null; } return transactionBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetTransactionResponse) } // @@protoc_insertion_point(class_scope:pactus.GetTransactionResponse) private static final pactus.TransactionOuterClass.GetTransactionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetTransactionResponse(); } public static pactus.TransactionOuterClass.GetTransactionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTransactionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetTransactionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CalculateFeeRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CalculateFeeRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The amount involved in the transaction, specified in NanoPAC.
     * 
* * int64 amount = 1 [json_name = "amount"]; * @return The amount. */ long getAmount(); /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ int getPayloadTypeValue(); /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return The payloadType. */ pactus.TransactionOuterClass.PayloadType getPayloadType(); /** *
     * Indicates if the amount should be fixed and include the fee.
     * 
* * bool fixed_amount = 3 [json_name = "fixedAmount"]; * @return The fixedAmount. */ boolean getFixedAmount(); } /** *
   * Request message for calculating transaction fee.
   * 
* * Protobuf type {@code pactus.CalculateFeeRequest} */ public static final class CalculateFeeRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CalculateFeeRequest) CalculateFeeRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CalculateFeeRequest"); } // Use CalculateFeeRequest.newBuilder() to construct. private CalculateFeeRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CalculateFeeRequest() { payloadType_ = 0; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CalculateFeeRequest.class, pactus.TransactionOuterClass.CalculateFeeRequest.Builder.class); } public static final int AMOUNT_FIELD_NUMBER = 1; private long amount_ = 0L; /** *
     * The amount involved in the transaction, specified in NanoPAC.
     * 
* * int64 amount = 1 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } public static final int PAYLOAD_TYPE_FIELD_NUMBER = 2; private int payloadType_ = 0; /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } public static final int FIXED_AMOUNT_FIELD_NUMBER = 3; private boolean fixedAmount_ = false; /** *
     * Indicates if the amount should be fixed and include the fee.
     * 
* * bool fixed_amount = 3 [json_name = "fixedAmount"]; * @return The fixedAmount. */ @java.lang.Override public boolean getFixedAmount() { return fixedAmount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (amount_ != 0L) { output.writeInt64(1, amount_); } if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(2, payloadType_); } if (fixedAmount_ != false) { output.writeBool(3, fixedAmount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, amount_); } if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, payloadType_); } if (fixedAmount_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, fixedAmount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.CalculateFeeRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.CalculateFeeRequest other = (pactus.TransactionOuterClass.CalculateFeeRequest) obj; if (getAmount() != other.getAmount()) return false; if (payloadType_ != other.payloadType_) return false; if (getFixedAmount() != other.getFixedAmount()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (37 * hash) + PAYLOAD_TYPE_FIELD_NUMBER; hash = (53 * hash) + payloadType_; hash = (37 * hash) + FIXED_AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getFixedAmount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CalculateFeeRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.CalculateFeeRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for calculating transaction fee.
     * 
* * Protobuf type {@code pactus.CalculateFeeRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CalculateFeeRequest) pactus.TransactionOuterClass.CalculateFeeRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CalculateFeeRequest.class, pactus.TransactionOuterClass.CalculateFeeRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.CalculateFeeRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; amount_ = 0L; payloadType_ = 0; fixedAmount_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.CalculateFeeRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeRequest build() { pactus.TransactionOuterClass.CalculateFeeRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeRequest buildPartial() { pactus.TransactionOuterClass.CalculateFeeRequest result = new pactus.TransactionOuterClass.CalculateFeeRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.CalculateFeeRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.amount_ = amount_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.payloadType_ = payloadType_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.fixedAmount_ = fixedAmount_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.CalculateFeeRequest) { return mergeFrom((pactus.TransactionOuterClass.CalculateFeeRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.CalculateFeeRequest other) { if (other == pactus.TransactionOuterClass.CalculateFeeRequest.getDefaultInstance()) return this; if (other.getAmount() != 0L) { setAmount(other.getAmount()); } if (other.payloadType_ != 0) { setPayloadTypeValue(other.getPayloadTypeValue()); } if (other.getFixedAmount() != false) { setFixedAmount(other.getFixedAmount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { amount_ = input.readInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { payloadType_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { fixedAmount_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private long amount_ ; /** *
       * The amount involved in the transaction, specified in NanoPAC.
       * 
* * int64 amount = 1 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The amount involved in the transaction, specified in NanoPAC.
       * 
* * int64 amount = 1 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The amount involved in the transaction, specified in NanoPAC.
       * 
* * int64 amount = 1 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000001); amount_ = 0L; onChanged(); return this; } private int payloadType_ = 0; /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @param value The enum numeric value on the wire for payloadType to set. * @return This builder for chaining. */ public Builder setPayloadTypeValue(int value) { payloadType_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @param value The payloadType to set. * @return This builder for chaining. */ public Builder setPayloadType(pactus.TransactionOuterClass.PayloadType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; payloadType_ = value.getNumber(); onChanged(); return this; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 2 [json_name = "payloadType"]; * @return This builder for chaining. */ public Builder clearPayloadType() { bitField0_ = (bitField0_ & ~0x00000002); payloadType_ = 0; onChanged(); return this; } private boolean fixedAmount_ ; /** *
       * Indicates if the amount should be fixed and include the fee.
       * 
* * bool fixed_amount = 3 [json_name = "fixedAmount"]; * @return The fixedAmount. */ @java.lang.Override public boolean getFixedAmount() { return fixedAmount_; } /** *
       * Indicates if the amount should be fixed and include the fee.
       * 
* * bool fixed_amount = 3 [json_name = "fixedAmount"]; * @param value The fixedAmount to set. * @return This builder for chaining. */ public Builder setFixedAmount(boolean value) { fixedAmount_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Indicates if the amount should be fixed and include the fee.
       * 
* * bool fixed_amount = 3 [json_name = "fixedAmount"]; * @return This builder for chaining. */ public Builder clearFixedAmount() { bitField0_ = (bitField0_ & ~0x00000004); fixedAmount_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CalculateFeeRequest) } // @@protoc_insertion_point(class_scope:pactus.CalculateFeeRequest) private static final pactus.TransactionOuterClass.CalculateFeeRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.CalculateFeeRequest(); } public static pactus.TransactionOuterClass.CalculateFeeRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CalculateFeeRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CalculateFeeResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CalculateFeeResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The calculated amount in NanoPAC.
     * 
* * int64 amount = 1 [json_name = "amount"]; * @return The amount. */ long getAmount(); /** *
     * The calculated transaction fee in NanoPAC.
     * 
* * int64 fee = 2 [json_name = "fee"]; * @return The fee. */ long getFee(); } /** *
   * Response message contains the calculated transaction fee.
   * 
* * Protobuf type {@code pactus.CalculateFeeResponse} */ public static final class CalculateFeeResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CalculateFeeResponse) CalculateFeeResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CalculateFeeResponse"); } // Use CalculateFeeResponse.newBuilder() to construct. private CalculateFeeResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CalculateFeeResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CalculateFeeResponse.class, pactus.TransactionOuterClass.CalculateFeeResponse.Builder.class); } public static final int AMOUNT_FIELD_NUMBER = 1; private long amount_ = 0L; /** *
     * The calculated amount in NanoPAC.
     * 
* * int64 amount = 1 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } public static final int FEE_FIELD_NUMBER = 2; private long fee_ = 0L; /** *
     * The calculated transaction fee in NanoPAC.
     * 
* * int64 fee = 2 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (amount_ != 0L) { output.writeInt64(1, amount_); } if (fee_ != 0L) { output.writeInt64(2, fee_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, amount_); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, fee_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.CalculateFeeResponse)) { return super.equals(obj); } pactus.TransactionOuterClass.CalculateFeeResponse other = (pactus.TransactionOuterClass.CalculateFeeResponse) obj; if (getAmount() != other.getAmount()) return false; if (getFee() != other.getFee()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CalculateFeeResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.CalculateFeeResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the calculated transaction fee.
     * 
* * Protobuf type {@code pactus.CalculateFeeResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CalculateFeeResponse) pactus.TransactionOuterClass.CalculateFeeResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CalculateFeeResponse.class, pactus.TransactionOuterClass.CalculateFeeResponse.Builder.class); } // Construct using pactus.TransactionOuterClass.CalculateFeeResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; amount_ = 0L; fee_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_CalculateFeeResponse_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeResponse getDefaultInstanceForType() { return pactus.TransactionOuterClass.CalculateFeeResponse.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeResponse build() { pactus.TransactionOuterClass.CalculateFeeResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeResponse buildPartial() { pactus.TransactionOuterClass.CalculateFeeResponse result = new pactus.TransactionOuterClass.CalculateFeeResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.CalculateFeeResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.amount_ = amount_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.fee_ = fee_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.CalculateFeeResponse) { return mergeFrom((pactus.TransactionOuterClass.CalculateFeeResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.CalculateFeeResponse other) { if (other == pactus.TransactionOuterClass.CalculateFeeResponse.getDefaultInstance()) return this; if (other.getAmount() != 0L) { setAmount(other.getAmount()); } if (other.getFee() != 0L) { setFee(other.getFee()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { amount_ = input.readInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { fee_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private long amount_ ; /** *
       * The calculated amount in NanoPAC.
       * 
* * int64 amount = 1 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The calculated amount in NanoPAC.
       * 
* * int64 amount = 1 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The calculated amount in NanoPAC.
       * 
* * int64 amount = 1 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000001); amount_ = 0L; onChanged(); return this; } private long fee_ ; /** *
       * The calculated transaction fee in NanoPAC.
       * 
* * int64 fee = 2 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The calculated transaction fee in NanoPAC.
       * 
* * int64 fee = 2 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The calculated transaction fee in NanoPAC.
       * 
* * int64 fee = 2 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000002); fee_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CalculateFeeResponse) } // @@protoc_insertion_point(class_scope:pactus.CalculateFeeResponse) private static final pactus.TransactionOuterClass.CalculateFeeResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.CalculateFeeResponse(); } public static pactus.TransactionOuterClass.CalculateFeeResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CalculateFeeResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.CalculateFeeResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface BroadcastTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.BroadcastTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The signed raw transaction data to be broadcasted.
     * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return The signedRawTransaction. */ java.lang.String getSignedRawTransaction(); /** *
     * The signed raw transaction data to be broadcasted.
     * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return The bytes for signedRawTransaction. */ com.google.protobuf.ByteString getSignedRawTransactionBytes(); } /** *
   * Request message for broadcasting a signed transaction to the network.
   * 
* * Protobuf type {@code pactus.BroadcastTransactionRequest} */ public static final class BroadcastTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.BroadcastTransactionRequest) BroadcastTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "BroadcastTransactionRequest"); } // Use BroadcastTransactionRequest.newBuilder() to construct. private BroadcastTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private BroadcastTransactionRequest() { signedRawTransaction_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.BroadcastTransactionRequest.class, pactus.TransactionOuterClass.BroadcastTransactionRequest.Builder.class); } public static final int SIGNED_RAW_TRANSACTION_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object signedRawTransaction_ = ""; /** *
     * The signed raw transaction data to be broadcasted.
     * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return The signedRawTransaction. */ @java.lang.Override public java.lang.String getSignedRawTransaction() { java.lang.Object ref = signedRawTransaction_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signedRawTransaction_ = s; return s; } } /** *
     * The signed raw transaction data to be broadcasted.
     * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return The bytes for signedRawTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getSignedRawTransactionBytes() { java.lang.Object ref = signedRawTransaction_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signedRawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signedRawTransaction_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, signedRawTransaction_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signedRawTransaction_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, signedRawTransaction_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.BroadcastTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.BroadcastTransactionRequest other = (pactus.TransactionOuterClass.BroadcastTransactionRequest) obj; if (!getSignedRawTransaction() .equals(other.getSignedRawTransaction())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SIGNED_RAW_TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getSignedRawTransaction().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.BroadcastTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for broadcasting a signed transaction to the network.
     * 
* * Protobuf type {@code pactus.BroadcastTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.BroadcastTransactionRequest) pactus.TransactionOuterClass.BroadcastTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.BroadcastTransactionRequest.class, pactus.TransactionOuterClass.BroadcastTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.BroadcastTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; signedRawTransaction_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.BroadcastTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionRequest build() { pactus.TransactionOuterClass.BroadcastTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionRequest buildPartial() { pactus.TransactionOuterClass.BroadcastTransactionRequest result = new pactus.TransactionOuterClass.BroadcastTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.BroadcastTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.signedRawTransaction_ = signedRawTransaction_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.BroadcastTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.BroadcastTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.BroadcastTransactionRequest other) { if (other == pactus.TransactionOuterClass.BroadcastTransactionRequest.getDefaultInstance()) return this; if (!other.getSignedRawTransaction().isEmpty()) { signedRawTransaction_ = other.signedRawTransaction_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { signedRawTransaction_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object signedRawTransaction_ = ""; /** *
       * The signed raw transaction data to be broadcasted.
       * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return The signedRawTransaction. */ public java.lang.String getSignedRawTransaction() { java.lang.Object ref = signedRawTransaction_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signedRawTransaction_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signed raw transaction data to be broadcasted.
       * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return The bytes for signedRawTransaction. */ public com.google.protobuf.ByteString getSignedRawTransactionBytes() { java.lang.Object ref = signedRawTransaction_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signedRawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signed raw transaction data to be broadcasted.
       * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @param value The signedRawTransaction to set. * @return This builder for chaining. */ public Builder setSignedRawTransaction( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signedRawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The signed raw transaction data to be broadcasted.
       * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @return This builder for chaining. */ public Builder clearSignedRawTransaction() { signedRawTransaction_ = getDefaultInstance().getSignedRawTransaction(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The signed raw transaction data to be broadcasted.
       * 
* * string signed_raw_transaction = 1 [json_name = "signedRawTransaction"]; * @param value The bytes for signedRawTransaction to set. * @return This builder for chaining. */ public Builder setSignedRawTransactionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signedRawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.BroadcastTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.BroadcastTransactionRequest) private static final pactus.TransactionOuterClass.BroadcastTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.BroadcastTransactionRequest(); } public static pactus.TransactionOuterClass.BroadcastTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public BroadcastTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface BroadcastTransactionResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.BroadcastTransactionResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The unique ID of the broadcasted transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The id. */ java.lang.String getId(); /** *
     * The unique ID of the broadcasted transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ com.google.protobuf.ByteString getIdBytes(); } /** *
   * Response message contains the ID of the broadcasted transaction.
   * 
* * Protobuf type {@code pactus.BroadcastTransactionResponse} */ public static final class BroadcastTransactionResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.BroadcastTransactionResponse) BroadcastTransactionResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "BroadcastTransactionResponse"); } // Use BroadcastTransactionResponse.newBuilder() to construct. private BroadcastTransactionResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private BroadcastTransactionResponse() { id_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.BroadcastTransactionResponse.class, pactus.TransactionOuterClass.BroadcastTransactionResponse.Builder.class); } public static final int ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object id_ = ""; /** *
     * The unique ID of the broadcasted transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** *
     * The unique ID of the broadcasted transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, id_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, id_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.BroadcastTransactionResponse)) { return super.equals(obj); } pactus.TransactionOuterClass.BroadcastTransactionResponse other = (pactus.TransactionOuterClass.BroadcastTransactionResponse) obj; if (!getId() .equals(other.getId())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.BroadcastTransactionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the ID of the broadcasted transaction.
     * 
* * Protobuf type {@code pactus.BroadcastTransactionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.BroadcastTransactionResponse) pactus.TransactionOuterClass.BroadcastTransactionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.BroadcastTransactionResponse.class, pactus.TransactionOuterClass.BroadcastTransactionResponse.Builder.class); } // Construct using pactus.TransactionOuterClass.BroadcastTransactionResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; id_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_BroadcastTransactionResponse_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionResponse getDefaultInstanceForType() { return pactus.TransactionOuterClass.BroadcastTransactionResponse.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionResponse build() { pactus.TransactionOuterClass.BroadcastTransactionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionResponse buildPartial() { pactus.TransactionOuterClass.BroadcastTransactionResponse result = new pactus.TransactionOuterClass.BroadcastTransactionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.BroadcastTransactionResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.id_ = id_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.BroadcastTransactionResponse) { return mergeFrom((pactus.TransactionOuterClass.BroadcastTransactionResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.BroadcastTransactionResponse other) { if (other == pactus.TransactionOuterClass.BroadcastTransactionResponse.getDefaultInstance()) return this; if (!other.getId().isEmpty()) { id_ = other.id_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { id_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object id_ = ""; /** *
       * The unique ID of the broadcasted transaction.
       * 
* * string id = 1 [json_name = "id"]; * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The unique ID of the broadcasted transaction.
       * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The unique ID of the broadcasted transaction.
       * 
* * string id = 1 [json_name = "id"]; * @param value The id to set. * @return This builder for chaining. */ public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The unique ID of the broadcasted transaction.
       * 
* * string id = 1 [json_name = "id"]; * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The unique ID of the broadcasted transaction.
       * 
* * string id = 1 [json_name = "id"]; * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.BroadcastTransactionResponse) } // @@protoc_insertion_point(class_scope:pactus.BroadcastTransactionResponse) private static final pactus.TransactionOuterClass.BroadcastTransactionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.BroadcastTransactionResponse(); } public static pactus.TransactionOuterClass.BroadcastTransactionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public BroadcastTransactionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.BroadcastTransactionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetRawTransferTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetRawTransferTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ int getLockTime(); /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The receiver's account address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The receiver. */ java.lang.String getReceiver(); /** *
     * The receiver's account address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The bytes for receiver. */ com.google.protobuf.ByteString getReceiverBytes(); /** *
     * The amount to be transferred, specified in NanoPAC. Must be greater than 0.
     * 
* * int64 amount = 4 [json_name = "amount"]; * @return The amount. */ long getAmount(); /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 5 [json_name = "fee"]; * @return The fee. */ long getFee(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); } /** *
   * Request message for retrieving raw details of a transfer transaction.
   * 
* * Protobuf type {@code pactus.GetRawTransferTransactionRequest} */ public static final class GetRawTransferTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetRawTransferTransactionRequest) GetRawTransferTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetRawTransferTransactionRequest"); } // Use GetRawTransferTransactionRequest.newBuilder() to construct. private GetRawTransferTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetRawTransferTransactionRequest() { sender_ = ""; receiver_ = ""; memo_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransferTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransferTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawTransferTransactionRequest.class, pactus.TransactionOuterClass.GetRawTransferTransactionRequest.Builder.class); } public static final int LOCK_TIME_FIELD_NUMBER = 1; private int lockTime_ = 0; /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } public static final int SENDER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECEIVER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object receiver_ = ""; /** *
     * The receiver's account address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The receiver. */ @java.lang.Override public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } } /** *
     * The receiver's account address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The bytes for receiver. */ @java.lang.Override public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AMOUNT_FIELD_NUMBER = 4; private long amount_ = 0L; /** *
     * The amount to be transferred, specified in NanoPAC. Must be greater than 0.
     * 
* * int64 amount = 4 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } public static final int FEE_FIELD_NUMBER = 5; private long fee_ = 0L; /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 5 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } public static final int MEMO_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (lockTime_ != 0) { output.writeUInt32(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, receiver_); } if (amount_ != 0L) { output.writeInt64(4, amount_); } if (fee_ != 0L) { output.writeInt64(5, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 6, memo_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (lockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, receiver_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, amount_); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(6, memo_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetRawTransferTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.GetRawTransferTransactionRequest other = (pactus.TransactionOuterClass.GetRawTransferTransactionRequest) obj; if (getLockTime() != other.getLockTime()) return false; if (!getSender() .equals(other.getSender())) return false; if (!getReceiver() .equals(other.getReceiver())) return false; if (getAmount() != other.getAmount()) return false; if (getFee() != other.getFee()) return false; if (!getMemo() .equals(other.getMemo())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getLockTime(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); hash = (37 * hash) + RECEIVER_FIELD_NUMBER; hash = (53 * hash) + getReceiver().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetRawTransferTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving raw details of a transfer transaction.
     * 
* * Protobuf type {@code pactus.GetRawTransferTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetRawTransferTransactionRequest) pactus.TransactionOuterClass.GetRawTransferTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransferTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransferTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawTransferTransactionRequest.class, pactus.TransactionOuterClass.GetRawTransferTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.GetRawTransferTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; lockTime_ = 0; sender_ = ""; receiver_ = ""; amount_ = 0L; fee_ = 0L; memo_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransferTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransferTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetRawTransferTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransferTransactionRequest build() { pactus.TransactionOuterClass.GetRawTransferTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransferTransactionRequest buildPartial() { pactus.TransactionOuterClass.GetRawTransferTransactionRequest result = new pactus.TransactionOuterClass.GetRawTransferTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetRawTransferTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.lockTime_ = lockTime_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.sender_ = sender_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.receiver_ = receiver_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.amount_ = amount_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.fee_ = fee_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.memo_ = memo_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetRawTransferTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.GetRawTransferTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetRawTransferTransactionRequest other) { if (other == pactus.TransactionOuterClass.GetRawTransferTransactionRequest.getDefaultInstance()) return this; if (other.getLockTime() != 0) { setLockTime(other.getLockTime()); } if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getReceiver().isEmpty()) { receiver_ = other.receiver_; bitField0_ |= 0x00000004; onChanged(); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } if (other.getFee() != 0L) { setFee(other.getFee()); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00000020; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { lockTime_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { receiver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { amount_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { fee_ = input.readInt64(); bitField0_ |= 0x00000010; break; } // case 40 case 50: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000020; break; } // case 50 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int lockTime_ ; /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { lockTime_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return This builder for chaining. */ public Builder clearLockTime() { bitField0_ = (bitField0_ & ~0x00000001); lockTime_ = 0; onChanged(); return this; } private java.lang.Object sender_ = ""; /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object receiver_ = ""; /** *
       * The receiver's account address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @return The receiver. */ public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The receiver's account address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @return The bytes for receiver. */ public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The receiver's account address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @param value The receiver to set. * @return This builder for chaining. */ public Builder setReceiver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } receiver_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The receiver's account address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @return This builder for chaining. */ public Builder clearReceiver() { receiver_ = getDefaultInstance().getReceiver(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The receiver's account address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @param value The bytes for receiver to set. * @return This builder for chaining. */ public Builder setReceiverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); receiver_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private long amount_ ; /** *
       * The amount to be transferred, specified in NanoPAC. Must be greater than 0.
       * 
* * int64 amount = 4 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The amount to be transferred, specified in NanoPAC. Must be greater than 0.
       * 
* * int64 amount = 4 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The amount to be transferred, specified in NanoPAC. Must be greater than 0.
       * 
* * int64 amount = 4 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000008); amount_ = 0L; onChanged(); return this; } private long fee_ ; /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 5 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 5 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 5 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000010); fee_ = 0L; onChanged(); return this; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetRawTransferTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.GetRawTransferTransactionRequest) private static final pactus.TransactionOuterClass.GetRawTransferTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetRawTransferTransactionRequest(); } public static pactus.TransactionOuterClass.GetRawTransferTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetRawTransferTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransferTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetRawBondTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetRawBondTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ int getLockTime(); /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The receiver's validator address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The receiver. */ java.lang.String getReceiver(); /** *
     * The receiver's validator address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The bytes for receiver. */ com.google.protobuf.ByteString getReceiverBytes(); /** *
     * The stake amount in NanoPAC. Must be greater than 0.
     * 
* * int64 stake = 4 [json_name = "stake"]; * @return The stake. */ long getStake(); /** *
     * The public key of the validator.
     * Optional, but required when registering a new validator.;
     * 
* * string public_key = 5 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key of the validator.
     * Optional, but required when registering a new validator.;
     * 
* * string public_key = 5 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 6 [json_name = "fee"]; * @return The fee. */ long getFee(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 7 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 7 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return The delegateOwner. */ java.lang.String getDelegateOwner(); /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ com.google.protobuf.ByteString getDelegateOwnerBytes(); /** *
     * The share percentage for the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * Must be between 0 and 0.7 PAC in nano PAC.
     * 
* * int64 delegate_share = 9 [json_name = "delegateShare"]; * @return The delegateShare. */ long getDelegateShare(); /** *
     * The expiry height for the delegate relationship.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * uint32 delegate_expiry = 10 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ int getDelegateExpiry(); } /** *
   * Request message for retrieving raw details of a bond transaction.
   * 
* * Protobuf type {@code pactus.GetRawBondTransactionRequest} */ public static final class GetRawBondTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetRawBondTransactionRequest) GetRawBondTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetRawBondTransactionRequest"); } // Use GetRawBondTransactionRequest.newBuilder() to construct. private GetRawBondTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetRawBondTransactionRequest() { sender_ = ""; receiver_ = ""; publicKey_ = ""; memo_ = ""; delegateOwner_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBondTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBondTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawBondTransactionRequest.class, pactus.TransactionOuterClass.GetRawBondTransactionRequest.Builder.class); } public static final int LOCK_TIME_FIELD_NUMBER = 1; private int lockTime_ = 0; /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } public static final int SENDER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECEIVER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object receiver_ = ""; /** *
     * The receiver's validator address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The receiver. */ @java.lang.Override public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } } /** *
     * The receiver's validator address.
     * 
* * string receiver = 3 [json_name = "receiver"]; * @return The bytes for receiver. */ @java.lang.Override public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STAKE_FIELD_NUMBER = 4; private long stake_ = 0L; /** *
     * The stake amount in NanoPAC. Must be greater than 0.
     * 
* * int64 stake = 4 [json_name = "stake"]; * @return The stake. */ @java.lang.Override public long getStake() { return stake_; } public static final int PUBLIC_KEY_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key of the validator.
     * Optional, but required when registering a new validator.;
     * 
* * string public_key = 5 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key of the validator.
     * Optional, but required when registering a new validator.;
     * 
* * string public_key = 5 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FEE_FIELD_NUMBER = 6; private long fee_ = 0L; /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 6 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } public static final int MEMO_FIELD_NUMBER = 7; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 7 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 7 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DELEGATE_OWNER_FIELD_NUMBER = 8; @SuppressWarnings("serial") private volatile java.lang.Object delegateOwner_ = ""; /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return The delegateOwner. */ @java.lang.Override public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } } /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ @java.lang.Override public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DELEGATE_SHARE_FIELD_NUMBER = 9; private long delegateShare_ = 0L; /** *
     * The share percentage for the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * Must be between 0 and 0.7 PAC in nano PAC.
     * 
* * int64 delegate_share = 9 [json_name = "delegateShare"]; * @return The delegateShare. */ @java.lang.Override public long getDelegateShare() { return delegateShare_; } public static final int DELEGATE_EXPIRY_FIELD_NUMBER = 10; private int delegateExpiry_ = 0; /** *
     * The expiry height for the delegate relationship.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * uint32 delegate_expiry = 10 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ @java.lang.Override public int getDelegateExpiry() { return delegateExpiry_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (lockTime_ != 0) { output.writeUInt32(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, receiver_); } if (stake_ != 0L) { output.writeInt64(4, stake_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, publicKey_); } if (fee_ != 0L) { output.writeInt64(6, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 7, memo_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { com.google.protobuf.GeneratedMessage.writeString(output, 8, delegateOwner_); } if (delegateShare_ != 0L) { output.writeInt64(9, delegateShare_); } if (delegateExpiry_ != 0) { output.writeUInt32(10, delegateExpiry_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (lockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, receiver_); } if (stake_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, stake_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, publicKey_); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(7, memo_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(8, delegateOwner_); } if (delegateShare_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(9, delegateShare_); } if (delegateExpiry_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(10, delegateExpiry_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetRawBondTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.GetRawBondTransactionRequest other = (pactus.TransactionOuterClass.GetRawBondTransactionRequest) obj; if (getLockTime() != other.getLockTime()) return false; if (!getSender() .equals(other.getSender())) return false; if (!getReceiver() .equals(other.getReceiver())) return false; if (getStake() != other.getStake()) return false; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (getFee() != other.getFee()) return false; if (!getMemo() .equals(other.getMemo())) return false; if (!getDelegateOwner() .equals(other.getDelegateOwner())) return false; if (getDelegateShare() != other.getDelegateShare()) return false; if (getDelegateExpiry() != other.getDelegateExpiry()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getLockTime(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); hash = (37 * hash) + RECEIVER_FIELD_NUMBER; hash = (53 * hash) + getReceiver().hashCode(); hash = (37 * hash) + STAKE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getStake()); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (37 * hash) + DELEGATE_OWNER_FIELD_NUMBER; hash = (53 * hash) + getDelegateOwner().hashCode(); hash = (37 * hash) + DELEGATE_SHARE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getDelegateShare()); hash = (37 * hash) + DELEGATE_EXPIRY_FIELD_NUMBER; hash = (53 * hash) + getDelegateExpiry(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetRawBondTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving raw details of a bond transaction.
     * 
* * Protobuf type {@code pactus.GetRawBondTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetRawBondTransactionRequest) pactus.TransactionOuterClass.GetRawBondTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBondTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBondTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawBondTransactionRequest.class, pactus.TransactionOuterClass.GetRawBondTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.GetRawBondTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; lockTime_ = 0; sender_ = ""; receiver_ = ""; stake_ = 0L; publicKey_ = ""; fee_ = 0L; memo_ = ""; delegateOwner_ = ""; delegateShare_ = 0L; delegateExpiry_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBondTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetRawBondTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetRawBondTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetRawBondTransactionRequest build() { pactus.TransactionOuterClass.GetRawBondTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetRawBondTransactionRequest buildPartial() { pactus.TransactionOuterClass.GetRawBondTransactionRequest result = new pactus.TransactionOuterClass.GetRawBondTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetRawBondTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.lockTime_ = lockTime_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.sender_ = sender_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.receiver_ = receiver_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.stake_ = stake_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.publicKey_ = publicKey_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.fee_ = fee_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.memo_ = memo_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.delegateOwner_ = delegateOwner_; } if (((from_bitField0_ & 0x00000100) != 0)) { result.delegateShare_ = delegateShare_; } if (((from_bitField0_ & 0x00000200) != 0)) { result.delegateExpiry_ = delegateExpiry_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetRawBondTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.GetRawBondTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetRawBondTransactionRequest other) { if (other == pactus.TransactionOuterClass.GetRawBondTransactionRequest.getDefaultInstance()) return this; if (other.getLockTime() != 0) { setLockTime(other.getLockTime()); } if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getReceiver().isEmpty()) { receiver_ = other.receiver_; bitField0_ |= 0x00000004; onChanged(); } if (other.getStake() != 0L) { setStake(other.getStake()); } if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000010; onChanged(); } if (other.getFee() != 0L) { setFee(other.getFee()); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00000040; onChanged(); } if (!other.getDelegateOwner().isEmpty()) { delegateOwner_ = other.delegateOwner_; bitField0_ |= 0x00000080; onChanged(); } if (other.getDelegateShare() != 0L) { setDelegateShare(other.getDelegateShare()); } if (other.getDelegateExpiry() != 0) { setDelegateExpiry(other.getDelegateExpiry()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { lockTime_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { receiver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { stake_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 case 48: { fee_ = input.readInt64(); bitField0_ |= 0x00000020; break; } // case 48 case 58: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000040; break; } // case 58 case 66: { delegateOwner_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000080; break; } // case 66 case 72: { delegateShare_ = input.readInt64(); bitField0_ |= 0x00000100; break; } // case 72 case 80: { delegateExpiry_ = input.readUInt32(); bitField0_ |= 0x00000200; break; } // case 80 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int lockTime_ ; /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { lockTime_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return This builder for chaining. */ public Builder clearLockTime() { bitField0_ = (bitField0_ & ~0x00000001); lockTime_ = 0; onChanged(); return this; } private java.lang.Object sender_ = ""; /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object receiver_ = ""; /** *
       * The receiver's validator address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @return The receiver. */ public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The receiver's validator address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @return The bytes for receiver. */ public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The receiver's validator address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @param value The receiver to set. * @return This builder for chaining. */ public Builder setReceiver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } receiver_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The receiver's validator address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @return This builder for chaining. */ public Builder clearReceiver() { receiver_ = getDefaultInstance().getReceiver(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The receiver's validator address.
       * 
* * string receiver = 3 [json_name = "receiver"]; * @param value The bytes for receiver to set. * @return This builder for chaining. */ public Builder setReceiverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); receiver_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private long stake_ ; /** *
       * The stake amount in NanoPAC. Must be greater than 0.
       * 
* * int64 stake = 4 [json_name = "stake"]; * @return The stake. */ @java.lang.Override public long getStake() { return stake_; } /** *
       * The stake amount in NanoPAC. Must be greater than 0.
       * 
* * int64 stake = 4 [json_name = "stake"]; * @param value The stake to set. * @return This builder for chaining. */ public Builder setStake(long value) { stake_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The stake amount in NanoPAC. Must be greater than 0.
       * 
* * int64 stake = 4 [json_name = "stake"]; * @return This builder for chaining. */ public Builder clearStake() { bitField0_ = (bitField0_ & ~0x00000008); stake_ = 0L; onChanged(); return this; } private java.lang.Object publicKey_ = ""; /** *
       * The public key of the validator.
       * Optional, but required when registering a new validator.;
       * 
* * string public_key = 5 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key of the validator.
       * Optional, but required when registering a new validator.;
       * 
* * string public_key = 5 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key of the validator.
       * Optional, but required when registering a new validator.;
       * 
* * string public_key = 5 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The public key of the validator.
       * Optional, but required when registering a new validator.;
       * 
* * string public_key = 5 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * The public key of the validator.
       * Optional, but required when registering a new validator.;
       * 
* * string public_key = 5 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } private long fee_ ; /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 6 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 6 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 6 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000020); fee_ = 0L; onChanged(); return this; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 7 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 7 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 7 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 7 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00000040); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 7 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } private java.lang.Object delegateOwner_ = ""; /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return The delegateOwner. */ public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @param value The delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } delegateOwner_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @return This builder for chaining. */ public Builder clearDelegateOwner() { delegateOwner_ = getDefaultInstance().getDelegateOwner(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 8 [json_name = "delegateOwner"]; * @param value The bytes for delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); delegateOwner_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } private long delegateShare_ ; /** *
       * The share percentage for the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * Must be between 0 and 0.7 PAC in nano PAC.
       * 
* * int64 delegate_share = 9 [json_name = "delegateShare"]; * @return The delegateShare. */ @java.lang.Override public long getDelegateShare() { return delegateShare_; } /** *
       * The share percentage for the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * Must be between 0 and 0.7 PAC in nano PAC.
       * 
* * int64 delegate_share = 9 [json_name = "delegateShare"]; * @param value The delegateShare to set. * @return This builder for chaining. */ public Builder setDelegateShare(long value) { delegateShare_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * The share percentage for the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * Must be between 0 and 0.7 PAC in nano PAC.
       * 
* * int64 delegate_share = 9 [json_name = "delegateShare"]; * @return This builder for chaining. */ public Builder clearDelegateShare() { bitField0_ = (bitField0_ & ~0x00000100); delegateShare_ = 0L; onChanged(); return this; } private int delegateExpiry_ ; /** *
       * The expiry height for the delegate relationship.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * uint32 delegate_expiry = 10 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ @java.lang.Override public int getDelegateExpiry() { return delegateExpiry_; } /** *
       * The expiry height for the delegate relationship.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * uint32 delegate_expiry = 10 [json_name = "delegateExpiry"]; * @param value The delegateExpiry to set. * @return This builder for chaining. */ public Builder setDelegateExpiry(int value) { delegateExpiry_ = value; bitField0_ |= 0x00000200; onChanged(); return this; } /** *
       * The expiry height for the delegate relationship.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * uint32 delegate_expiry = 10 [json_name = "delegateExpiry"]; * @return This builder for chaining. */ public Builder clearDelegateExpiry() { bitField0_ = (bitField0_ & ~0x00000200); delegateExpiry_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetRawBondTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.GetRawBondTransactionRequest) private static final pactus.TransactionOuterClass.GetRawBondTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetRawBondTransactionRequest(); } public static pactus.TransactionOuterClass.GetRawBondTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetRawBondTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetRawBondTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetRawUnbondTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetRawUnbondTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ int getLockTime(); /** *
     * The address of the validator to unbond from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The validatorAddress. */ java.lang.String getValidatorAddress(); /** *
     * The address of the validator to unbond from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ com.google.protobuf.ByteString getValidatorAddressBytes(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 3 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 3 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return The delegateOwner. */ java.lang.String getDelegateOwner(); /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ com.google.protobuf.ByteString getDelegateOwnerBytes(); } /** *
   * Request message for retrieving raw details of an unbond transaction.
   * 
* * Protobuf type {@code pactus.GetRawUnbondTransactionRequest} */ public static final class GetRawUnbondTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetRawUnbondTransactionRequest) GetRawUnbondTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetRawUnbondTransactionRequest"); } // Use GetRawUnbondTransactionRequest.newBuilder() to construct. private GetRawUnbondTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetRawUnbondTransactionRequest() { validatorAddress_ = ""; memo_ = ""; delegateOwner_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawUnbondTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawUnbondTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.class, pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.Builder.class); } public static final int LOCK_TIME_FIELD_NUMBER = 1; private int lockTime_ = 0; /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } public static final int VALIDATOR_ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object validatorAddress_ = ""; /** *
     * The address of the validator to unbond from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The validatorAddress. */ @java.lang.Override public java.lang.String getValidatorAddress() { java.lang.Object ref = validatorAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validatorAddress_ = s; return s; } } /** *
     * The address of the validator to unbond from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ @java.lang.Override public com.google.protobuf.ByteString getValidatorAddressBytes() { java.lang.Object ref = validatorAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validatorAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MEMO_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 3 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 3 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DELEGATE_OWNER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object delegateOwner_ = ""; /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return The delegateOwner. */ @java.lang.Override public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } } /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ @java.lang.Override public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (lockTime_ != 0) { output.writeUInt32(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validatorAddress_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, validatorAddress_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, memo_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, delegateOwner_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (lockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validatorAddress_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, validatorAddress_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, memo_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, delegateOwner_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetRawUnbondTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.GetRawUnbondTransactionRequest other = (pactus.TransactionOuterClass.GetRawUnbondTransactionRequest) obj; if (getLockTime() != other.getLockTime()) return false; if (!getValidatorAddress() .equals(other.getValidatorAddress())) return false; if (!getMemo() .equals(other.getMemo())) return false; if (!getDelegateOwner() .equals(other.getDelegateOwner())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getLockTime(); hash = (37 * hash) + VALIDATOR_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getValidatorAddress().hashCode(); hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (37 * hash) + DELEGATE_OWNER_FIELD_NUMBER; hash = (53 * hash) + getDelegateOwner().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving raw details of an unbond transaction.
     * 
* * Protobuf type {@code pactus.GetRawUnbondTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetRawUnbondTransactionRequest) pactus.TransactionOuterClass.GetRawUnbondTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawUnbondTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawUnbondTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.class, pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; lockTime_ = 0; validatorAddress_ = ""; memo_ = ""; delegateOwner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawUnbondTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetRawUnbondTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetRawUnbondTransactionRequest build() { pactus.TransactionOuterClass.GetRawUnbondTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetRawUnbondTransactionRequest buildPartial() { pactus.TransactionOuterClass.GetRawUnbondTransactionRequest result = new pactus.TransactionOuterClass.GetRawUnbondTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.lockTime_ = lockTime_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.validatorAddress_ = validatorAddress_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.memo_ = memo_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.delegateOwner_ = delegateOwner_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetRawUnbondTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.GetRawUnbondTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetRawUnbondTransactionRequest other) { if (other == pactus.TransactionOuterClass.GetRawUnbondTransactionRequest.getDefaultInstance()) return this; if (other.getLockTime() != 0) { setLockTime(other.getLockTime()); } if (!other.getValidatorAddress().isEmpty()) { validatorAddress_ = other.validatorAddress_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getDelegateOwner().isEmpty()) { delegateOwner_ = other.delegateOwner_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { lockTime_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { validatorAddress_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { delegateOwner_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int lockTime_ ; /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { lockTime_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return This builder for chaining. */ public Builder clearLockTime() { bitField0_ = (bitField0_ & ~0x00000001); lockTime_ = 0; onChanged(); return this; } private java.lang.Object validatorAddress_ = ""; /** *
       * The address of the validator to unbond from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The validatorAddress. */ public java.lang.String getValidatorAddress() { java.lang.Object ref = validatorAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validatorAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the validator to unbond from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ public com.google.protobuf.ByteString getValidatorAddressBytes() { java.lang.Object ref = validatorAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validatorAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the validator to unbond from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @param value The validatorAddress to set. * @return This builder for chaining. */ public Builder setValidatorAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } validatorAddress_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address of the validator to unbond from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return This builder for chaining. */ public Builder clearValidatorAddress() { validatorAddress_ = getDefaultInstance().getValidatorAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address of the validator to unbond from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @param value The bytes for validatorAddress to set. * @return This builder for chaining. */ public Builder setValidatorAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); validatorAddress_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 3 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 3 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 3 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 3 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 3 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object delegateOwner_ = ""; /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return The delegateOwner. */ public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @param value The delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } delegateOwner_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @return This builder for chaining. */ public Builder clearDelegateOwner() { delegateOwner_ = getDefaultInstance().getDelegateOwner(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 4 [json_name = "delegateOwner"]; * @param value The bytes for delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); delegateOwner_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetRawUnbondTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.GetRawUnbondTransactionRequest) private static final pactus.TransactionOuterClass.GetRawUnbondTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetRawUnbondTransactionRequest(); } public static pactus.TransactionOuterClass.GetRawUnbondTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetRawUnbondTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetRawUnbondTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetRawWithdrawTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetRawWithdrawTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ int getLockTime(); /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The validatorAddress. */ java.lang.String getValidatorAddress(); /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ com.google.protobuf.ByteString getValidatorAddressBytes(); /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return The accountAddress. */ java.lang.String getAccountAddress(); /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return The bytes for accountAddress. */ com.google.protobuf.ByteString getAccountAddressBytes(); /** *
     * The withdrawal amount in NanoPAC. Must be greater than 0.
     * 
* * int64 amount = 4 [json_name = "amount"]; * @return The amount. */ long getAmount(); /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 5 [json_name = "fee"]; * @return The fee. */ long getFee(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); } /** *
   * Request message for retrieving raw details of a withdraw transaction.
   * 
* * Protobuf type {@code pactus.GetRawWithdrawTransactionRequest} */ public static final class GetRawWithdrawTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetRawWithdrawTransactionRequest) GetRawWithdrawTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetRawWithdrawTransactionRequest"); } // Use GetRawWithdrawTransactionRequest.newBuilder() to construct. private GetRawWithdrawTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetRawWithdrawTransactionRequest() { validatorAddress_ = ""; accountAddress_ = ""; memo_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawWithdrawTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawWithdrawTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.class, pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.Builder.class); } public static final int LOCK_TIME_FIELD_NUMBER = 1; private int lockTime_ = 0; /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } public static final int VALIDATOR_ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object validatorAddress_ = ""; /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The validatorAddress. */ @java.lang.Override public java.lang.String getValidatorAddress() { java.lang.Object ref = validatorAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validatorAddress_ = s; return s; } } /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ @java.lang.Override public com.google.protobuf.ByteString getValidatorAddressBytes() { java.lang.Object ref = validatorAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validatorAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ACCOUNT_ADDRESS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object accountAddress_ = ""; /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return The accountAddress. */ @java.lang.Override public java.lang.String getAccountAddress() { java.lang.Object ref = accountAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); accountAddress_ = s; return s; } } /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return The bytes for accountAddress. */ @java.lang.Override public com.google.protobuf.ByteString getAccountAddressBytes() { java.lang.Object ref = accountAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); accountAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AMOUNT_FIELD_NUMBER = 4; private long amount_ = 0L; /** *
     * The withdrawal amount in NanoPAC. Must be greater than 0.
     * 
* * int64 amount = 4 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } public static final int FEE_FIELD_NUMBER = 5; private long fee_ = 0L; /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 5 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } public static final int MEMO_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 6 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (lockTime_ != 0) { output.writeUInt32(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validatorAddress_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, validatorAddress_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(accountAddress_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, accountAddress_); } if (amount_ != 0L) { output.writeInt64(4, amount_); } if (fee_ != 0L) { output.writeInt64(5, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 6, memo_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (lockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validatorAddress_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, validatorAddress_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(accountAddress_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, accountAddress_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, amount_); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(6, memo_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest other = (pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest) obj; if (getLockTime() != other.getLockTime()) return false; if (!getValidatorAddress() .equals(other.getValidatorAddress())) return false; if (!getAccountAddress() .equals(other.getAccountAddress())) return false; if (getAmount() != other.getAmount()) return false; if (getFee() != other.getFee()) return false; if (!getMemo() .equals(other.getMemo())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getLockTime(); hash = (37 * hash) + VALIDATOR_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getValidatorAddress().hashCode(); hash = (37 * hash) + ACCOUNT_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAccountAddress().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving raw details of a withdraw transaction.
     * 
* * Protobuf type {@code pactus.GetRawWithdrawTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetRawWithdrawTransactionRequest) pactus.TransactionOuterClass.GetRawWithdrawTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawWithdrawTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawWithdrawTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.class, pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; lockTime_ = 0; validatorAddress_ = ""; accountAddress_ = ""; amount_ = 0L; fee_ = 0L; memo_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawWithdrawTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest build() { pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest buildPartial() { pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest result = new pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.lockTime_ = lockTime_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.validatorAddress_ = validatorAddress_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.accountAddress_ = accountAddress_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.amount_ = amount_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.fee_ = fee_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.memo_ = memo_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest other) { if (other == pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest.getDefaultInstance()) return this; if (other.getLockTime() != 0) { setLockTime(other.getLockTime()); } if (!other.getValidatorAddress().isEmpty()) { validatorAddress_ = other.validatorAddress_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAccountAddress().isEmpty()) { accountAddress_ = other.accountAddress_; bitField0_ |= 0x00000004; onChanged(); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } if (other.getFee() != 0L) { setFee(other.getFee()); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00000020; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { lockTime_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { validatorAddress_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { accountAddress_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { amount_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { fee_ = input.readInt64(); bitField0_ |= 0x00000010; break; } // case 40 case 50: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000020; break; } // case 50 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int lockTime_ ; /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { lockTime_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return This builder for chaining. */ public Builder clearLockTime() { bitField0_ = (bitField0_ & ~0x00000001); lockTime_ = 0; onChanged(); return this; } private java.lang.Object validatorAddress_ = ""; /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The validatorAddress. */ public java.lang.String getValidatorAddress() { java.lang.Object ref = validatorAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validatorAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ public com.google.protobuf.ByteString getValidatorAddressBytes() { java.lang.Object ref = validatorAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validatorAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @param value The validatorAddress to set. * @return This builder for chaining. */ public Builder setValidatorAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } validatorAddress_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @return This builder for chaining. */ public Builder clearValidatorAddress() { validatorAddress_ = getDefaultInstance().getValidatorAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 2 [json_name = "validatorAddress"]; * @param value The bytes for validatorAddress to set. * @return This builder for chaining. */ public Builder setValidatorAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); validatorAddress_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object accountAddress_ = ""; /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return The accountAddress. */ public java.lang.String getAccountAddress() { java.lang.Object ref = accountAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); accountAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return The bytes for accountAddress. */ public com.google.protobuf.ByteString getAccountAddressBytes() { java.lang.Object ref = accountAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); accountAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 3 [json_name = "accountAddress"]; * @param value The accountAddress to set. * @return This builder for chaining. */ public Builder setAccountAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } accountAddress_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 3 [json_name = "accountAddress"]; * @return This builder for chaining. */ public Builder clearAccountAddress() { accountAddress_ = getDefaultInstance().getAccountAddress(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 3 [json_name = "accountAddress"]; * @param value The bytes for accountAddress to set. * @return This builder for chaining. */ public Builder setAccountAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); accountAddress_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private long amount_ ; /** *
       * The withdrawal amount in NanoPAC. Must be greater than 0.
       * 
* * int64 amount = 4 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The withdrawal amount in NanoPAC. Must be greater than 0.
       * 
* * int64 amount = 4 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The withdrawal amount in NanoPAC. Must be greater than 0.
       * 
* * int64 amount = 4 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000008); amount_ = 0L; onChanged(); return this; } private long fee_ ; /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 5 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 5 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 5 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000010); fee_ = 0L; onChanged(); return this; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 6 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetRawWithdrawTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.GetRawWithdrawTransactionRequest) private static final pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest(); } public static pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetRawWithdrawTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetRawWithdrawTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetRawBatchTransferTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetRawBatchTransferTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ int getLockTime(); /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ java.util.List getRecipientsList(); /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ pactus.TransactionOuterClass.Recipient getRecipients(int index); /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ int getRecipientsCount(); /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ java.util.List getRecipientsOrBuilderList(); /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ pactus.TransactionOuterClass.RecipientOrBuilder getRecipientsOrBuilder( int index); /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 4 [json_name = "fee"]; * @return The fee. */ long getFee(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 5 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 5 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); } /** *
   * Request message for retrieving raw details of a batch transfer transaction.
   * 
* * Protobuf type {@code pactus.GetRawBatchTransferTransactionRequest} */ public static final class GetRawBatchTransferTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetRawBatchTransferTransactionRequest) GetRawBatchTransferTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetRawBatchTransferTransactionRequest"); } // Use GetRawBatchTransferTransactionRequest.newBuilder() to construct. private GetRawBatchTransferTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetRawBatchTransferTransactionRequest() { sender_ = ""; recipients_ = java.util.Collections.emptyList(); memo_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBatchTransferTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBatchTransferTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.class, pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.Builder.class); } public static final int LOCK_TIME_FIELD_NUMBER = 1; private int lockTime_ = 0; /** *
     * The lock time for the transaction. If not set, defaults to the last block height.
     * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } public static final int SENDER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's account address.
     * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECIPIENTS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private java.util.List recipients_; /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ @java.lang.Override public java.util.List getRecipientsList() { return recipients_; } /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ @java.lang.Override public java.util.List getRecipientsOrBuilderList() { return recipients_; } /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ @java.lang.Override public int getRecipientsCount() { return recipients_.size(); } /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ @java.lang.Override public pactus.TransactionOuterClass.Recipient getRecipients(int index) { return recipients_.get(index); } /** *
     * The list of recipients with their amounts. Minimum 2 recipients required.
     * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ @java.lang.Override public pactus.TransactionOuterClass.RecipientOrBuilder getRecipientsOrBuilder( int index) { return recipients_.get(index); } public static final int FEE_FIELD_NUMBER = 4; private long fee_ = 0L; /** *
     * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
     * 
* * int64 fee = 4 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } public static final int MEMO_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 5 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 5 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (lockTime_ != 0) { output.writeUInt32(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, sender_); } for (int i = 0; i < recipients_.size(); i++) { output.writeMessage(3, recipients_.get(i)); } if (fee_ != 0L) { output.writeInt64(4, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, memo_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (lockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, lockTime_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, sender_); } for (int i = 0; i < recipients_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, recipients_.get(i)); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, memo_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest other = (pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest) obj; if (getLockTime() != other.getLockTime()) return false; if (!getSender() .equals(other.getSender())) return false; if (!getRecipientsList() .equals(other.getRecipientsList())) return false; if (getFee() != other.getFee()) return false; if (!getMemo() .equals(other.getMemo())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getLockTime(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); if (getRecipientsCount() > 0) { hash = (37 * hash) + RECIPIENTS_FIELD_NUMBER; hash = (53 * hash) + getRecipientsList().hashCode(); } hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for retrieving raw details of a batch transfer transaction.
     * 
* * Protobuf type {@code pactus.GetRawBatchTransferTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetRawBatchTransferTransactionRequest) pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBatchTransferTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBatchTransferTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.class, pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; lockTime_ = 0; sender_ = ""; if (recipientsBuilder_ == null) { recipients_ = java.util.Collections.emptyList(); } else { recipients_ = null; recipientsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); fee_ = 0L; memo_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawBatchTransferTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest build() { pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest buildPartial() { pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest result = new pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest result) { if (recipientsBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0)) { recipients_ = java.util.Collections.unmodifiableList(recipients_); bitField0_ = (bitField0_ & ~0x00000004); } result.recipients_ = recipients_; } else { result.recipients_ = recipientsBuilder_.build(); } } private void buildPartial0(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.lockTime_ = lockTime_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.sender_ = sender_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.fee_ = fee_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.memo_ = memo_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest other) { if (other == pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest.getDefaultInstance()) return this; if (other.getLockTime() != 0) { setLockTime(other.getLockTime()); } if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000002; onChanged(); } if (recipientsBuilder_ == null) { if (!other.recipients_.isEmpty()) { if (recipients_.isEmpty()) { recipients_ = other.recipients_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureRecipientsIsMutable(); recipients_.addAll(other.recipients_); } onChanged(); } } else { if (!other.recipients_.isEmpty()) { if (recipientsBuilder_.isEmpty()) { recipientsBuilder_.dispose(); recipientsBuilder_ = null; recipients_ = other.recipients_; bitField0_ = (bitField0_ & ~0x00000004); recipientsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetRecipientsFieldBuilder() : null; } else { recipientsBuilder_.addAllMessages(other.recipients_); } } } if (other.getFee() != 0L) { setFee(other.getFee()); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { lockTime_ = input.readUInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { pactus.TransactionOuterClass.Recipient m = input.readMessage( pactus.TransactionOuterClass.Recipient.parser(), extensionRegistry); if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.add(m); } else { recipientsBuilder_.addMessage(m); } break; } // case 26 case 32: { fee_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int lockTime_ ; /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { lockTime_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The lock time for the transaction. If not set, defaults to the last block height.
       * 
* * uint32 lock_time = 1 [json_name = "lockTime"]; * @return This builder for chaining. */ public Builder clearLockTime() { bitField0_ = (bitField0_ & ~0x00000001); lockTime_ = 0; onChanged(); return this; } private java.lang.Object sender_ = ""; /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The sender's account address.
       * 
* * string sender = 2 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.util.List recipients_ = java.util.Collections.emptyList(); private void ensureRecipientsIsMutable() { if (!((bitField0_ & 0x00000004) != 0)) { recipients_ = new java.util.ArrayList(recipients_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.Recipient, pactus.TransactionOuterClass.Recipient.Builder, pactus.TransactionOuterClass.RecipientOrBuilder> recipientsBuilder_; /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public java.util.List getRecipientsList() { if (recipientsBuilder_ == null) { return java.util.Collections.unmodifiableList(recipients_); } else { return recipientsBuilder_.getMessageList(); } } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public int getRecipientsCount() { if (recipientsBuilder_ == null) { return recipients_.size(); } else { return recipientsBuilder_.getCount(); } } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient getRecipients(int index) { if (recipientsBuilder_ == null) { return recipients_.get(index); } else { return recipientsBuilder_.getMessage(index); } } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder setRecipients( int index, pactus.TransactionOuterClass.Recipient value) { if (recipientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRecipientsIsMutable(); recipients_.set(index, value); onChanged(); } else { recipientsBuilder_.setMessage(index, value); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder setRecipients( int index, pactus.TransactionOuterClass.Recipient.Builder builderForValue) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.set(index, builderForValue.build()); onChanged(); } else { recipientsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder addRecipients(pactus.TransactionOuterClass.Recipient value) { if (recipientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRecipientsIsMutable(); recipients_.add(value); onChanged(); } else { recipientsBuilder_.addMessage(value); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder addRecipients( int index, pactus.TransactionOuterClass.Recipient value) { if (recipientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRecipientsIsMutable(); recipients_.add(index, value); onChanged(); } else { recipientsBuilder_.addMessage(index, value); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder addRecipients( pactus.TransactionOuterClass.Recipient.Builder builderForValue) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.add(builderForValue.build()); onChanged(); } else { recipientsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder addRecipients( int index, pactus.TransactionOuterClass.Recipient.Builder builderForValue) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.add(index, builderForValue.build()); onChanged(); } else { recipientsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder addAllRecipients( java.lang.Iterable values) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, recipients_); onChanged(); } else { recipientsBuilder_.addAllMessages(values); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder clearRecipients() { if (recipientsBuilder_ == null) { recipients_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { recipientsBuilder_.clear(); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public Builder removeRecipients(int index) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.remove(index); onChanged(); } else { recipientsBuilder_.remove(index); } return this; } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient.Builder getRecipientsBuilder( int index) { return internalGetRecipientsFieldBuilder().getBuilder(index); } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.RecipientOrBuilder getRecipientsOrBuilder( int index) { if (recipientsBuilder_ == null) { return recipients_.get(index); } else { return recipientsBuilder_.getMessageOrBuilder(index); } } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public java.util.List getRecipientsOrBuilderList() { if (recipientsBuilder_ != null) { return recipientsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(recipients_); } } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient.Builder addRecipientsBuilder() { return internalGetRecipientsFieldBuilder().addBuilder( pactus.TransactionOuterClass.Recipient.getDefaultInstance()); } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient.Builder addRecipientsBuilder( int index) { return internalGetRecipientsFieldBuilder().addBuilder( index, pactus.TransactionOuterClass.Recipient.getDefaultInstance()); } /** *
       * The list of recipients with their amounts. Minimum 2 recipients required.
       * 
* * repeated .pactus.Recipient recipients = 3 [json_name = "recipients"]; */ public java.util.List getRecipientsBuilderList() { return internalGetRecipientsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.Recipient, pactus.TransactionOuterClass.Recipient.Builder, pactus.TransactionOuterClass.RecipientOrBuilder> internalGetRecipientsFieldBuilder() { if (recipientsBuilder_ == null) { recipientsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.Recipient, pactus.TransactionOuterClass.Recipient.Builder, pactus.TransactionOuterClass.RecipientOrBuilder>( recipients_, ((bitField0_ & 0x00000004) != 0), getParentForChildren(), isClean()); recipients_ = null; } return recipientsBuilder_; } private long fee_ ; /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 4 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 4 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The transaction fee in NanoPAC. If not set, it is set to the estimated fee.
       * 
* * int64 fee = 4 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000008); fee_ = 0L; onChanged(); return this; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 5 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 5 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 5 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 5 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 5 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetRawBatchTransferTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.GetRawBatchTransferTransactionRequest) private static final pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest(); } public static pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetRawBatchTransferTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetRawBatchTransferTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetRawTransactionResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetRawTransactionResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ java.lang.String getRawTransaction(); /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ com.google.protobuf.ByteString getRawTransactionBytes(); /** *
     * The unique ID of the transaction.
     * 
* * string id = 2 [json_name = "id"]; * @return The id. */ java.lang.String getId(); /** *
     * The unique ID of the transaction.
     * 
* * string id = 2 [json_name = "id"]; * @return The bytes for id. */ com.google.protobuf.ByteString getIdBytes(); } /** *
   * Response message contains raw transaction data.
   * 
* * Protobuf type {@code pactus.GetRawTransactionResponse} */ public static final class GetRawTransactionResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetRawTransactionResponse) GetRawTransactionResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetRawTransactionResponse"); } // Use GetRawTransactionResponse.newBuilder() to construct. private GetRawTransactionResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetRawTransactionResponse() { rawTransaction_ = ""; id_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawTransactionResponse.class, pactus.TransactionOuterClass.GetRawTransactionResponse.Builder.class); } public static final int RAW_TRANSACTION_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object rawTransaction_ = ""; /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ @java.lang.Override public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } } /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object id_ = ""; /** *
     * The unique ID of the transaction.
     * 
* * string id = 2 [json_name = "id"]; * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** *
     * The unique ID of the transaction.
     * 
* * string id = 2 [json_name = "id"]; * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, rawTransaction_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, id_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, rawTransaction_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, id_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.GetRawTransactionResponse)) { return super.equals(obj); } pactus.TransactionOuterClass.GetRawTransactionResponse other = (pactus.TransactionOuterClass.GetRawTransactionResponse) obj; if (!getRawTransaction() .equals(other.getRawTransaction())) return false; if (!getId() .equals(other.getId())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RAW_TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getRawTransaction().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.GetRawTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.GetRawTransactionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains raw transaction data.
     * 
* * Protobuf type {@code pactus.GetRawTransactionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetRawTransactionResponse) pactus.TransactionOuterClass.GetRawTransactionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.GetRawTransactionResponse.class, pactus.TransactionOuterClass.GetRawTransactionResponse.Builder.class); } // Construct using pactus.TransactionOuterClass.GetRawTransactionResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; rawTransaction_ = ""; id_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_GetRawTransactionResponse_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransactionResponse getDefaultInstanceForType() { return pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransactionResponse build() { pactus.TransactionOuterClass.GetRawTransactionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransactionResponse buildPartial() { pactus.TransactionOuterClass.GetRawTransactionResponse result = new pactus.TransactionOuterClass.GetRawTransactionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.GetRawTransactionResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.rawTransaction_ = rawTransaction_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.id_ = id_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.GetRawTransactionResponse) { return mergeFrom((pactus.TransactionOuterClass.GetRawTransactionResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.GetRawTransactionResponse other) { if (other == pactus.TransactionOuterClass.GetRawTransactionResponse.getDefaultInstance()) return this; if (!other.getRawTransaction().isEmpty()) { rawTransaction_ = other.rawTransaction_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getId().isEmpty()) { id_ = other.id_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { rawTransaction_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { id_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object rawTransaction_ = ""; /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @param value The rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransaction( java.lang.String value) { if (value == null) { throw new NullPointerException(); } rawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return This builder for chaining. */ public Builder clearRawTransaction() { rawTransaction_ = getDefaultInstance().getRawTransaction(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @param value The bytes for rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransactionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); rawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object id_ = ""; /** *
       * The unique ID of the transaction.
       * 
* * string id = 2 [json_name = "id"]; * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The unique ID of the transaction.
       * 
* * string id = 2 [json_name = "id"]; * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The unique ID of the transaction.
       * 
* * string id = 2 [json_name = "id"]; * @param value The id to set. * @return This builder for chaining. */ public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The unique ID of the transaction.
       * 
* * string id = 2 [json_name = "id"]; * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The unique ID of the transaction.
       * 
* * string id = 2 [json_name = "id"]; * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetRawTransactionResponse) } // @@protoc_insertion_point(class_scope:pactus.GetRawTransactionResponse) private static final pactus.TransactionOuterClass.GetRawTransactionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.GetRawTransactionResponse(); } public static pactus.TransactionOuterClass.GetRawTransactionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetRawTransactionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.GetRawTransactionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PayloadTransferOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PayloadTransfer) com.google.protobuf.MessageOrBuilder { /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The receiver. */ java.lang.String getReceiver(); /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The bytes for receiver. */ com.google.protobuf.ByteString getReceiverBytes(); /** *
     * The amount to be transferred in NanoPAC.
     * 
* * int64 amount = 3 [json_name = "amount"]; * @return The amount. */ long getAmount(); } /** *
   * Payload for a transfer transaction.
   * 
* * Protobuf type {@code pactus.PayloadTransfer} */ public static final class PayloadTransfer extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PayloadTransfer) PayloadTransferOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadTransfer"); } // Use PayloadTransfer.newBuilder() to construct. private PayloadTransfer(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PayloadTransfer() { sender_ = ""; receiver_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadTransfer_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadTransfer_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadTransfer.class, pactus.TransactionOuterClass.PayloadTransfer.Builder.class); } public static final int SENDER_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECEIVER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object receiver_ = ""; /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The receiver. */ @java.lang.Override public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } } /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The bytes for receiver. */ @java.lang.Override public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AMOUNT_FIELD_NUMBER = 3; private long amount_ = 0L; /** *
     * The amount to be transferred in NanoPAC.
     * 
* * int64 amount = 3 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, receiver_); } if (amount_ != 0L) { output.writeInt64(3, amount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, receiver_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, amount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.PayloadTransfer)) { return super.equals(obj); } pactus.TransactionOuterClass.PayloadTransfer other = (pactus.TransactionOuterClass.PayloadTransfer) obj; if (!getSender() .equals(other.getSender())) return false; if (!getReceiver() .equals(other.getReceiver())) return false; if (getAmount() != other.getAmount()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); hash = (37 * hash) + RECEIVER_FIELD_NUMBER; hash = (53 * hash) + getReceiver().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadTransfer parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadTransfer parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadTransfer parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.PayloadTransfer prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Payload for a transfer transaction.
     * 
* * Protobuf type {@code pactus.PayloadTransfer} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PayloadTransfer) pactus.TransactionOuterClass.PayloadTransferOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadTransfer_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadTransfer_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadTransfer.class, pactus.TransactionOuterClass.PayloadTransfer.Builder.class); } // Construct using pactus.TransactionOuterClass.PayloadTransfer.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; sender_ = ""; receiver_ = ""; amount_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadTransfer_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.PayloadTransfer getDefaultInstanceForType() { return pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.PayloadTransfer build() { pactus.TransactionOuterClass.PayloadTransfer result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.PayloadTransfer buildPartial() { pactus.TransactionOuterClass.PayloadTransfer result = new pactus.TransactionOuterClass.PayloadTransfer(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.PayloadTransfer result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.sender_ = sender_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.receiver_ = receiver_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.amount_ = amount_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.PayloadTransfer) { return mergeFrom((pactus.TransactionOuterClass.PayloadTransfer)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.PayloadTransfer other) { if (other == pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance()) return this; if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getReceiver().isEmpty()) { receiver_ = other.receiver_; bitField0_ |= 0x00000002; onChanged(); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { receiver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { amount_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object sender_ = ""; /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object receiver_ = ""; /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @return The receiver. */ public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @return The bytes for receiver. */ public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @param value The receiver to set. * @return This builder for chaining. */ public Builder setReceiver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } receiver_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @return This builder for chaining. */ public Builder clearReceiver() { receiver_ = getDefaultInstance().getReceiver(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @param value The bytes for receiver to set. * @return This builder for chaining. */ public Builder setReceiverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); receiver_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long amount_ ; /** *
       * The amount to be transferred in NanoPAC.
       * 
* * int64 amount = 3 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The amount to be transferred in NanoPAC.
       * 
* * int64 amount = 3 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The amount to be transferred in NanoPAC.
       * 
* * int64 amount = 3 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000004); amount_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PayloadTransfer) } // @@protoc_insertion_point(class_scope:pactus.PayloadTransfer) private static final pactus.TransactionOuterClass.PayloadTransfer DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.PayloadTransfer(); } public static pactus.TransactionOuterClass.PayloadTransfer getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PayloadTransfer parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.PayloadTransfer getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PayloadBondOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PayloadBond) com.google.protobuf.MessageOrBuilder { /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The receiver. */ java.lang.String getReceiver(); /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The bytes for receiver. */ com.google.protobuf.ByteString getReceiverBytes(); /** *
     * The stake amount in NanoPAC.
     * 
* * int64 stake = 3 [json_name = "stake"]; * @return The stake. */ long getStake(); /** *
     * The public key of the validator.
     * 
* * string public_key = 4 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key of the validator.
     * 
* * string public_key = 4 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); /** *
     * Indicates whether the bond transaction is a delegation.
     * 
* * bool is_delegated = 5 [json_name = "isDelegated"]; * @return The isDelegated. */ boolean getIsDelegated(); /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return The delegateOwner. */ java.lang.String getDelegateOwner(); /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ com.google.protobuf.ByteString getDelegateOwnerBytes(); /** *
     * The share percentage for the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * Must be between 0 and 0.7 PAC in nano PAC.
     * 
* * int64 delegate_share = 7 [json_name = "delegateShare"]; * @return The delegateShare. */ long getDelegateShare(); /** *
     * The expiry height for the delegate relationship.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * uint32 delegate_expiry = 8 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ int getDelegateExpiry(); } /** *
   * Payload for a bond transaction.
   * 
* * Protobuf type {@code pactus.PayloadBond} */ public static final class PayloadBond extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PayloadBond) PayloadBondOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadBond"); } // Use PayloadBond.newBuilder() to construct. private PayloadBond(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PayloadBond() { sender_ = ""; receiver_ = ""; publicKey_ = ""; delegateOwner_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBond_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBond_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadBond.class, pactus.TransactionOuterClass.PayloadBond.Builder.class); } public static final int SENDER_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECEIVER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object receiver_ = ""; /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The receiver. */ @java.lang.Override public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } } /** *
     * The receiver's address.
     * 
* * string receiver = 2 [json_name = "receiver"]; * @return The bytes for receiver. */ @java.lang.Override public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STAKE_FIELD_NUMBER = 3; private long stake_ = 0L; /** *
     * The stake amount in NanoPAC.
     * 
* * int64 stake = 3 [json_name = "stake"]; * @return The stake. */ @java.lang.Override public long getStake() { return stake_; } public static final int PUBLIC_KEY_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key of the validator.
     * 
* * string public_key = 4 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key of the validator.
     * 
* * string public_key = 4 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IS_DELEGATED_FIELD_NUMBER = 5; private boolean isDelegated_ = false; /** *
     * Indicates whether the bond transaction is a delegation.
     * 
* * bool is_delegated = 5 [json_name = "isDelegated"]; * @return The isDelegated. */ @java.lang.Override public boolean getIsDelegated() { return isDelegated_; } public static final int DELEGATE_OWNER_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object delegateOwner_ = ""; /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return The delegateOwner. */ @java.lang.Override public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } } /** *
     * The address of the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ @java.lang.Override public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DELEGATE_SHARE_FIELD_NUMBER = 7; private long delegateShare_ = 0L; /** *
     * The share percentage for the delegate owner.
     * Optional, but required when registering a new validator with delegation.;
     * Must be between 0 and 0.7 PAC in nano PAC.
     * 
* * int64 delegate_share = 7 [json_name = "delegateShare"]; * @return The delegateShare. */ @java.lang.Override public long getDelegateShare() { return delegateShare_; } public static final int DELEGATE_EXPIRY_FIELD_NUMBER = 8; private int delegateExpiry_ = 0; /** *
     * The expiry height for the delegate relationship.
     * Optional, but required when registering a new validator with delegation.;
     * 
* * uint32 delegate_expiry = 8 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ @java.lang.Override public int getDelegateExpiry() { return delegateExpiry_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, receiver_); } if (stake_ != 0L) { output.writeInt64(3, stake_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, publicKey_); } if (isDelegated_ != false) { output.writeBool(5, isDelegated_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { com.google.protobuf.GeneratedMessage.writeString(output, 6, delegateOwner_); } if (delegateShare_ != 0L) { output.writeInt64(7, delegateShare_); } if (delegateExpiry_ != 0) { output.writeUInt32(8, delegateExpiry_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, receiver_); } if (stake_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, stake_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, publicKey_); } if (isDelegated_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, isDelegated_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(6, delegateOwner_); } if (delegateShare_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, delegateShare_); } if (delegateExpiry_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(8, delegateExpiry_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.PayloadBond)) { return super.equals(obj); } pactus.TransactionOuterClass.PayloadBond other = (pactus.TransactionOuterClass.PayloadBond) obj; if (!getSender() .equals(other.getSender())) return false; if (!getReceiver() .equals(other.getReceiver())) return false; if (getStake() != other.getStake()) return false; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (getIsDelegated() != other.getIsDelegated()) return false; if (!getDelegateOwner() .equals(other.getDelegateOwner())) return false; if (getDelegateShare() != other.getDelegateShare()) return false; if (getDelegateExpiry() != other.getDelegateExpiry()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); hash = (37 * hash) + RECEIVER_FIELD_NUMBER; hash = (53 * hash) + getReceiver().hashCode(); hash = (37 * hash) + STAKE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getStake()); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (37 * hash) + IS_DELEGATED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsDelegated()); hash = (37 * hash) + DELEGATE_OWNER_FIELD_NUMBER; hash = (53 * hash) + getDelegateOwner().hashCode(); hash = (37 * hash) + DELEGATE_SHARE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getDelegateShare()); hash = (37 * hash) + DELEGATE_EXPIRY_FIELD_NUMBER; hash = (53 * hash) + getDelegateExpiry(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.PayloadBond parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBond parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBond parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBond parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadBond parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadBond parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.PayloadBond prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Payload for a bond transaction.
     * 
* * Protobuf type {@code pactus.PayloadBond} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PayloadBond) pactus.TransactionOuterClass.PayloadBondOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBond_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBond_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadBond.class, pactus.TransactionOuterClass.PayloadBond.Builder.class); } // Construct using pactus.TransactionOuterClass.PayloadBond.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; sender_ = ""; receiver_ = ""; stake_ = 0L; publicKey_ = ""; isDelegated_ = false; delegateOwner_ = ""; delegateShare_ = 0L; delegateExpiry_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBond_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.PayloadBond getDefaultInstanceForType() { return pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.PayloadBond build() { pactus.TransactionOuterClass.PayloadBond result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.PayloadBond buildPartial() { pactus.TransactionOuterClass.PayloadBond result = new pactus.TransactionOuterClass.PayloadBond(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.PayloadBond result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.sender_ = sender_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.receiver_ = receiver_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.stake_ = stake_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.publicKey_ = publicKey_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.isDelegated_ = isDelegated_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.delegateOwner_ = delegateOwner_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.delegateShare_ = delegateShare_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.delegateExpiry_ = delegateExpiry_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.PayloadBond) { return mergeFrom((pactus.TransactionOuterClass.PayloadBond)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.PayloadBond other) { if (other == pactus.TransactionOuterClass.PayloadBond.getDefaultInstance()) return this; if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getReceiver().isEmpty()) { receiver_ = other.receiver_; bitField0_ |= 0x00000002; onChanged(); } if (other.getStake() != 0L) { setStake(other.getStake()); } if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000008; onChanged(); } if (other.getIsDelegated() != false) { setIsDelegated(other.getIsDelegated()); } if (!other.getDelegateOwner().isEmpty()) { delegateOwner_ = other.delegateOwner_; bitField0_ |= 0x00000020; onChanged(); } if (other.getDelegateShare() != 0L) { setDelegateShare(other.getDelegateShare()); } if (other.getDelegateExpiry() != 0) { setDelegateExpiry(other.getDelegateExpiry()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { receiver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { stake_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 40: { isDelegated_ = input.readBool(); bitField0_ |= 0x00000010; break; } // case 40 case 50: { delegateOwner_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000020; break; } // case 50 case 56: { delegateShare_ = input.readInt64(); bitField0_ |= 0x00000040; break; } // case 56 case 64: { delegateExpiry_ = input.readUInt32(); bitField0_ |= 0x00000080; break; } // case 64 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object sender_ = ""; /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object receiver_ = ""; /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @return The receiver. */ public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @return The bytes for receiver. */ public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @param value The receiver to set. * @return This builder for chaining. */ public Builder setReceiver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } receiver_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @return This builder for chaining. */ public Builder clearReceiver() { receiver_ = getDefaultInstance().getReceiver(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 2 [json_name = "receiver"]; * @param value The bytes for receiver to set. * @return This builder for chaining. */ public Builder setReceiverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); receiver_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long stake_ ; /** *
       * The stake amount in NanoPAC.
       * 
* * int64 stake = 3 [json_name = "stake"]; * @return The stake. */ @java.lang.Override public long getStake() { return stake_; } /** *
       * The stake amount in NanoPAC.
       * 
* * int64 stake = 3 [json_name = "stake"]; * @param value The stake to set. * @return This builder for chaining. */ public Builder setStake(long value) { stake_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The stake amount in NanoPAC.
       * 
* * int64 stake = 3 [json_name = "stake"]; * @return This builder for chaining. */ public Builder clearStake() { bitField0_ = (bitField0_ & ~0x00000004); stake_ = 0L; onChanged(); return this; } private java.lang.Object publicKey_ = ""; /** *
       * The public key of the validator.
       * 
* * string public_key = 4 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key of the validator.
       * 
* * string public_key = 4 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key of the validator.
       * 
* * string public_key = 4 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The public key of the validator.
       * 
* * string public_key = 4 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The public key of the validator.
       * 
* * string public_key = 4 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private boolean isDelegated_ ; /** *
       * Indicates whether the bond transaction is a delegation.
       * 
* * bool is_delegated = 5 [json_name = "isDelegated"]; * @return The isDelegated. */ @java.lang.Override public boolean getIsDelegated() { return isDelegated_; } /** *
       * Indicates whether the bond transaction is a delegation.
       * 
* * bool is_delegated = 5 [json_name = "isDelegated"]; * @param value The isDelegated to set. * @return This builder for chaining. */ public Builder setIsDelegated(boolean value) { isDelegated_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * Indicates whether the bond transaction is a delegation.
       * 
* * bool is_delegated = 5 [json_name = "isDelegated"]; * @return This builder for chaining. */ public Builder clearIsDelegated() { bitField0_ = (bitField0_ & ~0x00000010); isDelegated_ = false; onChanged(); return this; } private java.lang.Object delegateOwner_ = ""; /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return The delegateOwner. */ public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @param value The delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } delegateOwner_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @return This builder for chaining. */ public Builder clearDelegateOwner() { delegateOwner_ = getDefaultInstance().getDelegateOwner(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * string delegate_owner = 6 [json_name = "delegateOwner"]; * @param value The bytes for delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); delegateOwner_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } private long delegateShare_ ; /** *
       * The share percentage for the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * Must be between 0 and 0.7 PAC in nano PAC.
       * 
* * int64 delegate_share = 7 [json_name = "delegateShare"]; * @return The delegateShare. */ @java.lang.Override public long getDelegateShare() { return delegateShare_; } /** *
       * The share percentage for the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * Must be between 0 and 0.7 PAC in nano PAC.
       * 
* * int64 delegate_share = 7 [json_name = "delegateShare"]; * @param value The delegateShare to set. * @return This builder for chaining. */ public Builder setDelegateShare(long value) { delegateShare_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * The share percentage for the delegate owner.
       * Optional, but required when registering a new validator with delegation.;
       * Must be between 0 and 0.7 PAC in nano PAC.
       * 
* * int64 delegate_share = 7 [json_name = "delegateShare"]; * @return This builder for chaining. */ public Builder clearDelegateShare() { bitField0_ = (bitField0_ & ~0x00000040); delegateShare_ = 0L; onChanged(); return this; } private int delegateExpiry_ ; /** *
       * The expiry height for the delegate relationship.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * uint32 delegate_expiry = 8 [json_name = "delegateExpiry"]; * @return The delegateExpiry. */ @java.lang.Override public int getDelegateExpiry() { return delegateExpiry_; } /** *
       * The expiry height for the delegate relationship.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * uint32 delegate_expiry = 8 [json_name = "delegateExpiry"]; * @param value The delegateExpiry to set. * @return This builder for chaining. */ public Builder setDelegateExpiry(int value) { delegateExpiry_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * The expiry height for the delegate relationship.
       * Optional, but required when registering a new validator with delegation.;
       * 
* * uint32 delegate_expiry = 8 [json_name = "delegateExpiry"]; * @return This builder for chaining. */ public Builder clearDelegateExpiry() { bitField0_ = (bitField0_ & ~0x00000080); delegateExpiry_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PayloadBond) } // @@protoc_insertion_point(class_scope:pactus.PayloadBond) private static final pactus.TransactionOuterClass.PayloadBond DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.PayloadBond(); } public static pactus.TransactionOuterClass.PayloadBond getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PayloadBond parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.PayloadBond getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PayloadSortitionOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PayloadSortition) com.google.protobuf.MessageOrBuilder { /** *
     * The validator address associated with the sortition proof.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The validator address associated with the sortition proof.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The proof for the sortition.
     * 
* * string proof = 2 [json_name = "proof"]; * @return The proof. */ java.lang.String getProof(); /** *
     * The proof for the sortition.
     * 
* * string proof = 2 [json_name = "proof"]; * @return The bytes for proof. */ com.google.protobuf.ByteString getProofBytes(); } /** *
   * Payload for a sortition transaction.
   * 
* * Protobuf type {@code pactus.PayloadSortition} */ public static final class PayloadSortition extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PayloadSortition) PayloadSortitionOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadSortition"); } // Use PayloadSortition.newBuilder() to construct. private PayloadSortition(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PayloadSortition() { address_ = ""; proof_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadSortition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadSortition_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadSortition.class, pactus.TransactionOuterClass.PayloadSortition.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The validator address associated with the sortition proof.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The validator address associated with the sortition proof.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROOF_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object proof_ = ""; /** *
     * The proof for the sortition.
     * 
* * string proof = 2 [json_name = "proof"]; * @return The proof. */ @java.lang.Override public java.lang.String getProof() { java.lang.Object ref = proof_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); proof_ = s; return s; } } /** *
     * The proof for the sortition.
     * 
* * string proof = 2 [json_name = "proof"]; * @return The bytes for proof. */ @java.lang.Override public com.google.protobuf.ByteString getProofBytes() { java.lang.Object ref = proof_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); proof_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(proof_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, proof_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(proof_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, proof_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.PayloadSortition)) { return super.equals(obj); } pactus.TransactionOuterClass.PayloadSortition other = (pactus.TransactionOuterClass.PayloadSortition) obj; if (!getAddress() .equals(other.getAddress())) return false; if (!getProof() .equals(other.getProof())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + PROOF_FIELD_NUMBER; hash = (53 * hash) + getProof().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadSortition parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadSortition parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadSortition parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.PayloadSortition prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Payload for a sortition transaction.
     * 
* * Protobuf type {@code pactus.PayloadSortition} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PayloadSortition) pactus.TransactionOuterClass.PayloadSortitionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadSortition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadSortition_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadSortition.class, pactus.TransactionOuterClass.PayloadSortition.Builder.class); } // Construct using pactus.TransactionOuterClass.PayloadSortition.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; proof_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadSortition_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.PayloadSortition getDefaultInstanceForType() { return pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.PayloadSortition build() { pactus.TransactionOuterClass.PayloadSortition result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.PayloadSortition buildPartial() { pactus.TransactionOuterClass.PayloadSortition result = new pactus.TransactionOuterClass.PayloadSortition(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.PayloadSortition result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.proof_ = proof_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.PayloadSortition) { return mergeFrom((pactus.TransactionOuterClass.PayloadSortition)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.PayloadSortition other) { if (other == pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getProof().isEmpty()) { proof_ = other.proof_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { proof_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The validator address associated with the sortition proof.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The validator address associated with the sortition proof.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The validator address associated with the sortition proof.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The validator address associated with the sortition proof.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The validator address associated with the sortition proof.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object proof_ = ""; /** *
       * The proof for the sortition.
       * 
* * string proof = 2 [json_name = "proof"]; * @return The proof. */ public java.lang.String getProof() { java.lang.Object ref = proof_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); proof_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The proof for the sortition.
       * 
* * string proof = 2 [json_name = "proof"]; * @return The bytes for proof. */ public com.google.protobuf.ByteString getProofBytes() { java.lang.Object ref = proof_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); proof_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The proof for the sortition.
       * 
* * string proof = 2 [json_name = "proof"]; * @param value The proof to set. * @return This builder for chaining. */ public Builder setProof( java.lang.String value) { if (value == null) { throw new NullPointerException(); } proof_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The proof for the sortition.
       * 
* * string proof = 2 [json_name = "proof"]; * @return This builder for chaining. */ public Builder clearProof() { proof_ = getDefaultInstance().getProof(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The proof for the sortition.
       * 
* * string proof = 2 [json_name = "proof"]; * @param value The bytes for proof to set. * @return This builder for chaining. */ public Builder setProofBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); proof_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PayloadSortition) } // @@protoc_insertion_point(class_scope:pactus.PayloadSortition) private static final pactus.TransactionOuterClass.PayloadSortition DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.PayloadSortition(); } public static pactus.TransactionOuterClass.PayloadSortition getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PayloadSortition parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.PayloadSortition getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PayloadUnbondOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PayloadUnbond) com.google.protobuf.MessageOrBuilder { /** *
     * The address of the validator to unbond from.
     * 
* * string validator = 1 [json_name = "validator"]; * @return The validator. */ java.lang.String getValidator(); /** *
     * The address of the validator to unbond from.
     * 
* * string validator = 1 [json_name = "validator"]; * @return The bytes for validator. */ com.google.protobuf.ByteString getValidatorBytes(); /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return The delegateOwner. */ java.lang.String getDelegateOwner(); /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ com.google.protobuf.ByteString getDelegateOwnerBytes(); } /** *
   * Payload for an unbond transaction.
   * 
* * Protobuf type {@code pactus.PayloadUnbond} */ public static final class PayloadUnbond extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PayloadUnbond) PayloadUnbondOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadUnbond"); } // Use PayloadUnbond.newBuilder() to construct. private PayloadUnbond(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PayloadUnbond() { validator_ = ""; delegateOwner_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadUnbond_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadUnbond_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadUnbond.class, pactus.TransactionOuterClass.PayloadUnbond.Builder.class); } public static final int VALIDATOR_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object validator_ = ""; /** *
     * The address of the validator to unbond from.
     * 
* * string validator = 1 [json_name = "validator"]; * @return The validator. */ @java.lang.Override public java.lang.String getValidator() { java.lang.Object ref = validator_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validator_ = s; return s; } } /** *
     * The address of the validator to unbond from.
     * 
* * string validator = 1 [json_name = "validator"]; * @return The bytes for validator. */ @java.lang.Override public com.google.protobuf.ByteString getValidatorBytes() { java.lang.Object ref = validator_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validator_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DELEGATE_OWNER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object delegateOwner_ = ""; /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return The delegateOwner. */ @java.lang.Override public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } } /** *
     * The address of the delegate owner.
     * Optional, but required when the validator is a delegated validator.;
     * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ @java.lang.Override public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validator_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, validator_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, delegateOwner_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validator_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, validator_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(delegateOwner_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, delegateOwner_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.PayloadUnbond)) { return super.equals(obj); } pactus.TransactionOuterClass.PayloadUnbond other = (pactus.TransactionOuterClass.PayloadUnbond) obj; if (!getValidator() .equals(other.getValidator())) return false; if (!getDelegateOwner() .equals(other.getDelegateOwner())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + VALIDATOR_FIELD_NUMBER; hash = (53 * hash) + getValidator().hashCode(); hash = (37 * hash) + DELEGATE_OWNER_FIELD_NUMBER; hash = (53 * hash) + getDelegateOwner().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadUnbond parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadUnbond parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadUnbond parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.PayloadUnbond prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Payload for an unbond transaction.
     * 
* * Protobuf type {@code pactus.PayloadUnbond} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PayloadUnbond) pactus.TransactionOuterClass.PayloadUnbondOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadUnbond_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadUnbond_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadUnbond.class, pactus.TransactionOuterClass.PayloadUnbond.Builder.class); } // Construct using pactus.TransactionOuterClass.PayloadUnbond.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; validator_ = ""; delegateOwner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadUnbond_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbond getDefaultInstanceForType() { return pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbond build() { pactus.TransactionOuterClass.PayloadUnbond result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbond buildPartial() { pactus.TransactionOuterClass.PayloadUnbond result = new pactus.TransactionOuterClass.PayloadUnbond(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.PayloadUnbond result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.validator_ = validator_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.delegateOwner_ = delegateOwner_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.PayloadUnbond) { return mergeFrom((pactus.TransactionOuterClass.PayloadUnbond)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.PayloadUnbond other) { if (other == pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance()) return this; if (!other.getValidator().isEmpty()) { validator_ = other.validator_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getDelegateOwner().isEmpty()) { delegateOwner_ = other.delegateOwner_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { validator_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { delegateOwner_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object validator_ = ""; /** *
       * The address of the validator to unbond from.
       * 
* * string validator = 1 [json_name = "validator"]; * @return The validator. */ public java.lang.String getValidator() { java.lang.Object ref = validator_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validator_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the validator to unbond from.
       * 
* * string validator = 1 [json_name = "validator"]; * @return The bytes for validator. */ public com.google.protobuf.ByteString getValidatorBytes() { java.lang.Object ref = validator_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validator_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the validator to unbond from.
       * 
* * string validator = 1 [json_name = "validator"]; * @param value The validator to set. * @return This builder for chaining. */ public Builder setValidator( java.lang.String value) { if (value == null) { throw new NullPointerException(); } validator_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address of the validator to unbond from.
       * 
* * string validator = 1 [json_name = "validator"]; * @return This builder for chaining. */ public Builder clearValidator() { validator_ = getDefaultInstance().getValidator(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address of the validator to unbond from.
       * 
* * string validator = 1 [json_name = "validator"]; * @param value The bytes for validator to set. * @return This builder for chaining. */ public Builder setValidatorBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); validator_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object delegateOwner_ = ""; /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return The delegateOwner. */ public java.lang.String getDelegateOwner() { java.lang.Object ref = delegateOwner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); delegateOwner_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return The bytes for delegateOwner. */ public com.google.protobuf.ByteString getDelegateOwnerBytes() { java.lang.Object ref = delegateOwner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); delegateOwner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @param value The delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } delegateOwner_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @return This builder for chaining. */ public Builder clearDelegateOwner() { delegateOwner_ = getDefaultInstance().getDelegateOwner(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address of the delegate owner.
       * Optional, but required when the validator is a delegated validator.;
       * 
* * string delegate_owner = 2 [json_name = "delegateOwner"]; * @param value The bytes for delegateOwner to set. * @return This builder for chaining. */ public Builder setDelegateOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); delegateOwner_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PayloadUnbond) } // @@protoc_insertion_point(class_scope:pactus.PayloadUnbond) private static final pactus.TransactionOuterClass.PayloadUnbond DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.PayloadUnbond(); } public static pactus.TransactionOuterClass.PayloadUnbond getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PayloadUnbond parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbond getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PayloadWithdrawOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PayloadWithdraw) com.google.protobuf.MessageOrBuilder { /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return The validatorAddress. */ java.lang.String getValidatorAddress(); /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ com.google.protobuf.ByteString getValidatorAddressBytes(); /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return The accountAddress. */ java.lang.String getAccountAddress(); /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return The bytes for accountAddress. */ com.google.protobuf.ByteString getAccountAddressBytes(); /** *
     * The withdrawal amount in NanoPAC.
     * 
* * int64 amount = 3 [json_name = "amount"]; * @return The amount. */ long getAmount(); } /** *
   * Payload for a withdraw transaction.
   * 
* * Protobuf type {@code pactus.PayloadWithdraw} */ public static final class PayloadWithdraw extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PayloadWithdraw) PayloadWithdrawOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadWithdraw"); } // Use PayloadWithdraw.newBuilder() to construct. private PayloadWithdraw(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PayloadWithdraw() { validatorAddress_ = ""; accountAddress_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadWithdraw_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadWithdraw_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadWithdraw.class, pactus.TransactionOuterClass.PayloadWithdraw.Builder.class); } public static final int VALIDATOR_ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object validatorAddress_ = ""; /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return The validatorAddress. */ @java.lang.Override public java.lang.String getValidatorAddress() { java.lang.Object ref = validatorAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validatorAddress_ = s; return s; } } /** *
     * The address of the validator to withdraw from.
     * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ @java.lang.Override public com.google.protobuf.ByteString getValidatorAddressBytes() { java.lang.Object ref = validatorAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validatorAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ACCOUNT_ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object accountAddress_ = ""; /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return The accountAddress. */ @java.lang.Override public java.lang.String getAccountAddress() { java.lang.Object ref = accountAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); accountAddress_ = s; return s; } } /** *
     * The address of the account to withdraw to.
     * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return The bytes for accountAddress. */ @java.lang.Override public com.google.protobuf.ByteString getAccountAddressBytes() { java.lang.Object ref = accountAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); accountAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AMOUNT_FIELD_NUMBER = 3; private long amount_ = 0L; /** *
     * The withdrawal amount in NanoPAC.
     * 
* * int64 amount = 3 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validatorAddress_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, validatorAddress_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(accountAddress_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, accountAddress_); } if (amount_ != 0L) { output.writeInt64(3, amount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(validatorAddress_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, validatorAddress_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(accountAddress_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, accountAddress_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, amount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.PayloadWithdraw)) { return super.equals(obj); } pactus.TransactionOuterClass.PayloadWithdraw other = (pactus.TransactionOuterClass.PayloadWithdraw) obj; if (!getValidatorAddress() .equals(other.getValidatorAddress())) return false; if (!getAccountAddress() .equals(other.getAccountAddress())) return false; if (getAmount() != other.getAmount()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + VALIDATOR_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getValidatorAddress().hashCode(); hash = (37 * hash) + ACCOUNT_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAccountAddress().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadWithdraw parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadWithdraw parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadWithdraw parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.PayloadWithdraw prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Payload for a withdraw transaction.
     * 
* * Protobuf type {@code pactus.PayloadWithdraw} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PayloadWithdraw) pactus.TransactionOuterClass.PayloadWithdrawOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadWithdraw_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadWithdraw_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadWithdraw.class, pactus.TransactionOuterClass.PayloadWithdraw.Builder.class); } // Construct using pactus.TransactionOuterClass.PayloadWithdraw.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; validatorAddress_ = ""; accountAddress_ = ""; amount_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadWithdraw_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdraw getDefaultInstanceForType() { return pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdraw build() { pactus.TransactionOuterClass.PayloadWithdraw result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdraw buildPartial() { pactus.TransactionOuterClass.PayloadWithdraw result = new pactus.TransactionOuterClass.PayloadWithdraw(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.PayloadWithdraw result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.validatorAddress_ = validatorAddress_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.accountAddress_ = accountAddress_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.amount_ = amount_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.PayloadWithdraw) { return mergeFrom((pactus.TransactionOuterClass.PayloadWithdraw)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.PayloadWithdraw other) { if (other == pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance()) return this; if (!other.getValidatorAddress().isEmpty()) { validatorAddress_ = other.validatorAddress_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAccountAddress().isEmpty()) { accountAddress_ = other.accountAddress_; bitField0_ |= 0x00000002; onChanged(); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { validatorAddress_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { accountAddress_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { amount_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object validatorAddress_ = ""; /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return The validatorAddress. */ public java.lang.String getValidatorAddress() { java.lang.Object ref = validatorAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); validatorAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return The bytes for validatorAddress. */ public com.google.protobuf.ByteString getValidatorAddressBytes() { java.lang.Object ref = validatorAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); validatorAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @param value The validatorAddress to set. * @return This builder for chaining. */ public Builder setValidatorAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } validatorAddress_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @return This builder for chaining. */ public Builder clearValidatorAddress() { validatorAddress_ = getDefaultInstance().getValidatorAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address of the validator to withdraw from.
       * 
* * string validator_address = 1 [json_name = "validatorAddress"]; * @param value The bytes for validatorAddress to set. * @return This builder for chaining. */ public Builder setValidatorAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); validatorAddress_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object accountAddress_ = ""; /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return The accountAddress. */ public java.lang.String getAccountAddress() { java.lang.Object ref = accountAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); accountAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return The bytes for accountAddress. */ public com.google.protobuf.ByteString getAccountAddressBytes() { java.lang.Object ref = accountAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); accountAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 2 [json_name = "accountAddress"]; * @param value The accountAddress to set. * @return This builder for chaining. */ public Builder setAccountAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } accountAddress_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 2 [json_name = "accountAddress"]; * @return This builder for chaining. */ public Builder clearAccountAddress() { accountAddress_ = getDefaultInstance().getAccountAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address of the account to withdraw to.
       * 
* * string account_address = 2 [json_name = "accountAddress"]; * @param value The bytes for accountAddress to set. * @return This builder for chaining. */ public Builder setAccountAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); accountAddress_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long amount_ ; /** *
       * The withdrawal amount in NanoPAC.
       * 
* * int64 amount = 3 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The withdrawal amount in NanoPAC.
       * 
* * int64 amount = 3 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The withdrawal amount in NanoPAC.
       * 
* * int64 amount = 3 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000004); amount_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PayloadWithdraw) } // @@protoc_insertion_point(class_scope:pactus.PayloadWithdraw) private static final pactus.TransactionOuterClass.PayloadWithdraw DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.PayloadWithdraw(); } public static pactus.TransactionOuterClass.PayloadWithdraw getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PayloadWithdraw parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdraw getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PayloadBatchTransferOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PayloadBatchTransfer) com.google.protobuf.MessageOrBuilder { /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ java.util.List getRecipientsList(); /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ pactus.TransactionOuterClass.Recipient getRecipients(int index); /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ int getRecipientsCount(); /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ java.util.List getRecipientsOrBuilderList(); /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ pactus.TransactionOuterClass.RecipientOrBuilder getRecipientsOrBuilder( int index); } /** *
   * Payload for a batch transfer transaction.
   * 
* * Protobuf type {@code pactus.PayloadBatchTransfer} */ public static final class PayloadBatchTransfer extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PayloadBatchTransfer) PayloadBatchTransferOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PayloadBatchTransfer"); } // Use PayloadBatchTransfer.newBuilder() to construct. private PayloadBatchTransfer(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PayloadBatchTransfer() { sender_ = ""; recipients_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBatchTransfer_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBatchTransfer_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadBatchTransfer.class, pactus.TransactionOuterClass.PayloadBatchTransfer.Builder.class); } public static final int SENDER_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's address.
     * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECIPIENTS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List recipients_; /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ @java.lang.Override public java.util.List getRecipientsList() { return recipients_; } /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ @java.lang.Override public java.util.List getRecipientsOrBuilderList() { return recipients_; } /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ @java.lang.Override public int getRecipientsCount() { return recipients_.size(); } /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ @java.lang.Override public pactus.TransactionOuterClass.Recipient getRecipients(int index) { return recipients_.get(index); } /** *
     * The list of recipients with their amounts.
     * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ @java.lang.Override public pactus.TransactionOuterClass.RecipientOrBuilder getRecipientsOrBuilder( int index) { return recipients_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, sender_); } for (int i = 0; i < recipients_.size(); i++) { output.writeMessage(2, recipients_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, sender_); } for (int i = 0; i < recipients_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, recipients_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.PayloadBatchTransfer)) { return super.equals(obj); } pactus.TransactionOuterClass.PayloadBatchTransfer other = (pactus.TransactionOuterClass.PayloadBatchTransfer) obj; if (!getSender() .equals(other.getSender())) return false; if (!getRecipientsList() .equals(other.getRecipientsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); if (getRecipientsCount() > 0) { hash = (37 * hash) + RECIPIENTS_FIELD_NUMBER; hash = (53 * hash) + getRecipientsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.PayloadBatchTransfer parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.PayloadBatchTransfer prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Payload for a batch transfer transaction.
     * 
* * Protobuf type {@code pactus.PayloadBatchTransfer} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PayloadBatchTransfer) pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBatchTransfer_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBatchTransfer_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.PayloadBatchTransfer.class, pactus.TransactionOuterClass.PayloadBatchTransfer.Builder.class); } // Construct using pactus.TransactionOuterClass.PayloadBatchTransfer.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; sender_ = ""; if (recipientsBuilder_ == null) { recipients_ = java.util.Collections.emptyList(); } else { recipients_ = null; recipientsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_PayloadBatchTransfer_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransfer getDefaultInstanceForType() { return pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransfer build() { pactus.TransactionOuterClass.PayloadBatchTransfer result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransfer buildPartial() { pactus.TransactionOuterClass.PayloadBatchTransfer result = new pactus.TransactionOuterClass.PayloadBatchTransfer(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.TransactionOuterClass.PayloadBatchTransfer result) { if (recipientsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { recipients_ = java.util.Collections.unmodifiableList(recipients_); bitField0_ = (bitField0_ & ~0x00000002); } result.recipients_ = recipients_; } else { result.recipients_ = recipientsBuilder_.build(); } } private void buildPartial0(pactus.TransactionOuterClass.PayloadBatchTransfer result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.sender_ = sender_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.PayloadBatchTransfer) { return mergeFrom((pactus.TransactionOuterClass.PayloadBatchTransfer)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.PayloadBatchTransfer other) { if (other == pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance()) return this; if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000001; onChanged(); } if (recipientsBuilder_ == null) { if (!other.recipients_.isEmpty()) { if (recipients_.isEmpty()) { recipients_ = other.recipients_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureRecipientsIsMutable(); recipients_.addAll(other.recipients_); } onChanged(); } } else { if (!other.recipients_.isEmpty()) { if (recipientsBuilder_.isEmpty()) { recipientsBuilder_.dispose(); recipientsBuilder_ = null; recipients_ = other.recipients_; bitField0_ = (bitField0_ & ~0x00000002); recipientsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetRecipientsFieldBuilder() : null; } else { recipientsBuilder_.addAllMessages(other.recipients_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { pactus.TransactionOuterClass.Recipient m = input.readMessage( pactus.TransactionOuterClass.Recipient.parser(), extensionRegistry); if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.add(m); } else { recipientsBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object sender_ = ""; /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 1 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List recipients_ = java.util.Collections.emptyList(); private void ensureRecipientsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { recipients_ = new java.util.ArrayList(recipients_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.Recipient, pactus.TransactionOuterClass.Recipient.Builder, pactus.TransactionOuterClass.RecipientOrBuilder> recipientsBuilder_; /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public java.util.List getRecipientsList() { if (recipientsBuilder_ == null) { return java.util.Collections.unmodifiableList(recipients_); } else { return recipientsBuilder_.getMessageList(); } } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public int getRecipientsCount() { if (recipientsBuilder_ == null) { return recipients_.size(); } else { return recipientsBuilder_.getCount(); } } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient getRecipients(int index) { if (recipientsBuilder_ == null) { return recipients_.get(index); } else { return recipientsBuilder_.getMessage(index); } } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder setRecipients( int index, pactus.TransactionOuterClass.Recipient value) { if (recipientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRecipientsIsMutable(); recipients_.set(index, value); onChanged(); } else { recipientsBuilder_.setMessage(index, value); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder setRecipients( int index, pactus.TransactionOuterClass.Recipient.Builder builderForValue) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.set(index, builderForValue.build()); onChanged(); } else { recipientsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder addRecipients(pactus.TransactionOuterClass.Recipient value) { if (recipientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRecipientsIsMutable(); recipients_.add(value); onChanged(); } else { recipientsBuilder_.addMessage(value); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder addRecipients( int index, pactus.TransactionOuterClass.Recipient value) { if (recipientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRecipientsIsMutable(); recipients_.add(index, value); onChanged(); } else { recipientsBuilder_.addMessage(index, value); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder addRecipients( pactus.TransactionOuterClass.Recipient.Builder builderForValue) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.add(builderForValue.build()); onChanged(); } else { recipientsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder addRecipients( int index, pactus.TransactionOuterClass.Recipient.Builder builderForValue) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.add(index, builderForValue.build()); onChanged(); } else { recipientsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder addAllRecipients( java.lang.Iterable values) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, recipients_); onChanged(); } else { recipientsBuilder_.addAllMessages(values); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder clearRecipients() { if (recipientsBuilder_ == null) { recipients_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { recipientsBuilder_.clear(); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public Builder removeRecipients(int index) { if (recipientsBuilder_ == null) { ensureRecipientsIsMutable(); recipients_.remove(index); onChanged(); } else { recipientsBuilder_.remove(index); } return this; } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient.Builder getRecipientsBuilder( int index) { return internalGetRecipientsFieldBuilder().getBuilder(index); } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.RecipientOrBuilder getRecipientsOrBuilder( int index) { if (recipientsBuilder_ == null) { return recipients_.get(index); } else { return recipientsBuilder_.getMessageOrBuilder(index); } } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public java.util.List getRecipientsOrBuilderList() { if (recipientsBuilder_ != null) { return recipientsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(recipients_); } } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient.Builder addRecipientsBuilder() { return internalGetRecipientsFieldBuilder().addBuilder( pactus.TransactionOuterClass.Recipient.getDefaultInstance()); } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public pactus.TransactionOuterClass.Recipient.Builder addRecipientsBuilder( int index) { return internalGetRecipientsFieldBuilder().addBuilder( index, pactus.TransactionOuterClass.Recipient.getDefaultInstance()); } /** *
       * The list of recipients with their amounts.
       * 
* * repeated .pactus.Recipient recipients = 2 [json_name = "recipients"]; */ public java.util.List getRecipientsBuilderList() { return internalGetRecipientsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.Recipient, pactus.TransactionOuterClass.Recipient.Builder, pactus.TransactionOuterClass.RecipientOrBuilder> internalGetRecipientsFieldBuilder() { if (recipientsBuilder_ == null) { recipientsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.TransactionOuterClass.Recipient, pactus.TransactionOuterClass.Recipient.Builder, pactus.TransactionOuterClass.RecipientOrBuilder>( recipients_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); recipients_ = null; } return recipientsBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.PayloadBatchTransfer) } // @@protoc_insertion_point(class_scope:pactus.PayloadBatchTransfer) private static final pactus.TransactionOuterClass.PayloadBatchTransfer DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.PayloadBatchTransfer(); } public static pactus.TransactionOuterClass.PayloadBatchTransfer getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PayloadBatchTransfer parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransfer getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RecipientOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.Recipient) com.google.protobuf.MessageOrBuilder { /** *
     * The receiver's address.
     * 
* * string receiver = 1 [json_name = "receiver"]; * @return The receiver. */ java.lang.String getReceiver(); /** *
     * The receiver's address.
     * 
* * string receiver = 1 [json_name = "receiver"]; * @return The bytes for receiver. */ com.google.protobuf.ByteString getReceiverBytes(); /** *
     * The amount in NanoPAC.
     * 
* * int64 amount = 2 [json_name = "amount"]; * @return The amount. */ long getAmount(); } /** *
   * Recipient is receiver with amount.
   * 
* * Protobuf type {@code pactus.Recipient} */ public static final class Recipient extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.Recipient) RecipientOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "Recipient"); } // Use Recipient.newBuilder() to construct. private Recipient(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private Recipient() { receiver_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_Recipient_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_Recipient_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.Recipient.class, pactus.TransactionOuterClass.Recipient.Builder.class); } public static final int RECEIVER_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object receiver_ = ""; /** *
     * The receiver's address.
     * 
* * string receiver = 1 [json_name = "receiver"]; * @return The receiver. */ @java.lang.Override public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } } /** *
     * The receiver's address.
     * 
* * string receiver = 1 [json_name = "receiver"]; * @return The bytes for receiver. */ @java.lang.Override public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AMOUNT_FIELD_NUMBER = 2; private long amount_ = 0L; /** *
     * The amount in NanoPAC.
     * 
* * int64 amount = 2 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, receiver_); } if (amount_ != 0L) { output.writeInt64(2, amount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, receiver_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, amount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.Recipient)) { return super.equals(obj); } pactus.TransactionOuterClass.Recipient other = (pactus.TransactionOuterClass.Recipient) obj; if (!getReceiver() .equals(other.getReceiver())) return false; if (getAmount() != other.getAmount()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RECEIVER_FIELD_NUMBER; hash = (53 * hash) + getReceiver().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.Recipient parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.Recipient parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.Recipient parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.Recipient parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.Recipient parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.Recipient parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.Recipient parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.Recipient parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.Recipient parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.Recipient parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.Recipient parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.Recipient parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.Recipient prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Recipient is receiver with amount.
     * 
* * Protobuf type {@code pactus.Recipient} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.Recipient) pactus.TransactionOuterClass.RecipientOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_Recipient_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_Recipient_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.Recipient.class, pactus.TransactionOuterClass.Recipient.Builder.class); } // Construct using pactus.TransactionOuterClass.Recipient.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; receiver_ = ""; amount_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_Recipient_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.Recipient getDefaultInstanceForType() { return pactus.TransactionOuterClass.Recipient.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.Recipient build() { pactus.TransactionOuterClass.Recipient result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.Recipient buildPartial() { pactus.TransactionOuterClass.Recipient result = new pactus.TransactionOuterClass.Recipient(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.Recipient result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.receiver_ = receiver_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.amount_ = amount_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.Recipient) { return mergeFrom((pactus.TransactionOuterClass.Recipient)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.Recipient other) { if (other == pactus.TransactionOuterClass.Recipient.getDefaultInstance()) return this; if (!other.getReceiver().isEmpty()) { receiver_ = other.receiver_; bitField0_ |= 0x00000001; onChanged(); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { receiver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { amount_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object receiver_ = ""; /** *
       * The receiver's address.
       * 
* * string receiver = 1 [json_name = "receiver"]; * @return The receiver. */ public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 1 [json_name = "receiver"]; * @return The bytes for receiver. */ public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 1 [json_name = "receiver"]; * @param value The receiver to set. * @return This builder for chaining. */ public Builder setReceiver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } receiver_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 1 [json_name = "receiver"]; * @return This builder for chaining. */ public Builder clearReceiver() { receiver_ = getDefaultInstance().getReceiver(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 1 [json_name = "receiver"]; * @param value The bytes for receiver to set. * @return This builder for chaining. */ public Builder setReceiverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); receiver_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private long amount_ ; /** *
       * The amount in NanoPAC.
       * 
* * int64 amount = 2 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The amount in NanoPAC.
       * 
* * int64 amount = 2 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The amount in NanoPAC.
       * 
* * int64 amount = 2 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000002); amount_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.Recipient) } // @@protoc_insertion_point(class_scope:pactus.Recipient) private static final pactus.TransactionOuterClass.Recipient DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.Recipient(); } public static pactus.TransactionOuterClass.Recipient getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public Recipient parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.Recipient getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface TransactionInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.TransactionInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The unique ID of the transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The id. */ java.lang.String getId(); /** *
     * The unique ID of the transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ com.google.protobuf.ByteString getIdBytes(); /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string data = 2 [json_name = "data"]; * @return The data. */ java.lang.String getData(); /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ com.google.protobuf.ByteString getDataBytes(); /** *
     * The version of the transaction.
     * 
* * int32 version = 3 [json_name = "version"]; * @return The version. */ int getVersion(); /** *
     * The lock time for the transaction.
     * 
* * uint32 lock_time = 4 [json_name = "lockTime"]; * @return The lockTime. */ int getLockTime(); /** *
     * The value of the transaction in NanoPAC.
     * 
* * int64 value = 5 [json_name = "value"]; * @return The value. */ long getValue(); /** *
     * The fee for the transaction in NanoPAC.
     * 
* * int64 fee = 6 [json_name = "fee"]; * @return The fee. */ long getFee(); /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ int getPayloadTypeValue(); /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return The payloadType. */ pactus.TransactionOuterClass.PayloadType getPayloadType(); /** *
     * Transfer transaction payload.
     * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; * @return Whether the transfer field is set. */ boolean hasTransfer(); /** *
     * Transfer transaction payload.
     * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; * @return The transfer. */ pactus.TransactionOuterClass.PayloadTransfer getTransfer(); /** *
     * Transfer transaction payload.
     * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ pactus.TransactionOuterClass.PayloadTransferOrBuilder getTransferOrBuilder(); /** *
     * Bond transaction payload.
     * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; * @return Whether the bond field is set. */ boolean hasBond(); /** *
     * Bond transaction payload.
     * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; * @return The bond. */ pactus.TransactionOuterClass.PayloadBond getBond(); /** *
     * Bond transaction payload.
     * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ pactus.TransactionOuterClass.PayloadBondOrBuilder getBondOrBuilder(); /** *
     * Sortition transaction payload.
     * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; * @return Whether the sortition field is set. */ boolean hasSortition(); /** *
     * Sortition transaction payload.
     * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; * @return The sortition. */ pactus.TransactionOuterClass.PayloadSortition getSortition(); /** *
     * Sortition transaction payload.
     * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ pactus.TransactionOuterClass.PayloadSortitionOrBuilder getSortitionOrBuilder(); /** *
     * Unbond transaction payload.
     * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; * @return Whether the unbond field is set. */ boolean hasUnbond(); /** *
     * Unbond transaction payload.
     * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; * @return The unbond. */ pactus.TransactionOuterClass.PayloadUnbond getUnbond(); /** *
     * Unbond transaction payload.
     * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ pactus.TransactionOuterClass.PayloadUnbondOrBuilder getUnbondOrBuilder(); /** *
     * Withdraw transaction payload.
     * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; * @return Whether the withdraw field is set. */ boolean hasWithdraw(); /** *
     * Withdraw transaction payload.
     * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; * @return The withdraw. */ pactus.TransactionOuterClass.PayloadWithdraw getWithdraw(); /** *
     * Withdraw transaction payload.
     * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ pactus.TransactionOuterClass.PayloadWithdrawOrBuilder getWithdrawOrBuilder(); /** *
     * Batch Transfer transaction payload.
     * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; * @return Whether the batchTransfer field is set. */ boolean hasBatchTransfer(); /** *
     * Batch Transfer transaction payload.
     * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; * @return The batchTransfer. */ pactus.TransactionOuterClass.PayloadBatchTransfer getBatchTransfer(); /** *
     * Batch Transfer transaction payload.
     * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder getBatchTransferOrBuilder(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); /** *
     * The public key associated with the transaction.
     * 
* * string public_key = 9 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key associated with the transaction.
     * 
* * string public_key = 9 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); /** *
     * The signature for the transaction.
     * 
* * string signature = 10 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The signature for the transaction.
     * 
* * string signature = 10 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); /** *
     * The block height containing the transaction.
     * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
     * 
* * uint32 block_height = 11 [json_name = "blockHeight"]; * @return The blockHeight. */ int getBlockHeight(); /** *
     * Indicates whether the transaction is confirmed.
     * 
* * bool confirmed = 12 [json_name = "confirmed"]; * @return The confirmed. */ boolean getConfirmed(); /** *
     * The number of blocks that have been added to the chain after this transaction was included in a block.
     * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
     * 
* * int32 confirmations = 13 [json_name = "confirmations"]; * @return The confirmations. */ int getConfirmations(); pactus.TransactionOuterClass.TransactionInfo.PayloadCase getPayloadCase(); } /** *
   * Information about a transaction.
   * 
* * Protobuf type {@code pactus.TransactionInfo} */ public static final class TransactionInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.TransactionInfo) TransactionInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "TransactionInfo"); } // Use TransactionInfo.newBuilder() to construct. private TransactionInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private TransactionInfo() { id_ = ""; data_ = ""; payloadType_ = 0; memo_ = ""; publicKey_ = ""; signature_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_TransactionInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_TransactionInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.TransactionInfo.class, pactus.TransactionOuterClass.TransactionInfo.Builder.class); } private int payloadCase_ = 0; @SuppressWarnings("serial") private java.lang.Object payload_; public enum PayloadCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { TRANSFER(30), BOND(31), SORTITION(32), UNBOND(33), WITHDRAW(34), BATCH_TRANSFER(35), PAYLOAD_NOT_SET(0); private final int value; private PayloadCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static PayloadCase valueOf(int value) { return forNumber(value); } public static PayloadCase forNumber(int value) { switch (value) { case 30: return TRANSFER; case 31: return BOND; case 32: return SORTITION; case 33: return UNBOND; case 34: return WITHDRAW; case 35: return BATCH_TRANSFER; case 0: return PAYLOAD_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public PayloadCase getPayloadCase() { return PayloadCase.forNumber( payloadCase_); } public static final int ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object id_ = ""; /** *
     * The unique ID of the transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** *
     * The unique ID of the transaction.
     * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object data_ = ""; /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string data = 2 [json_name = "data"]; * @return The data. */ @java.lang.Override public java.lang.String getData() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } } /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ @java.lang.Override public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERSION_FIELD_NUMBER = 3; private int version_ = 0; /** *
     * The version of the transaction.
     * 
* * int32 version = 3 [json_name = "version"]; * @return The version. */ @java.lang.Override public int getVersion() { return version_; } public static final int LOCK_TIME_FIELD_NUMBER = 4; private int lockTime_ = 0; /** *
     * The lock time for the transaction.
     * 
* * uint32 lock_time = 4 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } public static final int VALUE_FIELD_NUMBER = 5; private long value_ = 0L; /** *
     * The value of the transaction in NanoPAC.
     * 
* * int64 value = 5 [json_name = "value"]; * @return The value. */ @java.lang.Override public long getValue() { return value_; } public static final int FEE_FIELD_NUMBER = 6; private long fee_ = 0L; /** *
     * The fee for the transaction in NanoPAC.
     * 
* * int64 fee = 6 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } public static final int PAYLOAD_TYPE_FIELD_NUMBER = 7; private int payloadType_ = 0; /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } public static final int TRANSFER_FIELD_NUMBER = 30; /** *
     * Transfer transaction payload.
     * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; * @return Whether the transfer field is set. */ @java.lang.Override public boolean hasTransfer() { return payloadCase_ == 30; } /** *
     * Transfer transaction payload.
     * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; * @return The transfer. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadTransfer getTransfer() { if (payloadCase_ == 30) { return (pactus.TransactionOuterClass.PayloadTransfer) payload_; } return pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } /** *
     * Transfer transaction payload.
     * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadTransferOrBuilder getTransferOrBuilder() { if (payloadCase_ == 30) { return (pactus.TransactionOuterClass.PayloadTransfer) payload_; } return pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } public static final int BOND_FIELD_NUMBER = 31; /** *
     * Bond transaction payload.
     * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; * @return Whether the bond field is set. */ @java.lang.Override public boolean hasBond() { return payloadCase_ == 31; } /** *
     * Bond transaction payload.
     * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; * @return The bond. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBond getBond() { if (payloadCase_ == 31) { return (pactus.TransactionOuterClass.PayloadBond) payload_; } return pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } /** *
     * Bond transaction payload.
     * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBondOrBuilder getBondOrBuilder() { if (payloadCase_ == 31) { return (pactus.TransactionOuterClass.PayloadBond) payload_; } return pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } public static final int SORTITION_FIELD_NUMBER = 32; /** *
     * Sortition transaction payload.
     * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; * @return Whether the sortition field is set. */ @java.lang.Override public boolean hasSortition() { return payloadCase_ == 32; } /** *
     * Sortition transaction payload.
     * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; * @return The sortition. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadSortition getSortition() { if (payloadCase_ == 32) { return (pactus.TransactionOuterClass.PayloadSortition) payload_; } return pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } /** *
     * Sortition transaction payload.
     * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadSortitionOrBuilder getSortitionOrBuilder() { if (payloadCase_ == 32) { return (pactus.TransactionOuterClass.PayloadSortition) payload_; } return pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } public static final int UNBOND_FIELD_NUMBER = 33; /** *
     * Unbond transaction payload.
     * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; * @return Whether the unbond field is set. */ @java.lang.Override public boolean hasUnbond() { return payloadCase_ == 33; } /** *
     * Unbond transaction payload.
     * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; * @return The unbond. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbond getUnbond() { if (payloadCase_ == 33) { return (pactus.TransactionOuterClass.PayloadUnbond) payload_; } return pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } /** *
     * Unbond transaction payload.
     * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbondOrBuilder getUnbondOrBuilder() { if (payloadCase_ == 33) { return (pactus.TransactionOuterClass.PayloadUnbond) payload_; } return pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } public static final int WITHDRAW_FIELD_NUMBER = 34; /** *
     * Withdraw transaction payload.
     * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; * @return Whether the withdraw field is set. */ @java.lang.Override public boolean hasWithdraw() { return payloadCase_ == 34; } /** *
     * Withdraw transaction payload.
     * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; * @return The withdraw. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdraw getWithdraw() { if (payloadCase_ == 34) { return (pactus.TransactionOuterClass.PayloadWithdraw) payload_; } return pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } /** *
     * Withdraw transaction payload.
     * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdrawOrBuilder getWithdrawOrBuilder() { if (payloadCase_ == 34) { return (pactus.TransactionOuterClass.PayloadWithdraw) payload_; } return pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } public static final int BATCH_TRANSFER_FIELD_NUMBER = 35; /** *
     * Batch Transfer transaction payload.
     * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; * @return Whether the batchTransfer field is set. */ @java.lang.Override public boolean hasBatchTransfer() { return payloadCase_ == 35; } /** *
     * Batch Transfer transaction payload.
     * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; * @return The batchTransfer. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransfer getBatchTransfer() { if (payloadCase_ == 35) { return (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_; } return pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } /** *
     * Batch Transfer transaction payload.
     * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder getBatchTransferOrBuilder() { if (payloadCase_ == 35) { return (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_; } return pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } public static final int MEMO_FIELD_NUMBER = 8; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PUBLIC_KEY_FIELD_NUMBER = 9; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key associated with the transaction.
     * 
* * string public_key = 9 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key associated with the transaction.
     * 
* * string public_key = 9 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SIGNATURE_FIELD_NUMBER = 10; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The signature for the transaction.
     * 
* * string signature = 10 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The signature for the transaction.
     * 
* * string signature = 10 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int BLOCK_HEIGHT_FIELD_NUMBER = 11; private int blockHeight_ = 0; /** *
     * The block height containing the transaction.
     * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
     * 
* * uint32 block_height = 11 [json_name = "blockHeight"]; * @return The blockHeight. */ @java.lang.Override public int getBlockHeight() { return blockHeight_; } public static final int CONFIRMED_FIELD_NUMBER = 12; private boolean confirmed_ = false; /** *
     * Indicates whether the transaction is confirmed.
     * 
* * bool confirmed = 12 [json_name = "confirmed"]; * @return The confirmed. */ @java.lang.Override public boolean getConfirmed() { return confirmed_; } public static final int CONFIRMATIONS_FIELD_NUMBER = 13; private int confirmations_ = 0; /** *
     * The number of blocks that have been added to the chain after this transaction was included in a block.
     * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
     * 
* * int32 confirmations = 13 [json_name = "confirmations"]; * @return The confirmations. */ @java.lang.Override public int getConfirmations() { return confirmations_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, id_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, data_); } if (version_ != 0) { output.writeInt32(3, version_); } if (lockTime_ != 0) { output.writeUInt32(4, lockTime_); } if (value_ != 0L) { output.writeInt64(5, value_); } if (fee_ != 0L) { output.writeInt64(6, fee_); } if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(7, payloadType_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 8, memo_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 9, publicKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 10, signature_); } if (blockHeight_ != 0) { output.writeUInt32(11, blockHeight_); } if (confirmed_ != false) { output.writeBool(12, confirmed_); } if (confirmations_ != 0) { output.writeInt32(13, confirmations_); } if (payloadCase_ == 30) { output.writeMessage(30, (pactus.TransactionOuterClass.PayloadTransfer) payload_); } if (payloadCase_ == 31) { output.writeMessage(31, (pactus.TransactionOuterClass.PayloadBond) payload_); } if (payloadCase_ == 32) { output.writeMessage(32, (pactus.TransactionOuterClass.PayloadSortition) payload_); } if (payloadCase_ == 33) { output.writeMessage(33, (pactus.TransactionOuterClass.PayloadUnbond) payload_); } if (payloadCase_ == 34) { output.writeMessage(34, (pactus.TransactionOuterClass.PayloadWithdraw) payload_); } if (payloadCase_ == 35) { output.writeMessage(35, (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, id_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(data_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, data_); } if (version_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, version_); } if (lockTime_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(4, lockTime_); } if (value_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, value_); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, fee_); } if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(7, payloadType_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(8, memo_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(9, publicKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(10, signature_); } if (blockHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(11, blockHeight_); } if (confirmed_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(12, confirmed_); } if (confirmations_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(13, confirmations_); } if (payloadCase_ == 30) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(30, (pactus.TransactionOuterClass.PayloadTransfer) payload_); } if (payloadCase_ == 31) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(31, (pactus.TransactionOuterClass.PayloadBond) payload_); } if (payloadCase_ == 32) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(32, (pactus.TransactionOuterClass.PayloadSortition) payload_); } if (payloadCase_ == 33) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(33, (pactus.TransactionOuterClass.PayloadUnbond) payload_); } if (payloadCase_ == 34) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(34, (pactus.TransactionOuterClass.PayloadWithdraw) payload_); } if (payloadCase_ == 35) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(35, (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.TransactionInfo)) { return super.equals(obj); } pactus.TransactionOuterClass.TransactionInfo other = (pactus.TransactionOuterClass.TransactionInfo) obj; if (!getId() .equals(other.getId())) return false; if (!getData() .equals(other.getData())) return false; if (getVersion() != other.getVersion()) return false; if (getLockTime() != other.getLockTime()) return false; if (getValue() != other.getValue()) return false; if (getFee() != other.getFee()) return false; if (payloadType_ != other.payloadType_) return false; if (!getMemo() .equals(other.getMemo())) return false; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (!getSignature() .equals(other.getSignature())) return false; if (getBlockHeight() != other.getBlockHeight()) return false; if (getConfirmed() != other.getConfirmed()) return false; if (getConfirmations() != other.getConfirmations()) return false; if (!getPayloadCase().equals(other.getPayloadCase())) return false; switch (payloadCase_) { case 30: if (!getTransfer() .equals(other.getTransfer())) return false; break; case 31: if (!getBond() .equals(other.getBond())) return false; break; case 32: if (!getSortition() .equals(other.getSortition())) return false; break; case 33: if (!getUnbond() .equals(other.getUnbond())) return false; break; case 34: if (!getWithdraw() .equals(other.getWithdraw())) return false; break; case 35: if (!getBatchTransfer() .equals(other.getBatchTransfer())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion(); hash = (37 * hash) + LOCK_TIME_FIELD_NUMBER; hash = (53 * hash) + getLockTime(); hash = (37 * hash) + VALUE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getValue()); hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (37 * hash) + PAYLOAD_TYPE_FIELD_NUMBER; hash = (53 * hash) + payloadType_; hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (37 * hash) + BLOCK_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getBlockHeight(); hash = (37 * hash) + CONFIRMED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getConfirmed()); hash = (37 * hash) + CONFIRMATIONS_FIELD_NUMBER; hash = (53 * hash) + getConfirmations(); switch (payloadCase_) { case 30: hash = (37 * hash) + TRANSFER_FIELD_NUMBER; hash = (53 * hash) + getTransfer().hashCode(); break; case 31: hash = (37 * hash) + BOND_FIELD_NUMBER; hash = (53 * hash) + getBond().hashCode(); break; case 32: hash = (37 * hash) + SORTITION_FIELD_NUMBER; hash = (53 * hash) + getSortition().hashCode(); break; case 33: hash = (37 * hash) + UNBOND_FIELD_NUMBER; hash = (53 * hash) + getUnbond().hashCode(); break; case 34: hash = (37 * hash) + WITHDRAW_FIELD_NUMBER; hash = (53 * hash) + getWithdraw().hashCode(); break; case 35: hash = (37 * hash) + BATCH_TRANSFER_FIELD_NUMBER; hash = (53 * hash) + getBatchTransfer().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.TransactionInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.TransactionInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.TransactionInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.TransactionInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Information about a transaction.
     * 
* * Protobuf type {@code pactus.TransactionInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.TransactionInfo) pactus.TransactionOuterClass.TransactionInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_TransactionInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_TransactionInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.TransactionInfo.class, pactus.TransactionOuterClass.TransactionInfo.Builder.class); } // Construct using pactus.TransactionOuterClass.TransactionInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; id_ = ""; data_ = ""; version_ = 0; lockTime_ = 0; value_ = 0L; fee_ = 0L; payloadType_ = 0; if (transferBuilder_ != null) { transferBuilder_.clear(); } if (bondBuilder_ != null) { bondBuilder_.clear(); } if (sortitionBuilder_ != null) { sortitionBuilder_.clear(); } if (unbondBuilder_ != null) { unbondBuilder_.clear(); } if (withdrawBuilder_ != null) { withdrawBuilder_.clear(); } if (batchTransferBuilder_ != null) { batchTransferBuilder_.clear(); } memo_ = ""; publicKey_ = ""; signature_ = ""; blockHeight_ = 0; confirmed_ = false; confirmations_ = 0; payloadCase_ = 0; payload_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_TransactionInfo_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo getDefaultInstanceForType() { return pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo build() { pactus.TransactionOuterClass.TransactionInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo buildPartial() { pactus.TransactionOuterClass.TransactionInfo result = new pactus.TransactionOuterClass.TransactionInfo(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.TransactionInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.id_ = id_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.data_ = data_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.version_ = version_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.lockTime_ = lockTime_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.value_ = value_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.fee_ = fee_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.payloadType_ = payloadType_; } if (((from_bitField0_ & 0x00002000) != 0)) { result.memo_ = memo_; } if (((from_bitField0_ & 0x00004000) != 0)) { result.publicKey_ = publicKey_; } if (((from_bitField0_ & 0x00008000) != 0)) { result.signature_ = signature_; } if (((from_bitField0_ & 0x00010000) != 0)) { result.blockHeight_ = blockHeight_; } if (((from_bitField0_ & 0x00020000) != 0)) { result.confirmed_ = confirmed_; } if (((from_bitField0_ & 0x00040000) != 0)) { result.confirmations_ = confirmations_; } } private void buildPartialOneofs(pactus.TransactionOuterClass.TransactionInfo result) { result.payloadCase_ = payloadCase_; result.payload_ = this.payload_; if (payloadCase_ == 30 && transferBuilder_ != null) { result.payload_ = transferBuilder_.build(); } if (payloadCase_ == 31 && bondBuilder_ != null) { result.payload_ = bondBuilder_.build(); } if (payloadCase_ == 32 && sortitionBuilder_ != null) { result.payload_ = sortitionBuilder_.build(); } if (payloadCase_ == 33 && unbondBuilder_ != null) { result.payload_ = unbondBuilder_.build(); } if (payloadCase_ == 34 && withdrawBuilder_ != null) { result.payload_ = withdrawBuilder_.build(); } if (payloadCase_ == 35 && batchTransferBuilder_ != null) { result.payload_ = batchTransferBuilder_.build(); } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.TransactionInfo) { return mergeFrom((pactus.TransactionOuterClass.TransactionInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.TransactionInfo other) { if (other == pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()) return this; if (!other.getId().isEmpty()) { id_ = other.id_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getData().isEmpty()) { data_ = other.data_; bitField0_ |= 0x00000002; onChanged(); } if (other.getVersion() != 0) { setVersion(other.getVersion()); } if (other.getLockTime() != 0) { setLockTime(other.getLockTime()); } if (other.getValue() != 0L) { setValue(other.getValue()); } if (other.getFee() != 0L) { setFee(other.getFee()); } if (other.payloadType_ != 0) { setPayloadTypeValue(other.getPayloadTypeValue()); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00002000; onChanged(); } if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00004000; onChanged(); } if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00008000; onChanged(); } if (other.getBlockHeight() != 0) { setBlockHeight(other.getBlockHeight()); } if (other.getConfirmed() != false) { setConfirmed(other.getConfirmed()); } if (other.getConfirmations() != 0) { setConfirmations(other.getConfirmations()); } switch (other.getPayloadCase()) { case TRANSFER: { mergeTransfer(other.getTransfer()); break; } case BOND: { mergeBond(other.getBond()); break; } case SORTITION: { mergeSortition(other.getSortition()); break; } case UNBOND: { mergeUnbond(other.getUnbond()); break; } case WITHDRAW: { mergeWithdraw(other.getWithdraw()); break; } case BATCH_TRANSFER: { mergeBatchTransfer(other.getBatchTransfer()); break; } case PAYLOAD_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { id_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { data_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { version_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { lockTime_ = input.readUInt32(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { value_ = input.readInt64(); bitField0_ |= 0x00000010; break; } // case 40 case 48: { fee_ = input.readInt64(); bitField0_ |= 0x00000020; break; } // case 48 case 56: { payloadType_ = input.readEnum(); bitField0_ |= 0x00000040; break; } // case 56 case 66: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00002000; break; } // case 66 case 74: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00004000; break; } // case 74 case 82: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00008000; break; } // case 82 case 88: { blockHeight_ = input.readUInt32(); bitField0_ |= 0x00010000; break; } // case 88 case 96: { confirmed_ = input.readBool(); bitField0_ |= 0x00020000; break; } // case 96 case 104: { confirmations_ = input.readInt32(); bitField0_ |= 0x00040000; break; } // case 104 case 242: { input.readMessage( internalGetTransferFieldBuilder().getBuilder(), extensionRegistry); payloadCase_ = 30; break; } // case 242 case 250: { input.readMessage( internalGetBondFieldBuilder().getBuilder(), extensionRegistry); payloadCase_ = 31; break; } // case 250 case 258: { input.readMessage( internalGetSortitionFieldBuilder().getBuilder(), extensionRegistry); payloadCase_ = 32; break; } // case 258 case 266: { input.readMessage( internalGetUnbondFieldBuilder().getBuilder(), extensionRegistry); payloadCase_ = 33; break; } // case 266 case 274: { input.readMessage( internalGetWithdrawFieldBuilder().getBuilder(), extensionRegistry); payloadCase_ = 34; break; } // case 274 case 282: { input.readMessage( internalGetBatchTransferFieldBuilder().getBuilder(), extensionRegistry); payloadCase_ = 35; break; } // case 282 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int payloadCase_ = 0; private java.lang.Object payload_; public PayloadCase getPayloadCase() { return PayloadCase.forNumber( payloadCase_); } public Builder clearPayload() { payloadCase_ = 0; payload_ = null; onChanged(); return this; } private int bitField0_; private java.lang.Object id_ = ""; /** *
       * The unique ID of the transaction.
       * 
* * string id = 1 [json_name = "id"]; * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The unique ID of the transaction.
       * 
* * string id = 1 [json_name = "id"]; * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The unique ID of the transaction.
       * 
* * string id = 1 [json_name = "id"]; * @param value The id to set. * @return This builder for chaining. */ public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The unique ID of the transaction.
       * 
* * string id = 1 [json_name = "id"]; * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The unique ID of the transaction.
       * 
* * string id = 1 [json_name = "id"]; * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object data_ = ""; /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string data = 2 [json_name = "data"]; * @return The data. */ public java.lang.String getData() { java.lang.Object ref = data_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); data_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string data = 2 [json_name = "data"]; * @return The bytes for data. */ public com.google.protobuf.ByteString getDataBytes() { java.lang.Object ref = data_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); data_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string data = 2 [json_name = "data"]; * @param value The data to set. * @return This builder for chaining. */ public Builder setData( java.lang.String value) { if (value == null) { throw new NullPointerException(); } data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string data = 2 [json_name = "data"]; * @return This builder for chaining. */ public Builder clearData() { data_ = getDefaultInstance().getData(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string data = 2 [json_name = "data"]; * @param value The bytes for data to set. * @return This builder for chaining. */ public Builder setDataBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int version_ ; /** *
       * The version of the transaction.
       * 
* * int32 version = 3 [json_name = "version"]; * @return The version. */ @java.lang.Override public int getVersion() { return version_; } /** *
       * The version of the transaction.
       * 
* * int32 version = 3 [json_name = "version"]; * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(int value) { version_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The version of the transaction.
       * 
* * int32 version = 3 [json_name = "version"]; * @return This builder for chaining. */ public Builder clearVersion() { bitField0_ = (bitField0_ & ~0x00000004); version_ = 0; onChanged(); return this; } private int lockTime_ ; /** *
       * The lock time for the transaction.
       * 
* * uint32 lock_time = 4 [json_name = "lockTime"]; * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** *
       * The lock time for the transaction.
       * 
* * uint32 lock_time = 4 [json_name = "lockTime"]; * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { lockTime_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The lock time for the transaction.
       * 
* * uint32 lock_time = 4 [json_name = "lockTime"]; * @return This builder for chaining. */ public Builder clearLockTime() { bitField0_ = (bitField0_ & ~0x00000008); lockTime_ = 0; onChanged(); return this; } private long value_ ; /** *
       * The value of the transaction in NanoPAC.
       * 
* * int64 value = 5 [json_name = "value"]; * @return The value. */ @java.lang.Override public long getValue() { return value_; } /** *
       * The value of the transaction in NanoPAC.
       * 
* * int64 value = 5 [json_name = "value"]; * @param value The value to set. * @return This builder for chaining. */ public Builder setValue(long value) { value_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The value of the transaction in NanoPAC.
       * 
* * int64 value = 5 [json_name = "value"]; * @return This builder for chaining. */ public Builder clearValue() { bitField0_ = (bitField0_ & ~0x00000010); value_ = 0L; onChanged(); return this; } private long fee_ ; /** *
       * The fee for the transaction in NanoPAC.
       * 
* * int64 fee = 6 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The fee for the transaction in NanoPAC.
       * 
* * int64 fee = 6 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The fee for the transaction in NanoPAC.
       * 
* * int64 fee = 6 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000020); fee_ = 0L; onChanged(); return this; } private int payloadType_ = 0; /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @param value The enum numeric value on the wire for payloadType to set. * @return This builder for chaining. */ public Builder setPayloadTypeValue(int value) { payloadType_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @param value The payloadType to set. * @return This builder for chaining. */ public Builder setPayloadType(pactus.TransactionOuterClass.PayloadType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; payloadType_ = value.getNumber(); onChanged(); return this; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 7 [json_name = "payloadType"]; * @return This builder for chaining. */ public Builder clearPayloadType() { bitField0_ = (bitField0_ & ~0x00000040); payloadType_ = 0; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadTransfer, pactus.TransactionOuterClass.PayloadTransfer.Builder, pactus.TransactionOuterClass.PayloadTransferOrBuilder> transferBuilder_; /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; * @return Whether the transfer field is set. */ @java.lang.Override public boolean hasTransfer() { return payloadCase_ == 30; } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; * @return The transfer. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadTransfer getTransfer() { if (transferBuilder_ == null) { if (payloadCase_ == 30) { return (pactus.TransactionOuterClass.PayloadTransfer) payload_; } return pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } else { if (payloadCase_ == 30) { return transferBuilder_.getMessage(); } return pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ public Builder setTransfer(pactus.TransactionOuterClass.PayloadTransfer value) { if (transferBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); } else { transferBuilder_.setMessage(value); } payloadCase_ = 30; return this; } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ public Builder setTransfer( pactus.TransactionOuterClass.PayloadTransfer.Builder builderForValue) { if (transferBuilder_ == null) { payload_ = builderForValue.build(); onChanged(); } else { transferBuilder_.setMessage(builderForValue.build()); } payloadCase_ = 30; return this; } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ public Builder mergeTransfer(pactus.TransactionOuterClass.PayloadTransfer value) { if (transferBuilder_ == null) { if (payloadCase_ == 30 && payload_ != pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance()) { payload_ = pactus.TransactionOuterClass.PayloadTransfer.newBuilder((pactus.TransactionOuterClass.PayloadTransfer) payload_) .mergeFrom(value).buildPartial(); } else { payload_ = value; } onChanged(); } else { if (payloadCase_ == 30) { transferBuilder_.mergeFrom(value); } else { transferBuilder_.setMessage(value); } } payloadCase_ = 30; return this; } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ public Builder clearTransfer() { if (transferBuilder_ == null) { if (payloadCase_ == 30) { payloadCase_ = 0; payload_ = null; onChanged(); } } else { if (payloadCase_ == 30) { payloadCase_ = 0; payload_ = null; } transferBuilder_.clear(); } return this; } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ public pactus.TransactionOuterClass.PayloadTransfer.Builder getTransferBuilder() { return internalGetTransferFieldBuilder().getBuilder(); } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadTransferOrBuilder getTransferOrBuilder() { if ((payloadCase_ == 30) && (transferBuilder_ != null)) { return transferBuilder_.getMessageOrBuilder(); } else { if (payloadCase_ == 30) { return (pactus.TransactionOuterClass.PayloadTransfer) payload_; } return pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } } /** *
       * Transfer transaction payload.
       * 
* * .pactus.PayloadTransfer transfer = 30 [json_name = "transfer"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadTransfer, pactus.TransactionOuterClass.PayloadTransfer.Builder, pactus.TransactionOuterClass.PayloadTransferOrBuilder> internalGetTransferFieldBuilder() { if (transferBuilder_ == null) { if (!(payloadCase_ == 30)) { payload_ = pactus.TransactionOuterClass.PayloadTransfer.getDefaultInstance(); } transferBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadTransfer, pactus.TransactionOuterClass.PayloadTransfer.Builder, pactus.TransactionOuterClass.PayloadTransferOrBuilder>( (pactus.TransactionOuterClass.PayloadTransfer) payload_, getParentForChildren(), isClean()); payload_ = null; } payloadCase_ = 30; onChanged(); return transferBuilder_; } private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadBond, pactus.TransactionOuterClass.PayloadBond.Builder, pactus.TransactionOuterClass.PayloadBondOrBuilder> bondBuilder_; /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; * @return Whether the bond field is set. */ @java.lang.Override public boolean hasBond() { return payloadCase_ == 31; } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; * @return The bond. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBond getBond() { if (bondBuilder_ == null) { if (payloadCase_ == 31) { return (pactus.TransactionOuterClass.PayloadBond) payload_; } return pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } else { if (payloadCase_ == 31) { return bondBuilder_.getMessage(); } return pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ public Builder setBond(pactus.TransactionOuterClass.PayloadBond value) { if (bondBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); } else { bondBuilder_.setMessage(value); } payloadCase_ = 31; return this; } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ public Builder setBond( pactus.TransactionOuterClass.PayloadBond.Builder builderForValue) { if (bondBuilder_ == null) { payload_ = builderForValue.build(); onChanged(); } else { bondBuilder_.setMessage(builderForValue.build()); } payloadCase_ = 31; return this; } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ public Builder mergeBond(pactus.TransactionOuterClass.PayloadBond value) { if (bondBuilder_ == null) { if (payloadCase_ == 31 && payload_ != pactus.TransactionOuterClass.PayloadBond.getDefaultInstance()) { payload_ = pactus.TransactionOuterClass.PayloadBond.newBuilder((pactus.TransactionOuterClass.PayloadBond) payload_) .mergeFrom(value).buildPartial(); } else { payload_ = value; } onChanged(); } else { if (payloadCase_ == 31) { bondBuilder_.mergeFrom(value); } else { bondBuilder_.setMessage(value); } } payloadCase_ = 31; return this; } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ public Builder clearBond() { if (bondBuilder_ == null) { if (payloadCase_ == 31) { payloadCase_ = 0; payload_ = null; onChanged(); } } else { if (payloadCase_ == 31) { payloadCase_ = 0; payload_ = null; } bondBuilder_.clear(); } return this; } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ public pactus.TransactionOuterClass.PayloadBond.Builder getBondBuilder() { return internalGetBondFieldBuilder().getBuilder(); } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBondOrBuilder getBondOrBuilder() { if ((payloadCase_ == 31) && (bondBuilder_ != null)) { return bondBuilder_.getMessageOrBuilder(); } else { if (payloadCase_ == 31) { return (pactus.TransactionOuterClass.PayloadBond) payload_; } return pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } } /** *
       * Bond transaction payload.
       * 
* * .pactus.PayloadBond bond = 31 [json_name = "bond"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadBond, pactus.TransactionOuterClass.PayloadBond.Builder, pactus.TransactionOuterClass.PayloadBondOrBuilder> internalGetBondFieldBuilder() { if (bondBuilder_ == null) { if (!(payloadCase_ == 31)) { payload_ = pactus.TransactionOuterClass.PayloadBond.getDefaultInstance(); } bondBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadBond, pactus.TransactionOuterClass.PayloadBond.Builder, pactus.TransactionOuterClass.PayloadBondOrBuilder>( (pactus.TransactionOuterClass.PayloadBond) payload_, getParentForChildren(), isClean()); payload_ = null; } payloadCase_ = 31; onChanged(); return bondBuilder_; } private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadSortition, pactus.TransactionOuterClass.PayloadSortition.Builder, pactus.TransactionOuterClass.PayloadSortitionOrBuilder> sortitionBuilder_; /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; * @return Whether the sortition field is set. */ @java.lang.Override public boolean hasSortition() { return payloadCase_ == 32; } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; * @return The sortition. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadSortition getSortition() { if (sortitionBuilder_ == null) { if (payloadCase_ == 32) { return (pactus.TransactionOuterClass.PayloadSortition) payload_; } return pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } else { if (payloadCase_ == 32) { return sortitionBuilder_.getMessage(); } return pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ public Builder setSortition(pactus.TransactionOuterClass.PayloadSortition value) { if (sortitionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); } else { sortitionBuilder_.setMessage(value); } payloadCase_ = 32; return this; } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ public Builder setSortition( pactus.TransactionOuterClass.PayloadSortition.Builder builderForValue) { if (sortitionBuilder_ == null) { payload_ = builderForValue.build(); onChanged(); } else { sortitionBuilder_.setMessage(builderForValue.build()); } payloadCase_ = 32; return this; } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ public Builder mergeSortition(pactus.TransactionOuterClass.PayloadSortition value) { if (sortitionBuilder_ == null) { if (payloadCase_ == 32 && payload_ != pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance()) { payload_ = pactus.TransactionOuterClass.PayloadSortition.newBuilder((pactus.TransactionOuterClass.PayloadSortition) payload_) .mergeFrom(value).buildPartial(); } else { payload_ = value; } onChanged(); } else { if (payloadCase_ == 32) { sortitionBuilder_.mergeFrom(value); } else { sortitionBuilder_.setMessage(value); } } payloadCase_ = 32; return this; } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ public Builder clearSortition() { if (sortitionBuilder_ == null) { if (payloadCase_ == 32) { payloadCase_ = 0; payload_ = null; onChanged(); } } else { if (payloadCase_ == 32) { payloadCase_ = 0; payload_ = null; } sortitionBuilder_.clear(); } return this; } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ public pactus.TransactionOuterClass.PayloadSortition.Builder getSortitionBuilder() { return internalGetSortitionFieldBuilder().getBuilder(); } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadSortitionOrBuilder getSortitionOrBuilder() { if ((payloadCase_ == 32) && (sortitionBuilder_ != null)) { return sortitionBuilder_.getMessageOrBuilder(); } else { if (payloadCase_ == 32) { return (pactus.TransactionOuterClass.PayloadSortition) payload_; } return pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } } /** *
       * Sortition transaction payload.
       * 
* * .pactus.PayloadSortition sortition = 32 [json_name = "sortition"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadSortition, pactus.TransactionOuterClass.PayloadSortition.Builder, pactus.TransactionOuterClass.PayloadSortitionOrBuilder> internalGetSortitionFieldBuilder() { if (sortitionBuilder_ == null) { if (!(payloadCase_ == 32)) { payload_ = pactus.TransactionOuterClass.PayloadSortition.getDefaultInstance(); } sortitionBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadSortition, pactus.TransactionOuterClass.PayloadSortition.Builder, pactus.TransactionOuterClass.PayloadSortitionOrBuilder>( (pactus.TransactionOuterClass.PayloadSortition) payload_, getParentForChildren(), isClean()); payload_ = null; } payloadCase_ = 32; onChanged(); return sortitionBuilder_; } private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadUnbond, pactus.TransactionOuterClass.PayloadUnbond.Builder, pactus.TransactionOuterClass.PayloadUnbondOrBuilder> unbondBuilder_; /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; * @return Whether the unbond field is set. */ @java.lang.Override public boolean hasUnbond() { return payloadCase_ == 33; } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; * @return The unbond. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbond getUnbond() { if (unbondBuilder_ == null) { if (payloadCase_ == 33) { return (pactus.TransactionOuterClass.PayloadUnbond) payload_; } return pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } else { if (payloadCase_ == 33) { return unbondBuilder_.getMessage(); } return pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ public Builder setUnbond(pactus.TransactionOuterClass.PayloadUnbond value) { if (unbondBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); } else { unbondBuilder_.setMessage(value); } payloadCase_ = 33; return this; } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ public Builder setUnbond( pactus.TransactionOuterClass.PayloadUnbond.Builder builderForValue) { if (unbondBuilder_ == null) { payload_ = builderForValue.build(); onChanged(); } else { unbondBuilder_.setMessage(builderForValue.build()); } payloadCase_ = 33; return this; } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ public Builder mergeUnbond(pactus.TransactionOuterClass.PayloadUnbond value) { if (unbondBuilder_ == null) { if (payloadCase_ == 33 && payload_ != pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance()) { payload_ = pactus.TransactionOuterClass.PayloadUnbond.newBuilder((pactus.TransactionOuterClass.PayloadUnbond) payload_) .mergeFrom(value).buildPartial(); } else { payload_ = value; } onChanged(); } else { if (payloadCase_ == 33) { unbondBuilder_.mergeFrom(value); } else { unbondBuilder_.setMessage(value); } } payloadCase_ = 33; return this; } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ public Builder clearUnbond() { if (unbondBuilder_ == null) { if (payloadCase_ == 33) { payloadCase_ = 0; payload_ = null; onChanged(); } } else { if (payloadCase_ == 33) { payloadCase_ = 0; payload_ = null; } unbondBuilder_.clear(); } return this; } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ public pactus.TransactionOuterClass.PayloadUnbond.Builder getUnbondBuilder() { return internalGetUnbondFieldBuilder().getBuilder(); } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadUnbondOrBuilder getUnbondOrBuilder() { if ((payloadCase_ == 33) && (unbondBuilder_ != null)) { return unbondBuilder_.getMessageOrBuilder(); } else { if (payloadCase_ == 33) { return (pactus.TransactionOuterClass.PayloadUnbond) payload_; } return pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } } /** *
       * Unbond transaction payload.
       * 
* * .pactus.PayloadUnbond unbond = 33 [json_name = "unbond"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadUnbond, pactus.TransactionOuterClass.PayloadUnbond.Builder, pactus.TransactionOuterClass.PayloadUnbondOrBuilder> internalGetUnbondFieldBuilder() { if (unbondBuilder_ == null) { if (!(payloadCase_ == 33)) { payload_ = pactus.TransactionOuterClass.PayloadUnbond.getDefaultInstance(); } unbondBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadUnbond, pactus.TransactionOuterClass.PayloadUnbond.Builder, pactus.TransactionOuterClass.PayloadUnbondOrBuilder>( (pactus.TransactionOuterClass.PayloadUnbond) payload_, getParentForChildren(), isClean()); payload_ = null; } payloadCase_ = 33; onChanged(); return unbondBuilder_; } private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadWithdraw, pactus.TransactionOuterClass.PayloadWithdraw.Builder, pactus.TransactionOuterClass.PayloadWithdrawOrBuilder> withdrawBuilder_; /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; * @return Whether the withdraw field is set. */ @java.lang.Override public boolean hasWithdraw() { return payloadCase_ == 34; } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; * @return The withdraw. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdraw getWithdraw() { if (withdrawBuilder_ == null) { if (payloadCase_ == 34) { return (pactus.TransactionOuterClass.PayloadWithdraw) payload_; } return pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } else { if (payloadCase_ == 34) { return withdrawBuilder_.getMessage(); } return pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ public Builder setWithdraw(pactus.TransactionOuterClass.PayloadWithdraw value) { if (withdrawBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); } else { withdrawBuilder_.setMessage(value); } payloadCase_ = 34; return this; } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ public Builder setWithdraw( pactus.TransactionOuterClass.PayloadWithdraw.Builder builderForValue) { if (withdrawBuilder_ == null) { payload_ = builderForValue.build(); onChanged(); } else { withdrawBuilder_.setMessage(builderForValue.build()); } payloadCase_ = 34; return this; } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ public Builder mergeWithdraw(pactus.TransactionOuterClass.PayloadWithdraw value) { if (withdrawBuilder_ == null) { if (payloadCase_ == 34 && payload_ != pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance()) { payload_ = pactus.TransactionOuterClass.PayloadWithdraw.newBuilder((pactus.TransactionOuterClass.PayloadWithdraw) payload_) .mergeFrom(value).buildPartial(); } else { payload_ = value; } onChanged(); } else { if (payloadCase_ == 34) { withdrawBuilder_.mergeFrom(value); } else { withdrawBuilder_.setMessage(value); } } payloadCase_ = 34; return this; } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ public Builder clearWithdraw() { if (withdrawBuilder_ == null) { if (payloadCase_ == 34) { payloadCase_ = 0; payload_ = null; onChanged(); } } else { if (payloadCase_ == 34) { payloadCase_ = 0; payload_ = null; } withdrawBuilder_.clear(); } return this; } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ public pactus.TransactionOuterClass.PayloadWithdraw.Builder getWithdrawBuilder() { return internalGetWithdrawFieldBuilder().getBuilder(); } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadWithdrawOrBuilder getWithdrawOrBuilder() { if ((payloadCase_ == 34) && (withdrawBuilder_ != null)) { return withdrawBuilder_.getMessageOrBuilder(); } else { if (payloadCase_ == 34) { return (pactus.TransactionOuterClass.PayloadWithdraw) payload_; } return pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } } /** *
       * Withdraw transaction payload.
       * 
* * .pactus.PayloadWithdraw withdraw = 34 [json_name = "withdraw"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadWithdraw, pactus.TransactionOuterClass.PayloadWithdraw.Builder, pactus.TransactionOuterClass.PayloadWithdrawOrBuilder> internalGetWithdrawFieldBuilder() { if (withdrawBuilder_ == null) { if (!(payloadCase_ == 34)) { payload_ = pactus.TransactionOuterClass.PayloadWithdraw.getDefaultInstance(); } withdrawBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadWithdraw, pactus.TransactionOuterClass.PayloadWithdraw.Builder, pactus.TransactionOuterClass.PayloadWithdrawOrBuilder>( (pactus.TransactionOuterClass.PayloadWithdraw) payload_, getParentForChildren(), isClean()); payload_ = null; } payloadCase_ = 34; onChanged(); return withdrawBuilder_; } private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadBatchTransfer, pactus.TransactionOuterClass.PayloadBatchTransfer.Builder, pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder> batchTransferBuilder_; /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; * @return Whether the batchTransfer field is set. */ @java.lang.Override public boolean hasBatchTransfer() { return payloadCase_ == 35; } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; * @return The batchTransfer. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransfer getBatchTransfer() { if (batchTransferBuilder_ == null) { if (payloadCase_ == 35) { return (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_; } return pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } else { if (payloadCase_ == 35) { return batchTransferBuilder_.getMessage(); } return pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ public Builder setBatchTransfer(pactus.TransactionOuterClass.PayloadBatchTransfer value) { if (batchTransferBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); } else { batchTransferBuilder_.setMessage(value); } payloadCase_ = 35; return this; } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ public Builder setBatchTransfer( pactus.TransactionOuterClass.PayloadBatchTransfer.Builder builderForValue) { if (batchTransferBuilder_ == null) { payload_ = builderForValue.build(); onChanged(); } else { batchTransferBuilder_.setMessage(builderForValue.build()); } payloadCase_ = 35; return this; } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ public Builder mergeBatchTransfer(pactus.TransactionOuterClass.PayloadBatchTransfer value) { if (batchTransferBuilder_ == null) { if (payloadCase_ == 35 && payload_ != pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance()) { payload_ = pactus.TransactionOuterClass.PayloadBatchTransfer.newBuilder((pactus.TransactionOuterClass.PayloadBatchTransfer) payload_) .mergeFrom(value).buildPartial(); } else { payload_ = value; } onChanged(); } else { if (payloadCase_ == 35) { batchTransferBuilder_.mergeFrom(value); } else { batchTransferBuilder_.setMessage(value); } } payloadCase_ = 35; return this; } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ public Builder clearBatchTransfer() { if (batchTransferBuilder_ == null) { if (payloadCase_ == 35) { payloadCase_ = 0; payload_ = null; onChanged(); } } else { if (payloadCase_ == 35) { payloadCase_ = 0; payload_ = null; } batchTransferBuilder_.clear(); } return this; } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ public pactus.TransactionOuterClass.PayloadBatchTransfer.Builder getBatchTransferBuilder() { return internalGetBatchTransferFieldBuilder().getBuilder(); } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ @java.lang.Override public pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder getBatchTransferOrBuilder() { if ((payloadCase_ == 35) && (batchTransferBuilder_ != null)) { return batchTransferBuilder_.getMessageOrBuilder(); } else { if (payloadCase_ == 35) { return (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_; } return pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } } /** *
       * Batch Transfer transaction payload.
       * 
* * .pactus.PayloadBatchTransfer batch_transfer = 35 [json_name = "batchTransfer"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadBatchTransfer, pactus.TransactionOuterClass.PayloadBatchTransfer.Builder, pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder> internalGetBatchTransferFieldBuilder() { if (batchTransferBuilder_ == null) { if (!(payloadCase_ == 35)) { payload_ = pactus.TransactionOuterClass.PayloadBatchTransfer.getDefaultInstance(); } batchTransferBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.PayloadBatchTransfer, pactus.TransactionOuterClass.PayloadBatchTransfer.Builder, pactus.TransactionOuterClass.PayloadBatchTransferOrBuilder>( (pactus.TransactionOuterClass.PayloadBatchTransfer) payload_, getParentForChildren(), isClean()); payload_ = null; } payloadCase_ = 35; onChanged(); return batchTransferBuilder_; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00002000); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00002000; onChanged(); return this; } private java.lang.Object publicKey_ = ""; /** *
       * The public key associated with the transaction.
       * 
* * string public_key = 9 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key associated with the transaction.
       * 
* * string public_key = 9 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key associated with the transaction.
       * 
* * string public_key = 9 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00004000; onChanged(); return this; } /** *
       * The public key associated with the transaction.
       * 
* * string public_key = 9 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00004000); onChanged(); return this; } /** *
       * The public key associated with the transaction.
       * 
* * string public_key = 9 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00004000; onChanged(); return this; } private java.lang.Object signature_ = ""; /** *
       * The signature for the transaction.
       * 
* * string signature = 10 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signature for the transaction.
       * 
* * string signature = 10 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signature for the transaction.
       * 
* * string signature = 10 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00008000; onChanged(); return this; } /** *
       * The signature for the transaction.
       * 
* * string signature = 10 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00008000); onChanged(); return this; } /** *
       * The signature for the transaction.
       * 
* * string signature = 10 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00008000; onChanged(); return this; } private int blockHeight_ ; /** *
       * The block height containing the transaction.
       * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
       * 
* * uint32 block_height = 11 [json_name = "blockHeight"]; * @return The blockHeight. */ @java.lang.Override public int getBlockHeight() { return blockHeight_; } /** *
       * The block height containing the transaction.
       * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
       * 
* * uint32 block_height = 11 [json_name = "blockHeight"]; * @param value The blockHeight to set. * @return This builder for chaining. */ public Builder setBlockHeight(int value) { blockHeight_ = value; bitField0_ |= 0x00010000; onChanged(); return this; } /** *
       * The block height containing the transaction.
       * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
       * 
* * uint32 block_height = 11 [json_name = "blockHeight"]; * @return This builder for chaining. */ public Builder clearBlockHeight() { bitField0_ = (bitField0_ & ~0x00010000); blockHeight_ = 0; onChanged(); return this; } private boolean confirmed_ ; /** *
       * Indicates whether the transaction is confirmed.
       * 
* * bool confirmed = 12 [json_name = "confirmed"]; * @return The confirmed. */ @java.lang.Override public boolean getConfirmed() { return confirmed_; } /** *
       * Indicates whether the transaction is confirmed.
       * 
* * bool confirmed = 12 [json_name = "confirmed"]; * @param value The confirmed to set. * @return This builder for chaining. */ public Builder setConfirmed(boolean value) { confirmed_ = value; bitField0_ |= 0x00020000; onChanged(); return this; } /** *
       * Indicates whether the transaction is confirmed.
       * 
* * bool confirmed = 12 [json_name = "confirmed"]; * @return This builder for chaining. */ public Builder clearConfirmed() { bitField0_ = (bitField0_ & ~0x00020000); confirmed_ = false; onChanged(); return this; } private int confirmations_ ; /** *
       * The number of blocks that have been added to the chain after this transaction was included in a block.
       * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
       * 
* * int32 confirmations = 13 [json_name = "confirmations"]; * @return The confirmations. */ @java.lang.Override public int getConfirmations() { return confirmations_; } /** *
       * The number of blocks that have been added to the chain after this transaction was included in a block.
       * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
       * 
* * int32 confirmations = 13 [json_name = "confirmations"]; * @param value The confirmations to set. * @return This builder for chaining. */ public Builder setConfirmations(int value) { confirmations_ = value; bitField0_ |= 0x00040000; onChanged(); return this; } /** *
       * The number of blocks that have been added to the chain after this transaction was included in a block.
       * A value of zero means the transaction is unconfirmed and may still in the transaction pool.
       * 
* * int32 confirmations = 13 [json_name = "confirmations"]; * @return This builder for chaining. */ public Builder clearConfirmations() { bitField0_ = (bitField0_ & ~0x00040000); confirmations_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.TransactionInfo) } // @@protoc_insertion_point(class_scope:pactus.TransactionInfo) private static final pactus.TransactionOuterClass.TransactionInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.TransactionInfo(); } public static pactus.TransactionOuterClass.TransactionInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TransactionInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface DecodeRawTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.DecodeRawTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ java.lang.String getRawTransaction(); /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ com.google.protobuf.ByteString getRawTransactionBytes(); } /** *
   * Request message for decoding a raw transaction.
   * 
* * Protobuf type {@code pactus.DecodeRawTransactionRequest} */ public static final class DecodeRawTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.DecodeRawTransactionRequest) DecodeRawTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "DecodeRawTransactionRequest"); } // Use DecodeRawTransactionRequest.newBuilder() to construct. private DecodeRawTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private DecodeRawTransactionRequest() { rawTransaction_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.DecodeRawTransactionRequest.class, pactus.TransactionOuterClass.DecodeRawTransactionRequest.Builder.class); } public static final int RAW_TRANSACTION_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object rawTransaction_ = ""; /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ @java.lang.Override public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } } /** *
     * The raw transaction data in hexadecimal format.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, rawTransaction_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, rawTransaction_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.DecodeRawTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.DecodeRawTransactionRequest other = (pactus.TransactionOuterClass.DecodeRawTransactionRequest) obj; if (!getRawTransaction() .equals(other.getRawTransaction())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RAW_TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getRawTransaction().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.DecodeRawTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for decoding a raw transaction.
     * 
* * Protobuf type {@code pactus.DecodeRawTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.DecodeRawTransactionRequest) pactus.TransactionOuterClass.DecodeRawTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.DecodeRawTransactionRequest.class, pactus.TransactionOuterClass.DecodeRawTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.DecodeRawTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; rawTransaction_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.DecodeRawTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionRequest build() { pactus.TransactionOuterClass.DecodeRawTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionRequest buildPartial() { pactus.TransactionOuterClass.DecodeRawTransactionRequest result = new pactus.TransactionOuterClass.DecodeRawTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.DecodeRawTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.rawTransaction_ = rawTransaction_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.DecodeRawTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.DecodeRawTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.DecodeRawTransactionRequest other) { if (other == pactus.TransactionOuterClass.DecodeRawTransactionRequest.getDefaultInstance()) return this; if (!other.getRawTransaction().isEmpty()) { rawTransaction_ = other.rawTransaction_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { rawTransaction_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object rawTransaction_ = ""; /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @param value The rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransaction( java.lang.String value) { if (value == null) { throw new NullPointerException(); } rawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return This builder for chaining. */ public Builder clearRawTransaction() { rawTransaction_ = getDefaultInstance().getRawTransaction(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The raw transaction data in hexadecimal format.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @param value The bytes for rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransactionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); rawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.DecodeRawTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.DecodeRawTransactionRequest) private static final pactus.TransactionOuterClass.DecodeRawTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.DecodeRawTransactionRequest(); } public static pactus.TransactionOuterClass.DecodeRawTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public DecodeRawTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface DecodeRawTransactionResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.DecodeRawTransactionResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The decoded transaction information.
     * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; * @return Whether the transaction field is set. */ boolean hasTransaction(); /** *
     * The decoded transaction information.
     * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; * @return The transaction. */ pactus.TransactionOuterClass.TransactionInfo getTransaction(); /** *
     * The decoded transaction information.
     * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ pactus.TransactionOuterClass.TransactionInfoOrBuilder getTransactionOrBuilder(); } /** *
   * Response message contains the decoded transaction.
   * 
* * Protobuf type {@code pactus.DecodeRawTransactionResponse} */ public static final class DecodeRawTransactionResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.DecodeRawTransactionResponse) DecodeRawTransactionResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "DecodeRawTransactionResponse"); } // Use DecodeRawTransactionResponse.newBuilder() to construct. private DecodeRawTransactionResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private DecodeRawTransactionResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.DecodeRawTransactionResponse.class, pactus.TransactionOuterClass.DecodeRawTransactionResponse.Builder.class); } private int bitField0_; public static final int TRANSACTION_FIELD_NUMBER = 1; private pactus.TransactionOuterClass.TransactionInfo transaction_; /** *
     * The decoded transaction information.
     * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; * @return Whether the transaction field is set. */ @java.lang.Override public boolean hasTransaction() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * The decoded transaction information.
     * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; * @return The transaction. */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfo getTransaction() { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } /** *
     * The decoded transaction information.
     * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ @java.lang.Override public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTransactionOrBuilder() { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getTransaction()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getTransaction()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.DecodeRawTransactionResponse)) { return super.equals(obj); } pactus.TransactionOuterClass.DecodeRawTransactionResponse other = (pactus.TransactionOuterClass.DecodeRawTransactionResponse) obj; if (hasTransaction() != other.hasTransaction()) return false; if (hasTransaction()) { if (!getTransaction() .equals(other.getTransaction())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasTransaction()) { hash = (37 * hash) + TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getTransaction().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.DecodeRawTransactionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the decoded transaction.
     * 
* * Protobuf type {@code pactus.DecodeRawTransactionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.DecodeRawTransactionResponse) pactus.TransactionOuterClass.DecodeRawTransactionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.DecodeRawTransactionResponse.class, pactus.TransactionOuterClass.DecodeRawTransactionResponse.Builder.class); } // Construct using pactus.TransactionOuterClass.DecodeRawTransactionResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetTransactionFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; transaction_ = null; if (transactionBuilder_ != null) { transactionBuilder_.dispose(); transactionBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_DecodeRawTransactionResponse_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionResponse getDefaultInstanceForType() { return pactus.TransactionOuterClass.DecodeRawTransactionResponse.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionResponse build() { pactus.TransactionOuterClass.DecodeRawTransactionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionResponse buildPartial() { pactus.TransactionOuterClass.DecodeRawTransactionResponse result = new pactus.TransactionOuterClass.DecodeRawTransactionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.DecodeRawTransactionResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.transaction_ = transactionBuilder_ == null ? transaction_ : transactionBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.DecodeRawTransactionResponse) { return mergeFrom((pactus.TransactionOuterClass.DecodeRawTransactionResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.DecodeRawTransactionResponse other) { if (other == pactus.TransactionOuterClass.DecodeRawTransactionResponse.getDefaultInstance()) return this; if (other.hasTransaction()) { mergeTransaction(other.getTransaction()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( internalGetTransactionFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private pactus.TransactionOuterClass.TransactionInfo transaction_; private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> transactionBuilder_; /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; * @return Whether the transaction field is set. */ public boolean hasTransaction() { return ((bitField0_ & 0x00000001) != 0); } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; * @return The transaction. */ public pactus.TransactionOuterClass.TransactionInfo getTransaction() { if (transactionBuilder_ == null) { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } else { return transactionBuilder_.getMessage(); } } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ public Builder setTransaction(pactus.TransactionOuterClass.TransactionInfo value) { if (transactionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } transaction_ = value; } else { transactionBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ public Builder setTransaction( pactus.TransactionOuterClass.TransactionInfo.Builder builderForValue) { if (transactionBuilder_ == null) { transaction_ = builderForValue.build(); } else { transactionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ public Builder mergeTransaction(pactus.TransactionOuterClass.TransactionInfo value) { if (transactionBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && transaction_ != null && transaction_ != pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance()) { getTransactionBuilder().mergeFrom(value); } else { transaction_ = value; } } else { transactionBuilder_.mergeFrom(value); } if (transaction_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ public Builder clearTransaction() { bitField0_ = (bitField0_ & ~0x00000001); transaction_ = null; if (transactionBuilder_ != null) { transactionBuilder_.dispose(); transactionBuilder_ = null; } onChanged(); return this; } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ public pactus.TransactionOuterClass.TransactionInfo.Builder getTransactionBuilder() { bitField0_ |= 0x00000001; onChanged(); return internalGetTransactionFieldBuilder().getBuilder(); } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ public pactus.TransactionOuterClass.TransactionInfoOrBuilder getTransactionOrBuilder() { if (transactionBuilder_ != null) { return transactionBuilder_.getMessageOrBuilder(); } else { return transaction_ == null ? pactus.TransactionOuterClass.TransactionInfo.getDefaultInstance() : transaction_; } } /** *
       * The decoded transaction information.
       * 
* * .pactus.TransactionInfo transaction = 1 [json_name = "transaction"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder> internalGetTransactionFieldBuilder() { if (transactionBuilder_ == null) { transactionBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.TransactionOuterClass.TransactionInfo, pactus.TransactionOuterClass.TransactionInfo.Builder, pactus.TransactionOuterClass.TransactionInfoOrBuilder>( getTransaction(), getParentForChildren(), isClean()); transaction_ = null; } return transactionBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.DecodeRawTransactionResponse) } // @@protoc_insertion_point(class_scope:pactus.DecodeRawTransactionResponse) private static final pactus.TransactionOuterClass.DecodeRawTransactionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.DecodeRawTransactionResponse(); } public static pactus.TransactionOuterClass.DecodeRawTransactionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public DecodeRawTransactionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.DecodeRawTransactionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CheckTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CheckTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The raw transaction data to be checked.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ java.lang.String getRawTransaction(); /** *
     * The raw transaction data to be checked.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ com.google.protobuf.ByteString getRawTransactionBytes(); } /** *
   * Request message for checking a transaction.
   * 
* * Protobuf type {@code pactus.CheckTransactionRequest} */ public static final class CheckTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CheckTransactionRequest) CheckTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CheckTransactionRequest"); } // Use CheckTransactionRequest.newBuilder() to construct. private CheckTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CheckTransactionRequest() { rawTransaction_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CheckTransactionRequest.class, pactus.TransactionOuterClass.CheckTransactionRequest.Builder.class); } public static final int RAW_TRANSACTION_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object rawTransaction_ = ""; /** *
     * The raw transaction data to be checked.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ @java.lang.Override public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } } /** *
     * The raw transaction data to be checked.
     * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, rawTransaction_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, rawTransaction_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.CheckTransactionRequest)) { return super.equals(obj); } pactus.TransactionOuterClass.CheckTransactionRequest other = (pactus.TransactionOuterClass.CheckTransactionRequest) obj; if (!getRawTransaction() .equals(other.getRawTransaction())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RAW_TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getRawTransaction().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CheckTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.CheckTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for checking a transaction.
     * 
* * Protobuf type {@code pactus.CheckTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CheckTransactionRequest) pactus.TransactionOuterClass.CheckTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CheckTransactionRequest.class, pactus.TransactionOuterClass.CheckTransactionRequest.Builder.class); } // Construct using pactus.TransactionOuterClass.CheckTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; rawTransaction_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionRequest_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionRequest getDefaultInstanceForType() { return pactus.TransactionOuterClass.CheckTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionRequest build() { pactus.TransactionOuterClass.CheckTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionRequest buildPartial() { pactus.TransactionOuterClass.CheckTransactionRequest result = new pactus.TransactionOuterClass.CheckTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.CheckTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.rawTransaction_ = rawTransaction_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.CheckTransactionRequest) { return mergeFrom((pactus.TransactionOuterClass.CheckTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.CheckTransactionRequest other) { if (other == pactus.TransactionOuterClass.CheckTransactionRequest.getDefaultInstance()) return this; if (!other.getRawTransaction().isEmpty()) { rawTransaction_ = other.rawTransaction_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { rawTransaction_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object rawTransaction_ = ""; /** *
       * The raw transaction data to be checked.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The rawTransaction. */ public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The raw transaction data to be checked.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The raw transaction data to be checked.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @param value The rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransaction( java.lang.String value) { if (value == null) { throw new NullPointerException(); } rawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The raw transaction data to be checked.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @return This builder for chaining. */ public Builder clearRawTransaction() { rawTransaction_ = getDefaultInstance().getRawTransaction(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The raw transaction data to be checked.
       * 
* * string raw_transaction = 1 [json_name = "rawTransaction"]; * @param value The bytes for rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransactionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); rawTransaction_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CheckTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.CheckTransactionRequest) private static final pactus.TransactionOuterClass.CheckTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.CheckTransactionRequest(); } public static pactus.TransactionOuterClass.CheckTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CheckTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CheckTransactionResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CheckTransactionResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Indicates whether the transaction is valid.
     * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return The isValid. */ boolean getIsValid(); /** *
     * An error message if the transaction is invalid.
     * Empty if the transaction is valid.
     * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return The errorMessage. */ java.lang.String getErrorMessage(); /** *
     * An error message if the transaction is invalid.
     * Empty if the transaction is valid.
     * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return The bytes for errorMessage. */ com.google.protobuf.ByteString getErrorMessageBytes(); } /** *
   * Response message contains the result of the transaction check.
   * 
* * Protobuf type {@code pactus.CheckTransactionResponse} */ public static final class CheckTransactionResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CheckTransactionResponse) CheckTransactionResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CheckTransactionResponse"); } // Use CheckTransactionResponse.newBuilder() to construct. private CheckTransactionResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CheckTransactionResponse() { errorMessage_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CheckTransactionResponse.class, pactus.TransactionOuterClass.CheckTransactionResponse.Builder.class); } public static final int IS_VALID_FIELD_NUMBER = 1; private boolean isValid_ = false; /** *
     * Indicates whether the transaction is valid.
     * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return The isValid. */ @java.lang.Override public boolean getIsValid() { return isValid_; } public static final int ERROR_MESSAGE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object errorMessage_ = ""; /** *
     * An error message if the transaction is invalid.
     * Empty if the transaction is valid.
     * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return The errorMessage. */ @java.lang.Override public java.lang.String getErrorMessage() { java.lang.Object ref = errorMessage_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); errorMessage_ = s; return s; } } /** *
     * An error message if the transaction is invalid.
     * Empty if the transaction is valid.
     * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return The bytes for errorMessage. */ @java.lang.Override public com.google.protobuf.ByteString getErrorMessageBytes() { java.lang.Object ref = errorMessage_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); errorMessage_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (isValid_ != false) { output.writeBool(1, isValid_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(errorMessage_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, errorMessage_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (isValid_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, isValid_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(errorMessage_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, errorMessage_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.TransactionOuterClass.CheckTransactionResponse)) { return super.equals(obj); } pactus.TransactionOuterClass.CheckTransactionResponse other = (pactus.TransactionOuterClass.CheckTransactionResponse) obj; if (getIsValid() != other.getIsValid()) return false; if (!getErrorMessage() .equals(other.getErrorMessage())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + IS_VALID_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsValid()); hash = (37 * hash) + ERROR_MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getErrorMessage().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.TransactionOuterClass.CheckTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.TransactionOuterClass.CheckTransactionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the result of the transaction check.
     * 
* * Protobuf type {@code pactus.CheckTransactionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CheckTransactionResponse) pactus.TransactionOuterClass.CheckTransactionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.TransactionOuterClass.CheckTransactionResponse.class, pactus.TransactionOuterClass.CheckTransactionResponse.Builder.class); } // Construct using pactus.TransactionOuterClass.CheckTransactionResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; isValid_ = false; errorMessage_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.TransactionOuterClass.internal_static_pactus_CheckTransactionResponse_descriptor; } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionResponse getDefaultInstanceForType() { return pactus.TransactionOuterClass.CheckTransactionResponse.getDefaultInstance(); } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionResponse build() { pactus.TransactionOuterClass.CheckTransactionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionResponse buildPartial() { pactus.TransactionOuterClass.CheckTransactionResponse result = new pactus.TransactionOuterClass.CheckTransactionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.TransactionOuterClass.CheckTransactionResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.isValid_ = isValid_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.errorMessage_ = errorMessage_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.TransactionOuterClass.CheckTransactionResponse) { return mergeFrom((pactus.TransactionOuterClass.CheckTransactionResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.TransactionOuterClass.CheckTransactionResponse other) { if (other == pactus.TransactionOuterClass.CheckTransactionResponse.getDefaultInstance()) return this; if (other.getIsValid() != false) { setIsValid(other.getIsValid()); } if (!other.getErrorMessage().isEmpty()) { errorMessage_ = other.errorMessage_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { isValid_ = input.readBool(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { errorMessage_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private boolean isValid_ ; /** *
       * Indicates whether the transaction is valid.
       * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return The isValid. */ @java.lang.Override public boolean getIsValid() { return isValid_; } /** *
       * Indicates whether the transaction is valid.
       * 
* * bool is_valid = 1 [json_name = "isValid"]; * @param value The isValid to set. * @return This builder for chaining. */ public Builder setIsValid(boolean value) { isValid_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Indicates whether the transaction is valid.
       * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return This builder for chaining. */ public Builder clearIsValid() { bitField0_ = (bitField0_ & ~0x00000001); isValid_ = false; onChanged(); return this; } private java.lang.Object errorMessage_ = ""; /** *
       * An error message if the transaction is invalid.
       * Empty if the transaction is valid.
       * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return The errorMessage. */ public java.lang.String getErrorMessage() { java.lang.Object ref = errorMessage_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); errorMessage_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * An error message if the transaction is invalid.
       * Empty if the transaction is valid.
       * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return The bytes for errorMessage. */ public com.google.protobuf.ByteString getErrorMessageBytes() { java.lang.Object ref = errorMessage_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); errorMessage_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * An error message if the transaction is invalid.
       * Empty if the transaction is valid.
       * 
* * string error_message = 2 [json_name = "errorMessage"]; * @param value The errorMessage to set. * @return This builder for chaining. */ public Builder setErrorMessage( java.lang.String value) { if (value == null) { throw new NullPointerException(); } errorMessage_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * An error message if the transaction is invalid.
       * Empty if the transaction is valid.
       * 
* * string error_message = 2 [json_name = "errorMessage"]; * @return This builder for chaining. */ public Builder clearErrorMessage() { errorMessage_ = getDefaultInstance().getErrorMessage(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * An error message if the transaction is invalid.
       * Empty if the transaction is valid.
       * 
* * string error_message = 2 [json_name = "errorMessage"]; * @param value The bytes for errorMessage to set. * @return This builder for chaining. */ public Builder setErrorMessageBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); errorMessage_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CheckTransactionResponse) } // @@protoc_insertion_point(class_scope:pactus.CheckTransactionResponse) private static final pactus.TransactionOuterClass.CheckTransactionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.TransactionOuterClass.CheckTransactionResponse(); } public static pactus.TransactionOuterClass.CheckTransactionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CheckTransactionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.TransactionOuterClass.CheckTransactionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTransactionResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTransactionResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CalculateFeeRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CalculateFeeRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CalculateFeeResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CalculateFeeResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_BroadcastTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_BroadcastTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_BroadcastTransactionResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_BroadcastTransactionResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetRawTransferTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetRawTransferTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetRawBondTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetRawBondTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetRawUnbondTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetRawUnbondTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetRawWithdrawTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetRawWithdrawTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetRawBatchTransferTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetRawBatchTransferTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetRawTransactionResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetRawTransactionResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PayloadTransfer_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PayloadTransfer_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PayloadBond_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PayloadBond_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PayloadSortition_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PayloadSortition_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PayloadUnbond_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PayloadUnbond_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PayloadWithdraw_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PayloadWithdraw_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PayloadBatchTransfer_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PayloadBatchTransfer_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_Recipient_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_Recipient_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_TransactionInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_TransactionInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_DecodeRawTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_DecodeRawTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_DecodeRawTransactionResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_DecodeRawTransactionResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CheckTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CheckTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CheckTransactionResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CheckTransactionResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\021transaction.proto\022\006pactus\"c\n\025GetTransa" + "ctionRequest\022\016\n\002id\030\001 \001(\tR\002id\022:\n\tverbosit" + "y\030\002 \001(\0162\034.pactus.TransactionVerbosityR\tv" + "erbosity\"\225\001\n\026GetTransactionResponse\022!\n\014b" + "lock_height\030\001 \001(\rR\013blockHeight\022\035\n\nblock_" + "time\030\002 \001(\rR\tblockTime\0229\n\013transaction\030\003 \001" + "(\0132\027.pactus.TransactionInfoR\013transaction" + "\"\210\001\n\023CalculateFeeRequest\022\026\n\006amount\030\001 \001(\003" + "R\006amount\0226\n\014payload_type\030\002 \001(\0162\023.pactus." + "PayloadTypeR\013payloadType\022!\n\014fixed_amount" + "\030\003 \001(\010R\013fixedAmount\"@\n\024CalculateFeeRespo" + "nse\022\026\n\006amount\030\001 \001(\003R\006amount\022\020\n\003fee\030\002 \001(\003" + "R\003fee\"S\n\033BroadcastTransactionRequest\0224\n\026" + "signed_raw_transaction\030\001 \001(\tR\024signedRawT" + "ransaction\".\n\034BroadcastTransactionRespon" + "se\022\016\n\002id\030\001 \001(\tR\002id\"\261\001\n GetRawTransferTra" + "nsactionRequest\022\033\n\tlock_time\030\001 \001(\rR\010lock" + "Time\022\026\n\006sender\030\002 \001(\tR\006sender\022\032\n\010receiver" + "\030\003 \001(\tR\010receiver\022\026\n\006amount\030\004 \001(\003R\006amount" + "\022\020\n\003fee\030\005 \001(\003R\003fee\022\022\n\004memo\030\006 \001(\tR\004memo\"\301" + "\002\n\034GetRawBondTransactionRequest\022\033\n\tlock_" + "time\030\001 \001(\rR\010lockTime\022\026\n\006sender\030\002 \001(\tR\006se" + "nder\022\032\n\010receiver\030\003 \001(\tR\010receiver\022\024\n\005stak" + "e\030\004 \001(\003R\005stake\022\035\n\npublic_key\030\005 \001(\tR\tpubl" + "icKey\022\020\n\003fee\030\006 \001(\003R\003fee\022\022\n\004memo\030\007 \001(\tR\004m" + "emo\022%\n\016delegate_owner\030\010 \001(\tR\rdelegateOwn" + "er\022%\n\016delegate_share\030\t \001(\003R\rdelegateShar" + "e\022\'\n\017delegate_expiry\030\n \001(\rR\016delegateExpi" + "ry\"\245\001\n\036GetRawUnbondTransactionRequest\022\033\n" + "\tlock_time\030\001 \001(\rR\010lockTime\022+\n\021validator_" + "address\030\002 \001(\tR\020validatorAddress\022\022\n\004memo\030" + "\003 \001(\tR\004memo\022%\n\016delegate_owner\030\004 \001(\tR\rdel" + "egateOwner\"\323\001\n GetRawWithdrawTransaction" + "Request\022\033\n\tlock_time\030\001 \001(\rR\010lockTime\022+\n\021" + "validator_address\030\002 \001(\tR\020validatorAddres" + "s\022\'\n\017account_address\030\003 \001(\tR\016accountAddre" + "ss\022\026\n\006amount\030\004 \001(\003R\006amount\022\020\n\003fee\030\005 \001(\003R" + "\003fee\022\022\n\004memo\030\006 \001(\tR\004memo\"\265\001\n%GetRawBatch" + "TransferTransactionRequest\022\033\n\tlock_time\030" + "\001 \001(\rR\010lockTime\022\026\n\006sender\030\002 \001(\tR\006sender\022" + "1\n\nrecipients\030\003 \003(\0132\021.pactus.RecipientR\n" + "recipients\022\020\n\003fee\030\004 \001(\003R\003fee\022\022\n\004memo\030\005 \001" + "(\tR\004memo\"T\n\031GetRawTransactionResponse\022\'\n" + "\017raw_transaction\030\001 \001(\tR\016rawTransaction\022\016" + "\n\002id\030\002 \001(\tR\002id\"]\n\017PayloadTransfer\022\026\n\006sen" + "der\030\001 \001(\tR\006sender\022\032\n\010receiver\030\002 \001(\tR\010rec" + "eiver\022\026\n\006amount\030\003 \001(\003R\006amount\"\220\002\n\013Payloa" + "dBond\022\026\n\006sender\030\001 \001(\tR\006sender\022\032\n\010receive" + "r\030\002 \001(\tR\010receiver\022\024\n\005stake\030\003 \001(\003R\005stake\022" + "\035\n\npublic_key\030\004 \001(\tR\tpublicKey\022!\n\014is_del" + "egated\030\005 \001(\010R\013isDelegated\022%\n\016delegate_ow" + "ner\030\006 \001(\tR\rdelegateOwner\022%\n\016delegate_sha" + "re\030\007 \001(\003R\rdelegateShare\022\'\n\017delegate_expi" + "ry\030\010 \001(\rR\016delegateExpiry\"B\n\020PayloadSorti" + "tion\022\030\n\007address\030\001 \001(\tR\007address\022\024\n\005proof\030" + "\002 \001(\tR\005proof\"T\n\rPayloadUnbond\022\034\n\tvalidat" + "or\030\001 \001(\tR\tvalidator\022%\n\016delegate_owner\030\002 " + "\001(\tR\rdelegateOwner\"\177\n\017PayloadWithdraw\022+\n" + "\021validator_address\030\001 \001(\tR\020validatorAddre" + "ss\022\'\n\017account_address\030\002 \001(\tR\016accountAddr" + "ess\022\026\n\006amount\030\003 \001(\003R\006amount\"a\n\024PayloadBa" + "tchTransfer\022\026\n\006sender\030\001 \001(\tR\006sender\0221\n\nr" + "ecipients\030\002 \003(\0132\021.pactus.RecipientR\nreci" + "pients\"?\n\tRecipient\022\032\n\010receiver\030\001 \001(\tR\010r" + "eceiver\022\026\n\006amount\030\002 \001(\003R\006amount\"\332\005\n\017Tran" + "sactionInfo\022\016\n\002id\030\001 \001(\tR\002id\022\022\n\004data\030\002 \001(" + "\tR\004data\022\030\n\007version\030\003 \001(\005R\007version\022\033\n\tloc" + "k_time\030\004 \001(\rR\010lockTime\022\024\n\005value\030\005 \001(\003R\005v" + "alue\022\020\n\003fee\030\006 \001(\003R\003fee\0226\n\014payload_type\030\007" + " \001(\0162\023.pactus.PayloadTypeR\013payloadType\0225" + "\n\010transfer\030\036 \001(\0132\027.pactus.PayloadTransfe" + "rH\000R\010transfer\022)\n\004bond\030\037 \001(\0132\023.pactus.Pay" + "loadBondH\000R\004bond\0228\n\tsortition\030 \001(\0132\030.pa" + "ctus.PayloadSortitionH\000R\tsortition\022/\n\006un" + "bond\030! \001(\0132\025.pactus.PayloadUnbondH\000R\006unb" + "ond\0225\n\010withdraw\030\" \001(\0132\027.pactus.PayloadWi" + "thdrawH\000R\010withdraw\022E\n\016batch_transfer\030# \001" + "(\0132\034.pactus.PayloadBatchTransferH\000R\rbatc" + "hTransfer\022\022\n\004memo\030\010 \001(\tR\004memo\022\035\n\npublic_" + "key\030\t \001(\tR\tpublicKey\022\034\n\tsignature\030\n \001(\tR" + "\tsignature\022!\n\014block_height\030\013 \001(\rR\013blockH" + "eight\022\034\n\tconfirmed\030\014 \001(\010R\tconfirmed\022$\n\rc" + "onfirmations\030\r \001(\005R\rconfirmationsB\t\n\007pay" + "load\"F\n\033DecodeRawTransactionRequest\022\'\n\017r" + "aw_transaction\030\001 \001(\tR\016rawTransaction\"Y\n\034" + "DecodeRawTransactionResponse\0229\n\013transact" + "ion\030\001 \001(\0132\027.pactus.TransactionInfoR\013tran" + "saction\"B\n\027CheckTransactionRequest\022\'\n\017ra" + "w_transaction\030\001 \001(\tR\016rawTransaction\"Z\n\030C" + "heckTransactionResponse\022\031\n\010is_valid\030\001 \001(" + "\010R\007isValid\022#\n\rerror_message\030\002 \001(\tR\014error" + "Message*\316\001\n\013PayloadType\022\034\n\030PAYLOAD_TYPE_" + "UNSPECIFIED\020\000\022\031\n\025PAYLOAD_TYPE_TRANSFER\020\001" + "\022\025\n\021PAYLOAD_TYPE_BOND\020\002\022\032\n\026PAYLOAD_TYPE_" + "SORTITION\020\003\022\027\n\023PAYLOAD_TYPE_UNBOND\020\004\022\031\n\025" + "PAYLOAD_TYPE_WITHDRAW\020\005\022\037\n\033PAYLOAD_TYPE_" + "BATCH_TRANSFER\020\006*V\n\024TransactionVerbosity" + "\022\036\n\032TRANSACTION_VERBOSITY_DATA\020\000\022\036\n\032TRAN" + "SACTION_VERBOSITY_INFO\020\0012\326\007\n\013Transaction" + "\022O\n\016GetTransaction\022\035.pactus.GetTransacti" + "onRequest\032\036.pactus.GetTransactionRespons" + "e\022I\n\014CalculateFee\022\033.pactus.CalculateFeeR" + "equest\032\034.pactus.CalculateFeeResponse\022a\n\024" + "BroadcastTransaction\022#.pactus.BroadcastT" + "ransactionRequest\032$.pactus.BroadcastTran" + "sactionResponse\022h\n\031GetRawTransferTransac" + "tion\022(.pactus.GetRawTransferTransactionR" + "equest\032!.pactus.GetRawTransactionRespons" + "e\022`\n\025GetRawBondTransaction\022$.pactus.GetR" + "awBondTransactionRequest\032!.pactus.GetRaw" + "TransactionResponse\022d\n\027GetRawUnbondTrans" + "action\022&.pactus.GetRawUnbondTransactionR" + "equest\032!.pactus.GetRawTransactionRespons" + "e\022h\n\031GetRawWithdrawTransaction\022(.pactus." + "GetRawWithdrawTransactionRequest\032!.pactu" + "s.GetRawTransactionResponse\022r\n\036GetRawBat" + "chTransferTransaction\022-.pactus.GetRawBat" + "chTransferTransactionRequest\032!.pactus.Ge" + "tRawTransactionResponse\022a\n\024DecodeRawTran" + "saction\022#.pactus.DecodeRawTransactionReq" + "uest\032$.pactus.DecodeRawTransactionRespon" + "se\022U\n\020CheckTransaction\022\037.pactus.CheckTra" + "nsactionRequest\032 .pactus.CheckTransactio" + "nResponseB:\n\006pactusZ0github.com/pactus-p" + "roject/pactus/www/grpc/pactusb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_pactus_GetTransactionRequest_descriptor = getDescriptor().getMessageType(0); internal_static_pactus_GetTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTransactionRequest_descriptor, new java.lang.String[] { "Id", "Verbosity", }); internal_static_pactus_GetTransactionResponse_descriptor = getDescriptor().getMessageType(1); internal_static_pactus_GetTransactionResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTransactionResponse_descriptor, new java.lang.String[] { "BlockHeight", "BlockTime", "Transaction", }); internal_static_pactus_CalculateFeeRequest_descriptor = getDescriptor().getMessageType(2); internal_static_pactus_CalculateFeeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CalculateFeeRequest_descriptor, new java.lang.String[] { "Amount", "PayloadType", "FixedAmount", }); internal_static_pactus_CalculateFeeResponse_descriptor = getDescriptor().getMessageType(3); internal_static_pactus_CalculateFeeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CalculateFeeResponse_descriptor, new java.lang.String[] { "Amount", "Fee", }); internal_static_pactus_BroadcastTransactionRequest_descriptor = getDescriptor().getMessageType(4); internal_static_pactus_BroadcastTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_BroadcastTransactionRequest_descriptor, new java.lang.String[] { "SignedRawTransaction", }); internal_static_pactus_BroadcastTransactionResponse_descriptor = getDescriptor().getMessageType(5); internal_static_pactus_BroadcastTransactionResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_BroadcastTransactionResponse_descriptor, new java.lang.String[] { "Id", }); internal_static_pactus_GetRawTransferTransactionRequest_descriptor = getDescriptor().getMessageType(6); internal_static_pactus_GetRawTransferTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetRawTransferTransactionRequest_descriptor, new java.lang.String[] { "LockTime", "Sender", "Receiver", "Amount", "Fee", "Memo", }); internal_static_pactus_GetRawBondTransactionRequest_descriptor = getDescriptor().getMessageType(7); internal_static_pactus_GetRawBondTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetRawBondTransactionRequest_descriptor, new java.lang.String[] { "LockTime", "Sender", "Receiver", "Stake", "PublicKey", "Fee", "Memo", "DelegateOwner", "DelegateShare", "DelegateExpiry", }); internal_static_pactus_GetRawUnbondTransactionRequest_descriptor = getDescriptor().getMessageType(8); internal_static_pactus_GetRawUnbondTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetRawUnbondTransactionRequest_descriptor, new java.lang.String[] { "LockTime", "ValidatorAddress", "Memo", "DelegateOwner", }); internal_static_pactus_GetRawWithdrawTransactionRequest_descriptor = getDescriptor().getMessageType(9); internal_static_pactus_GetRawWithdrawTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetRawWithdrawTransactionRequest_descriptor, new java.lang.String[] { "LockTime", "ValidatorAddress", "AccountAddress", "Amount", "Fee", "Memo", }); internal_static_pactus_GetRawBatchTransferTransactionRequest_descriptor = getDescriptor().getMessageType(10); internal_static_pactus_GetRawBatchTransferTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetRawBatchTransferTransactionRequest_descriptor, new java.lang.String[] { "LockTime", "Sender", "Recipients", "Fee", "Memo", }); internal_static_pactus_GetRawTransactionResponse_descriptor = getDescriptor().getMessageType(11); internal_static_pactus_GetRawTransactionResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetRawTransactionResponse_descriptor, new java.lang.String[] { "RawTransaction", "Id", }); internal_static_pactus_PayloadTransfer_descriptor = getDescriptor().getMessageType(12); internal_static_pactus_PayloadTransfer_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PayloadTransfer_descriptor, new java.lang.String[] { "Sender", "Receiver", "Amount", }); internal_static_pactus_PayloadBond_descriptor = getDescriptor().getMessageType(13); internal_static_pactus_PayloadBond_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PayloadBond_descriptor, new java.lang.String[] { "Sender", "Receiver", "Stake", "PublicKey", "IsDelegated", "DelegateOwner", "DelegateShare", "DelegateExpiry", }); internal_static_pactus_PayloadSortition_descriptor = getDescriptor().getMessageType(14); internal_static_pactus_PayloadSortition_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PayloadSortition_descriptor, new java.lang.String[] { "Address", "Proof", }); internal_static_pactus_PayloadUnbond_descriptor = getDescriptor().getMessageType(15); internal_static_pactus_PayloadUnbond_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PayloadUnbond_descriptor, new java.lang.String[] { "Validator", "DelegateOwner", }); internal_static_pactus_PayloadWithdraw_descriptor = getDescriptor().getMessageType(16); internal_static_pactus_PayloadWithdraw_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PayloadWithdraw_descriptor, new java.lang.String[] { "ValidatorAddress", "AccountAddress", "Amount", }); internal_static_pactus_PayloadBatchTransfer_descriptor = getDescriptor().getMessageType(17); internal_static_pactus_PayloadBatchTransfer_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PayloadBatchTransfer_descriptor, new java.lang.String[] { "Sender", "Recipients", }); internal_static_pactus_Recipient_descriptor = getDescriptor().getMessageType(18); internal_static_pactus_Recipient_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_Recipient_descriptor, new java.lang.String[] { "Receiver", "Amount", }); internal_static_pactus_TransactionInfo_descriptor = getDescriptor().getMessageType(19); internal_static_pactus_TransactionInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_TransactionInfo_descriptor, new java.lang.String[] { "Id", "Data", "Version", "LockTime", "Value", "Fee", "PayloadType", "Transfer", "Bond", "Sortition", "Unbond", "Withdraw", "BatchTransfer", "Memo", "PublicKey", "Signature", "BlockHeight", "Confirmed", "Confirmations", "Payload", }); internal_static_pactus_DecodeRawTransactionRequest_descriptor = getDescriptor().getMessageType(20); internal_static_pactus_DecodeRawTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_DecodeRawTransactionRequest_descriptor, new java.lang.String[] { "RawTransaction", }); internal_static_pactus_DecodeRawTransactionResponse_descriptor = getDescriptor().getMessageType(21); internal_static_pactus_DecodeRawTransactionResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_DecodeRawTransactionResponse_descriptor, new java.lang.String[] { "Transaction", }); internal_static_pactus_CheckTransactionRequest_descriptor = getDescriptor().getMessageType(22); internal_static_pactus_CheckTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CheckTransactionRequest_descriptor, new java.lang.String[] { "RawTransaction", }); internal_static_pactus_CheckTransactionResponse_descriptor = getDescriptor().getMessageType(23); internal_static_pactus_CheckTransactionResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CheckTransactionResponse_descriptor, new java.lang.String[] { "IsValid", "ErrorMessage", }); descriptor.resolveAllFeaturesImmutable(); } // @@protoc_insertion_point(outer_class_scope) } ================================================ FILE: www/grpc/gen/java/pactus/UtilsGrpc.java ================================================ package pactus; import static io.grpc.MethodDescriptor.generateFullMethodName; /** *
 * Utils service defines RPC methods for utility functions such as message
 * signing, verification, and other cryptographic operations.
 * 
*/ @io.grpc.stub.annotations.GrpcGenerated public final class UtilsGrpc { private UtilsGrpc() {} public static final java.lang.String SERVICE_NAME = "pactus.Utils"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor getSignMessageWithPrivateKeyMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SignMessageWithPrivateKey", requestType = pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.class, responseType = pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getSignMessageWithPrivateKeyMethod() { io.grpc.MethodDescriptor getSignMessageWithPrivateKeyMethod; if ((getSignMessageWithPrivateKeyMethod = UtilsGrpc.getSignMessageWithPrivateKeyMethod) == null) { synchronized (UtilsGrpc.class) { if ((getSignMessageWithPrivateKeyMethod = UtilsGrpc.getSignMessageWithPrivateKeyMethod) == null) { UtilsGrpc.getSignMessageWithPrivateKeyMethod = getSignMessageWithPrivateKeyMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SignMessageWithPrivateKey")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.getDefaultInstance())) .setSchemaDescriptor(new UtilsMethodDescriptorSupplier("SignMessageWithPrivateKey")) .build(); } } } return getSignMessageWithPrivateKeyMethod; } private static volatile io.grpc.MethodDescriptor getVerifyMessageMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "VerifyMessage", requestType = pactus.UtilsOuterClass.VerifyMessageRequest.class, responseType = pactus.UtilsOuterClass.VerifyMessageResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getVerifyMessageMethod() { io.grpc.MethodDescriptor getVerifyMessageMethod; if ((getVerifyMessageMethod = UtilsGrpc.getVerifyMessageMethod) == null) { synchronized (UtilsGrpc.class) { if ((getVerifyMessageMethod = UtilsGrpc.getVerifyMessageMethod) == null) { UtilsGrpc.getVerifyMessageMethod = getVerifyMessageMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "VerifyMessage")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.VerifyMessageRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.VerifyMessageResponse.getDefaultInstance())) .setSchemaDescriptor(new UtilsMethodDescriptorSupplier("VerifyMessage")) .build(); } } } return getVerifyMessageMethod; } private static volatile io.grpc.MethodDescriptor getPublicKeyAggregationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "PublicKeyAggregation", requestType = pactus.UtilsOuterClass.PublicKeyAggregationRequest.class, responseType = pactus.UtilsOuterClass.PublicKeyAggregationResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getPublicKeyAggregationMethod() { io.grpc.MethodDescriptor getPublicKeyAggregationMethod; if ((getPublicKeyAggregationMethod = UtilsGrpc.getPublicKeyAggregationMethod) == null) { synchronized (UtilsGrpc.class) { if ((getPublicKeyAggregationMethod = UtilsGrpc.getPublicKeyAggregationMethod) == null) { UtilsGrpc.getPublicKeyAggregationMethod = getPublicKeyAggregationMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "PublicKeyAggregation")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.PublicKeyAggregationRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.PublicKeyAggregationResponse.getDefaultInstance())) .setSchemaDescriptor(new UtilsMethodDescriptorSupplier("PublicKeyAggregation")) .build(); } } } return getPublicKeyAggregationMethod; } private static volatile io.grpc.MethodDescriptor getSignatureAggregationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SignatureAggregation", requestType = pactus.UtilsOuterClass.SignatureAggregationRequest.class, responseType = pactus.UtilsOuterClass.SignatureAggregationResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getSignatureAggregationMethod() { io.grpc.MethodDescriptor getSignatureAggregationMethod; if ((getSignatureAggregationMethod = UtilsGrpc.getSignatureAggregationMethod) == null) { synchronized (UtilsGrpc.class) { if ((getSignatureAggregationMethod = UtilsGrpc.getSignatureAggregationMethod) == null) { UtilsGrpc.getSignatureAggregationMethod = getSignatureAggregationMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SignatureAggregation")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.SignatureAggregationRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.UtilsOuterClass.SignatureAggregationResponse.getDefaultInstance())) .setSchemaDescriptor(new UtilsMethodDescriptorSupplier("SignatureAggregation")) .build(); } } } return getSignatureAggregationMethod; } /** * Creates a new async stub that supports all call types for the service */ public static UtilsStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public UtilsStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsStub(channel, callOptions); } }; return UtilsStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static UtilsBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public UtilsBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsBlockingV2Stub(channel, callOptions); } }; return UtilsBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static UtilsBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public UtilsBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsBlockingStub(channel, callOptions); } }; return UtilsBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static UtilsFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public UtilsFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsFutureStub(channel, callOptions); } }; return UtilsFutureStub.newStub(factory, channel); } /** *
   * Utils service defines RPC methods for utility functions such as message
   * signing, verification, and other cryptographic operations.
   * 
*/ public interface AsyncService { /** *
     * SignMessageWithPrivateKey signs a message with the provided private key.
     * 
*/ default void signMessageWithPrivateKey(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSignMessageWithPrivateKeyMethod(), responseObserver); } /** *
     * VerifyMessage verifies a signature against the public key and message.
     * 
*/ default void verifyMessage(pactus.UtilsOuterClass.VerifyMessageRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getVerifyMessageMethod(), responseObserver); } /** *
     * PublicKeyAggregation aggregates multiple BLS public keys into a single key.
     * 
*/ default void publicKeyAggregation(pactus.UtilsOuterClass.PublicKeyAggregationRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getPublicKeyAggregationMethod(), responseObserver); } /** *
     * SignatureAggregation aggregates multiple BLS signatures into a single signature.
     * 
*/ default void signatureAggregation(pactus.UtilsOuterClass.SignatureAggregationRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSignatureAggregationMethod(), responseObserver); } } /** * Base class for the server implementation of the service Utils. *
   * Utils service defines RPC methods for utility functions such as message
   * signing, verification, and other cryptographic operations.
   * 
*/ public static abstract class UtilsImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return UtilsGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service Utils. *
   * Utils service defines RPC methods for utility functions such as message
   * signing, verification, and other cryptographic operations.
   * 
*/ public static final class UtilsStub extends io.grpc.stub.AbstractAsyncStub { private UtilsStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected UtilsStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsStub(channel, callOptions); } /** *
     * SignMessageWithPrivateKey signs a message with the provided private key.
     * 
*/ public void signMessageWithPrivateKey(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getSignMessageWithPrivateKeyMethod(), getCallOptions()), request, responseObserver); } /** *
     * VerifyMessage verifies a signature against the public key and message.
     * 
*/ public void verifyMessage(pactus.UtilsOuterClass.VerifyMessageRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getVerifyMessageMethod(), getCallOptions()), request, responseObserver); } /** *
     * PublicKeyAggregation aggregates multiple BLS public keys into a single key.
     * 
*/ public void publicKeyAggregation(pactus.UtilsOuterClass.PublicKeyAggregationRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getPublicKeyAggregationMethod(), getCallOptions()), request, responseObserver); } /** *
     * SignatureAggregation aggregates multiple BLS signatures into a single signature.
     * 
*/ public void signatureAggregation(pactus.UtilsOuterClass.SignatureAggregationRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getSignatureAggregationMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Utils. *
   * Utils service defines RPC methods for utility functions such as message
   * signing, verification, and other cryptographic operations.
   * 
*/ public static final class UtilsBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub { private UtilsBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected UtilsBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsBlockingV2Stub(channel, callOptions); } /** *
     * SignMessageWithPrivateKey signs a message with the provided private key.
     * 
*/ public pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse signMessageWithPrivateKey(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getSignMessageWithPrivateKeyMethod(), getCallOptions(), request); } /** *
     * VerifyMessage verifies a signature against the public key and message.
     * 
*/ public pactus.UtilsOuterClass.VerifyMessageResponse verifyMessage(pactus.UtilsOuterClass.VerifyMessageRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getVerifyMessageMethod(), getCallOptions(), request); } /** *
     * PublicKeyAggregation aggregates multiple BLS public keys into a single key.
     * 
*/ public pactus.UtilsOuterClass.PublicKeyAggregationResponse publicKeyAggregation(pactus.UtilsOuterClass.PublicKeyAggregationRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getPublicKeyAggregationMethod(), getCallOptions(), request); } /** *
     * SignatureAggregation aggregates multiple BLS signatures into a single signature.
     * 
*/ public pactus.UtilsOuterClass.SignatureAggregationResponse signatureAggregation(pactus.UtilsOuterClass.SignatureAggregationRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getSignatureAggregationMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Utils. *
   * Utils service defines RPC methods for utility functions such as message
   * signing, verification, and other cryptographic operations.
   * 
*/ public static final class UtilsBlockingStub extends io.grpc.stub.AbstractBlockingStub { private UtilsBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected UtilsBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsBlockingStub(channel, callOptions); } /** *
     * SignMessageWithPrivateKey signs a message with the provided private key.
     * 
*/ public pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse signMessageWithPrivateKey(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getSignMessageWithPrivateKeyMethod(), getCallOptions(), request); } /** *
     * VerifyMessage verifies a signature against the public key and message.
     * 
*/ public pactus.UtilsOuterClass.VerifyMessageResponse verifyMessage(pactus.UtilsOuterClass.VerifyMessageRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getVerifyMessageMethod(), getCallOptions(), request); } /** *
     * PublicKeyAggregation aggregates multiple BLS public keys into a single key.
     * 
*/ public pactus.UtilsOuterClass.PublicKeyAggregationResponse publicKeyAggregation(pactus.UtilsOuterClass.PublicKeyAggregationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getPublicKeyAggregationMethod(), getCallOptions(), request); } /** *
     * SignatureAggregation aggregates multiple BLS signatures into a single signature.
     * 
*/ public pactus.UtilsOuterClass.SignatureAggregationResponse signatureAggregation(pactus.UtilsOuterClass.SignatureAggregationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getSignatureAggregationMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service Utils. *
   * Utils service defines RPC methods for utility functions such as message
   * signing, verification, and other cryptographic operations.
   * 
*/ public static final class UtilsFutureStub extends io.grpc.stub.AbstractFutureStub { private UtilsFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected UtilsFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new UtilsFutureStub(channel, callOptions); } /** *
     * SignMessageWithPrivateKey signs a message with the provided private key.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture signMessageWithPrivateKey( pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getSignMessageWithPrivateKeyMethod(), getCallOptions()), request); } /** *
     * VerifyMessage verifies a signature against the public key and message.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture verifyMessage( pactus.UtilsOuterClass.VerifyMessageRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getVerifyMessageMethod(), getCallOptions()), request); } /** *
     * PublicKeyAggregation aggregates multiple BLS public keys into a single key.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture publicKeyAggregation( pactus.UtilsOuterClass.PublicKeyAggregationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getPublicKeyAggregationMethod(), getCallOptions()), request); } /** *
     * SignatureAggregation aggregates multiple BLS signatures into a single signature.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture signatureAggregation( pactus.UtilsOuterClass.SignatureAggregationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getSignatureAggregationMethod(), getCallOptions()), request); } } private static final int METHODID_SIGN_MESSAGE_WITH_PRIVATE_KEY = 0; private static final int METHODID_VERIFY_MESSAGE = 1; private static final int METHODID_PUBLIC_KEY_AGGREGATION = 2; private static final int METHODID_SIGNATURE_AGGREGATION = 3; private static final class MethodHandlers implements io.grpc.stub.ServerCalls.UnaryMethod, io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_SIGN_MESSAGE_WITH_PRIVATE_KEY: serviceImpl.signMessageWithPrivateKey((pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_VERIFY_MESSAGE: serviceImpl.verifyMessage((pactus.UtilsOuterClass.VerifyMessageRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_PUBLIC_KEY_AGGREGATION: serviceImpl.publicKeyAggregation((pactus.UtilsOuterClass.PublicKeyAggregationRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_SIGNATURE_AGGREGATION: serviceImpl.signatureAggregation((pactus.UtilsOuterClass.SignatureAggregationRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver invoke( io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getSignMessageWithPrivateKeyMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest, pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse>( service, METHODID_SIGN_MESSAGE_WITH_PRIVATE_KEY))) .addMethod( getVerifyMessageMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.UtilsOuterClass.VerifyMessageRequest, pactus.UtilsOuterClass.VerifyMessageResponse>( service, METHODID_VERIFY_MESSAGE))) .addMethod( getPublicKeyAggregationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.UtilsOuterClass.PublicKeyAggregationRequest, pactus.UtilsOuterClass.PublicKeyAggregationResponse>( service, METHODID_PUBLIC_KEY_AGGREGATION))) .addMethod( getSignatureAggregationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.UtilsOuterClass.SignatureAggregationRequest, pactus.UtilsOuterClass.SignatureAggregationResponse>( service, METHODID_SIGNATURE_AGGREGATION))) .build(); } private static abstract class UtilsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { UtilsBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return pactus.UtilsOuterClass.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Utils"); } } private static final class UtilsFileDescriptorSupplier extends UtilsBaseDescriptorSupplier { UtilsFileDescriptorSupplier() {} } private static final class UtilsMethodDescriptorSupplier extends UtilsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; UtilsMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (UtilsGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new UtilsFileDescriptorSupplier()) .addMethod(getSignMessageWithPrivateKeyMethod()) .addMethod(getVerifyMessageMethod()) .addMethod(getPublicKeyAggregationMethod()) .addMethod(getSignatureAggregationMethod()) .build(); } } } return result; } } ================================================ FILE: www/grpc/gen/java/pactus/UtilsOuterClass.java ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: utils.proto // Protobuf Java Version: 4.33.2 package pactus; @com.google.protobuf.Generated public final class UtilsOuterClass extends com.google.protobuf.GeneratedFile { private UtilsOuterClass() {} static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "UtilsOuterClass"); } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface SignMessageWithPrivateKeyRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignMessageWithPrivateKeyRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The private key to sign the message.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The privateKey. */ java.lang.String getPrivateKey(); /** *
     * The private key to sign the message.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The bytes for privateKey. */ com.google.protobuf.ByteString getPrivateKeyBytes(); /** *
     * The message content to be signed.
     * 
* * string message = 2 [json_name = "message"]; * @return The message. */ java.lang.String getMessage(); /** *
     * The message content to be signed.
     * 
* * string message = 2 [json_name = "message"]; * @return The bytes for message. */ com.google.protobuf.ByteString getMessageBytes(); } /** *
   * Request message for signing a message with a private key.
   * 
* * Protobuf type {@code pactus.SignMessageWithPrivateKeyRequest} */ public static final class SignMessageWithPrivateKeyRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignMessageWithPrivateKeyRequest) SignMessageWithPrivateKeyRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignMessageWithPrivateKeyRequest"); } // Use SignMessageWithPrivateKeyRequest.newBuilder() to construct. private SignMessageWithPrivateKeyRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignMessageWithPrivateKeyRequest() { privateKey_ = ""; message_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.class, pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.Builder.class); } public static final int PRIVATE_KEY_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object privateKey_ = ""; /** *
     * The private key to sign the message.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The privateKey. */ @java.lang.Override public java.lang.String getPrivateKey() { java.lang.Object ref = privateKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); privateKey_ = s; return s; } } /** *
     * The private key to sign the message.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The bytes for privateKey. */ @java.lang.Override public com.google.protobuf.ByteString getPrivateKeyBytes() { java.lang.Object ref = privateKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); privateKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MESSAGE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object message_ = ""; /** *
     * The message content to be signed.
     * 
* * string message = 2 [json_name = "message"]; * @return The message. */ @java.lang.Override public java.lang.String getMessage() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } } /** *
     * The message content to be signed.
     * 
* * string message = 2 [json_name = "message"]; * @return The bytes for message. */ @java.lang.Override public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(privateKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, privateKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(message_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, message_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(privateKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, privateKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(message_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, message_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest)) { return super.equals(obj); } pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest other = (pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest) obj; if (!getPrivateKey() .equals(other.getPrivateKey())) return false; if (!getMessage() .equals(other.getMessage())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PRIVATE_KEY_FIELD_NUMBER; hash = (53 * hash) + getPrivateKey().hashCode(); hash = (37 * hash) + MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getMessage().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for signing a message with a private key.
     * 
* * Protobuf type {@code pactus.SignMessageWithPrivateKeyRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignMessageWithPrivateKeyRequest) pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.class, pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.Builder.class); } // Construct using pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; privateKey_ = ""; message_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyRequest_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest getDefaultInstanceForType() { return pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest build() { pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest buildPartial() { pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest result = new pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.privateKey_ = privateKey_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.message_ = message_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest) { return mergeFrom((pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest other) { if (other == pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest.getDefaultInstance()) return this; if (!other.getPrivateKey().isEmpty()) { privateKey_ = other.privateKey_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getMessage().isEmpty()) { message_ = other.message_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { privateKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { message_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object privateKey_ = ""; /** *
       * The private key to sign the message.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The privateKey. */ public java.lang.String getPrivateKey() { java.lang.Object ref = privateKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); privateKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The private key to sign the message.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The bytes for privateKey. */ public com.google.protobuf.ByteString getPrivateKeyBytes() { java.lang.Object ref = privateKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); privateKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The private key to sign the message.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @param value The privateKey to set. * @return This builder for chaining. */ public Builder setPrivateKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } privateKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The private key to sign the message.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @return This builder for chaining. */ public Builder clearPrivateKey() { privateKey_ = getDefaultInstance().getPrivateKey(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The private key to sign the message.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @param value The bytes for privateKey to set. * @return This builder for chaining. */ public Builder setPrivateKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); privateKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object message_ = ""; /** *
       * The message content to be signed.
       * 
* * string message = 2 [json_name = "message"]; * @return The message. */ public java.lang.String getMessage() { java.lang.Object ref = message_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The message content to be signed.
       * 
* * string message = 2 [json_name = "message"]; * @return The bytes for message. */ public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The message content to be signed.
       * 
* * string message = 2 [json_name = "message"]; * @param value The message to set. * @return This builder for chaining. */ public Builder setMessage( java.lang.String value) { if (value == null) { throw new NullPointerException(); } message_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The message content to be signed.
       * 
* * string message = 2 [json_name = "message"]; * @return This builder for chaining. */ public Builder clearMessage() { message_ = getDefaultInstance().getMessage(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The message content to be signed.
       * 
* * string message = 2 [json_name = "message"]; * @param value The bytes for message to set. * @return This builder for chaining. */ public Builder setMessageBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); message_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignMessageWithPrivateKeyRequest) } // @@protoc_insertion_point(class_scope:pactus.SignMessageWithPrivateKeyRequest) private static final pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest(); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignMessageWithPrivateKeyRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignMessageWithPrivateKeyResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignMessageWithPrivateKeyResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The resulting signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The resulting signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); } /** *
   * Response message contains the signature generated from the message.
   * 
* * Protobuf type {@code pactus.SignMessageWithPrivateKeyResponse} */ public static final class SignMessageWithPrivateKeyResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignMessageWithPrivateKeyResponse) SignMessageWithPrivateKeyResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignMessageWithPrivateKeyResponse"); } // Use SignMessageWithPrivateKeyResponse.newBuilder() to construct. private SignMessageWithPrivateKeyResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignMessageWithPrivateKeyResponse() { signature_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.class, pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.Builder.class); } public static final int SIGNATURE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The resulting signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The resulting signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, signature_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, signature_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse)) { return super.equals(obj); } pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse other = (pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse) obj; if (!getSignature() .equals(other.getSignature())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the signature generated from the message.
     * 
* * Protobuf type {@code pactus.SignMessageWithPrivateKeyResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignMessageWithPrivateKeyResponse) pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.class, pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.Builder.class); } // Construct using pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; signature_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_SignMessageWithPrivateKeyResponse_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse getDefaultInstanceForType() { return pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse build() { pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse buildPartial() { pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse result = new pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.signature_ = signature_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse) { return mergeFrom((pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse other) { if (other == pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse.getDefaultInstance()) return this; if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object signature_ = ""; /** *
       * The resulting signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The resulting signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The resulting signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The resulting signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The resulting signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignMessageWithPrivateKeyResponse) } // @@protoc_insertion_point(class_scope:pactus.SignMessageWithPrivateKeyResponse) private static final pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse(); } public static pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignMessageWithPrivateKeyResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.SignMessageWithPrivateKeyResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface VerifyMessageRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.VerifyMessageRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The original message content that was signed.
     * 
* * string message = 1 [json_name = "message"]; * @return The message. */ java.lang.String getMessage(); /** *
     * The original message content that was signed.
     * 
* * string message = 1 [json_name = "message"]; * @return The bytes for message. */ com.google.protobuf.ByteString getMessageBytes(); /** *
     * The signature to verify in hexadecimal format.
     * 
* * string signature = 2 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The signature to verify in hexadecimal format.
     * 
* * string signature = 2 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); /** *
     * The public key of the signer.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key of the signer.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); } /** *
   * Request message for verifying a message signature.
   * 
* * Protobuf type {@code pactus.VerifyMessageRequest} */ public static final class VerifyMessageRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.VerifyMessageRequest) VerifyMessageRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "VerifyMessageRequest"); } // Use VerifyMessageRequest.newBuilder() to construct. private VerifyMessageRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private VerifyMessageRequest() { message_ = ""; signature_ = ""; publicKey_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.VerifyMessageRequest.class, pactus.UtilsOuterClass.VerifyMessageRequest.Builder.class); } public static final int MESSAGE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object message_ = ""; /** *
     * The original message content that was signed.
     * 
* * string message = 1 [json_name = "message"]; * @return The message. */ @java.lang.Override public java.lang.String getMessage() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } } /** *
     * The original message content that was signed.
     * 
* * string message = 1 [json_name = "message"]; * @return The bytes for message. */ @java.lang.Override public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SIGNATURE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The signature to verify in hexadecimal format.
     * 
* * string signature = 2 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The signature to verify in hexadecimal format.
     * 
* * string signature = 2 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PUBLIC_KEY_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key of the signer.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key of the signer.
     * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(message_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, message_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, signature_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, publicKey_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(message_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, message_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, signature_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, publicKey_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.VerifyMessageRequest)) { return super.equals(obj); } pactus.UtilsOuterClass.VerifyMessageRequest other = (pactus.UtilsOuterClass.VerifyMessageRequest) obj; if (!getMessage() .equals(other.getMessage())) return false; if (!getSignature() .equals(other.getSignature())) return false; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getMessage().hashCode(); hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.VerifyMessageRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.VerifyMessageRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for verifying a message signature.
     * 
* * Protobuf type {@code pactus.VerifyMessageRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.VerifyMessageRequest) pactus.UtilsOuterClass.VerifyMessageRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.VerifyMessageRequest.class, pactus.UtilsOuterClass.VerifyMessageRequest.Builder.class); } // Construct using pactus.UtilsOuterClass.VerifyMessageRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; message_ = ""; signature_ = ""; publicKey_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageRequest_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageRequest getDefaultInstanceForType() { return pactus.UtilsOuterClass.VerifyMessageRequest.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageRequest build() { pactus.UtilsOuterClass.VerifyMessageRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageRequest buildPartial() { pactus.UtilsOuterClass.VerifyMessageRequest result = new pactus.UtilsOuterClass.VerifyMessageRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.VerifyMessageRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.message_ = message_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.signature_ = signature_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.publicKey_ = publicKey_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.VerifyMessageRequest) { return mergeFrom((pactus.UtilsOuterClass.VerifyMessageRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.VerifyMessageRequest other) { if (other == pactus.UtilsOuterClass.VerifyMessageRequest.getDefaultInstance()) return this; if (!other.getMessage().isEmpty()) { message_ = other.message_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { message_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object message_ = ""; /** *
       * The original message content that was signed.
       * 
* * string message = 1 [json_name = "message"]; * @return The message. */ public java.lang.String getMessage() { java.lang.Object ref = message_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The original message content that was signed.
       * 
* * string message = 1 [json_name = "message"]; * @return The bytes for message. */ public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The original message content that was signed.
       * 
* * string message = 1 [json_name = "message"]; * @param value The message to set. * @return This builder for chaining. */ public Builder setMessage( java.lang.String value) { if (value == null) { throw new NullPointerException(); } message_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The original message content that was signed.
       * 
* * string message = 1 [json_name = "message"]; * @return This builder for chaining. */ public Builder clearMessage() { message_ = getDefaultInstance().getMessage(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The original message content that was signed.
       * 
* * string message = 1 [json_name = "message"]; * @param value The bytes for message to set. * @return This builder for chaining. */ public Builder setMessageBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); message_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object signature_ = ""; /** *
       * The signature to verify in hexadecimal format.
       * 
* * string signature = 2 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signature to verify in hexadecimal format.
       * 
* * string signature = 2 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signature to verify in hexadecimal format.
       * 
* * string signature = 2 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The signature to verify in hexadecimal format.
       * 
* * string signature = 2 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The signature to verify in hexadecimal format.
       * 
* * string signature = 2 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object publicKey_ = ""; /** *
       * The public key of the signer.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key of the signer.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key of the signer.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The public key of the signer.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The public key of the signer.
       * 
* * string public_key = 3 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.VerifyMessageRequest) } // @@protoc_insertion_point(class_scope:pactus.VerifyMessageRequest) private static final pactus.UtilsOuterClass.VerifyMessageRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.VerifyMessageRequest(); } public static pactus.UtilsOuterClass.VerifyMessageRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public VerifyMessageRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface VerifyMessageResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.VerifyMessageResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Boolean indicating whether the signature is valid for the given message and public key.
     * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return The isValid. */ boolean getIsValid(); } /** *
   * Response message contains the verification result.
   * 
* * Protobuf type {@code pactus.VerifyMessageResponse} */ public static final class VerifyMessageResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.VerifyMessageResponse) VerifyMessageResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "VerifyMessageResponse"); } // Use VerifyMessageResponse.newBuilder() to construct. private VerifyMessageResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private VerifyMessageResponse() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.VerifyMessageResponse.class, pactus.UtilsOuterClass.VerifyMessageResponse.Builder.class); } public static final int IS_VALID_FIELD_NUMBER = 1; private boolean isValid_ = false; /** *
     * Boolean indicating whether the signature is valid for the given message and public key.
     * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return The isValid. */ @java.lang.Override public boolean getIsValid() { return isValid_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (isValid_ != false) { output.writeBool(1, isValid_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (isValid_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, isValid_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.VerifyMessageResponse)) { return super.equals(obj); } pactus.UtilsOuterClass.VerifyMessageResponse other = (pactus.UtilsOuterClass.VerifyMessageResponse) obj; if (getIsValid() != other.getIsValid()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + IS_VALID_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsValid()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.VerifyMessageResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.VerifyMessageResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the verification result.
     * 
* * Protobuf type {@code pactus.VerifyMessageResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.VerifyMessageResponse) pactus.UtilsOuterClass.VerifyMessageResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.VerifyMessageResponse.class, pactus.UtilsOuterClass.VerifyMessageResponse.Builder.class); } // Construct using pactus.UtilsOuterClass.VerifyMessageResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; isValid_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_VerifyMessageResponse_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageResponse getDefaultInstanceForType() { return pactus.UtilsOuterClass.VerifyMessageResponse.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageResponse build() { pactus.UtilsOuterClass.VerifyMessageResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageResponse buildPartial() { pactus.UtilsOuterClass.VerifyMessageResponse result = new pactus.UtilsOuterClass.VerifyMessageResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.VerifyMessageResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.isValid_ = isValid_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.VerifyMessageResponse) { return mergeFrom((pactus.UtilsOuterClass.VerifyMessageResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.VerifyMessageResponse other) { if (other == pactus.UtilsOuterClass.VerifyMessageResponse.getDefaultInstance()) return this; if (other.getIsValid() != false) { setIsValid(other.getIsValid()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { isValid_ = input.readBool(); bitField0_ |= 0x00000001; break; } // case 8 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private boolean isValid_ ; /** *
       * Boolean indicating whether the signature is valid for the given message and public key.
       * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return The isValid. */ @java.lang.Override public boolean getIsValid() { return isValid_; } /** *
       * Boolean indicating whether the signature is valid for the given message and public key.
       * 
* * bool is_valid = 1 [json_name = "isValid"]; * @param value The isValid to set. * @return This builder for chaining. */ public Builder setIsValid(boolean value) { isValid_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Boolean indicating whether the signature is valid for the given message and public key.
       * 
* * bool is_valid = 1 [json_name = "isValid"]; * @return This builder for chaining. */ public Builder clearIsValid() { bitField0_ = (bitField0_ & ~0x00000001); isValid_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.VerifyMessageResponse) } // @@protoc_insertion_point(class_scope:pactus.VerifyMessageResponse) private static final pactus.UtilsOuterClass.VerifyMessageResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.VerifyMessageResponse(); } public static pactus.UtilsOuterClass.VerifyMessageResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public VerifyMessageResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.VerifyMessageResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PublicKeyAggregationRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PublicKeyAggregationRequest) com.google.protobuf.MessageOrBuilder { /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return A list containing the publicKeys. */ java.util.List getPublicKeysList(); /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return The count of publicKeys. */ int getPublicKeysCount(); /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index of the element to return. * @return The publicKeys at the given index. */ java.lang.String getPublicKeys(int index); /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index of the value to return. * @return The bytes of the publicKeys at the given index. */ com.google.protobuf.ByteString getPublicKeysBytes(int index); } /** *
   * Request message for aggregating multiple BLS public keys.
   * 
* * Protobuf type {@code pactus.PublicKeyAggregationRequest} */ public static final class PublicKeyAggregationRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PublicKeyAggregationRequest) PublicKeyAggregationRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PublicKeyAggregationRequest"); } // Use PublicKeyAggregationRequest.newBuilder() to construct. private PublicKeyAggregationRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PublicKeyAggregationRequest() { publicKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.PublicKeyAggregationRequest.class, pactus.UtilsOuterClass.PublicKeyAggregationRequest.Builder.class); } public static final int PUBLIC_KEYS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList publicKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return A list containing the publicKeys. */ public com.google.protobuf.ProtocolStringList getPublicKeysList() { return publicKeys_; } /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return The count of publicKeys. */ public int getPublicKeysCount() { return publicKeys_.size(); } /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index of the element to return. * @return The publicKeys at the given index. */ public java.lang.String getPublicKeys(int index) { return publicKeys_.get(index); } /** *
     * List of BLS public keys to be aggregated.
     * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index of the value to return. * @return The bytes of the publicKeys at the given index. */ public com.google.protobuf.ByteString getPublicKeysBytes(int index) { return publicKeys_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < publicKeys_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 1, publicKeys_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < publicKeys_.size(); i++) { dataSize += computeStringSizeNoTag(publicKeys_.getRaw(i)); } size += dataSize; size += 1 * getPublicKeysList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.PublicKeyAggregationRequest)) { return super.equals(obj); } pactus.UtilsOuterClass.PublicKeyAggregationRequest other = (pactus.UtilsOuterClass.PublicKeyAggregationRequest) obj; if (!getPublicKeysList() .equals(other.getPublicKeysList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getPublicKeysCount() > 0) { hash = (37 * hash) + PUBLIC_KEYS_FIELD_NUMBER; hash = (53 * hash) + getPublicKeysList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.PublicKeyAggregationRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for aggregating multiple BLS public keys.
     * 
* * Protobuf type {@code pactus.PublicKeyAggregationRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PublicKeyAggregationRequest) pactus.UtilsOuterClass.PublicKeyAggregationRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.PublicKeyAggregationRequest.class, pactus.UtilsOuterClass.PublicKeyAggregationRequest.Builder.class); } // Construct using pactus.UtilsOuterClass.PublicKeyAggregationRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; publicKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationRequest_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationRequest getDefaultInstanceForType() { return pactus.UtilsOuterClass.PublicKeyAggregationRequest.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationRequest build() { pactus.UtilsOuterClass.PublicKeyAggregationRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationRequest buildPartial() { pactus.UtilsOuterClass.PublicKeyAggregationRequest result = new pactus.UtilsOuterClass.PublicKeyAggregationRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.PublicKeyAggregationRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { publicKeys_.makeImmutable(); result.publicKeys_ = publicKeys_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.PublicKeyAggregationRequest) { return mergeFrom((pactus.UtilsOuterClass.PublicKeyAggregationRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.PublicKeyAggregationRequest other) { if (other == pactus.UtilsOuterClass.PublicKeyAggregationRequest.getDefaultInstance()) return this; if (!other.publicKeys_.isEmpty()) { if (publicKeys_.isEmpty()) { publicKeys_ = other.publicKeys_; bitField0_ |= 0x00000001; } else { ensurePublicKeysIsMutable(); publicKeys_.addAll(other.publicKeys_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); ensurePublicKeysIsMutable(); publicKeys_.add(s); break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.LazyStringArrayList publicKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensurePublicKeysIsMutable() { if (!publicKeys_.isModifiable()) { publicKeys_ = new com.google.protobuf.LazyStringArrayList(publicKeys_); } bitField0_ |= 0x00000001; } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return A list containing the publicKeys. */ public com.google.protobuf.ProtocolStringList getPublicKeysList() { publicKeys_.makeImmutable(); return publicKeys_; } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return The count of publicKeys. */ public int getPublicKeysCount() { return publicKeys_.size(); } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index of the element to return. * @return The publicKeys at the given index. */ public java.lang.String getPublicKeys(int index) { return publicKeys_.get(index); } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index of the value to return. * @return The bytes of the publicKeys at the given index. */ public com.google.protobuf.ByteString getPublicKeysBytes(int index) { return publicKeys_.getByteString(index); } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param index The index to set the value at. * @param value The publicKeys to set. * @return This builder for chaining. */ public Builder setPublicKeys( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePublicKeysIsMutable(); publicKeys_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param value The publicKeys to add. * @return This builder for chaining. */ public Builder addPublicKeys( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePublicKeysIsMutable(); publicKeys_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param values The publicKeys to add. * @return This builder for chaining. */ public Builder addAllPublicKeys( java.lang.Iterable values) { ensurePublicKeysIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, publicKeys_); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @return This builder for chaining. */ public Builder clearPublicKeys() { publicKeys_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001);; onChanged(); return this; } /** *
       * List of BLS public keys to be aggregated.
       * 
* * repeated string public_keys = 1 [json_name = "publicKeys"]; * @param value The bytes of the publicKeys to add. * @return This builder for chaining. */ public Builder addPublicKeysBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensurePublicKeysIsMutable(); publicKeys_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PublicKeyAggregationRequest) } // @@protoc_insertion_point(class_scope:pactus.PublicKeyAggregationRequest) private static final pactus.UtilsOuterClass.PublicKeyAggregationRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.PublicKeyAggregationRequest(); } public static pactus.UtilsOuterClass.PublicKeyAggregationRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PublicKeyAggregationRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface PublicKeyAggregationResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.PublicKeyAggregationResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The aggregated BLS public key.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The aggregated BLS public key.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); /** *
     * The blockchain address derived from the aggregated public key.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The blockchain address derived from the aggregated public key.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Response message contains the aggregated BLS public key result.
   * 
* * Protobuf type {@code pactus.PublicKeyAggregationResponse} */ public static final class PublicKeyAggregationResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.PublicKeyAggregationResponse) PublicKeyAggregationResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "PublicKeyAggregationResponse"); } // Use PublicKeyAggregationResponse.newBuilder() to construct. private PublicKeyAggregationResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private PublicKeyAggregationResponse() { publicKey_ = ""; address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.PublicKeyAggregationResponse.class, pactus.UtilsOuterClass.PublicKeyAggregationResponse.Builder.class); } public static final int PUBLIC_KEY_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The aggregated BLS public key.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The aggregated BLS public key.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The blockchain address derived from the aggregated public key.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The blockchain address derived from the aggregated public key.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, publicKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, publicKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.PublicKeyAggregationResponse)) { return super.equals(obj); } pactus.UtilsOuterClass.PublicKeyAggregationResponse other = (pactus.UtilsOuterClass.PublicKeyAggregationResponse) obj; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.PublicKeyAggregationResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the aggregated BLS public key result.
     * 
* * Protobuf type {@code pactus.PublicKeyAggregationResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.PublicKeyAggregationResponse) pactus.UtilsOuterClass.PublicKeyAggregationResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.PublicKeyAggregationResponse.class, pactus.UtilsOuterClass.PublicKeyAggregationResponse.Builder.class); } // Construct using pactus.UtilsOuterClass.PublicKeyAggregationResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; publicKey_ = ""; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_PublicKeyAggregationResponse_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationResponse getDefaultInstanceForType() { return pactus.UtilsOuterClass.PublicKeyAggregationResponse.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationResponse build() { pactus.UtilsOuterClass.PublicKeyAggregationResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationResponse buildPartial() { pactus.UtilsOuterClass.PublicKeyAggregationResponse result = new pactus.UtilsOuterClass.PublicKeyAggregationResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.PublicKeyAggregationResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.publicKey_ = publicKey_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.PublicKeyAggregationResponse) { return mergeFrom((pactus.UtilsOuterClass.PublicKeyAggregationResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.PublicKeyAggregationResponse other) { if (other == pactus.UtilsOuterClass.PublicKeyAggregationResponse.getDefaultInstance()) return this; if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object publicKey_ = ""; /** *
       * The aggregated BLS public key.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The aggregated BLS public key.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The aggregated BLS public key.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The aggregated BLS public key.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The aggregated BLS public key.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The blockchain address derived from the aggregated public key.
       * 
* * string address = 2 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The blockchain address derived from the aggregated public key.
       * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The blockchain address derived from the aggregated public key.
       * 
* * string address = 2 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The blockchain address derived from the aggregated public key.
       * 
* * string address = 2 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The blockchain address derived from the aggregated public key.
       * 
* * string address = 2 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.PublicKeyAggregationResponse) } // @@protoc_insertion_point(class_scope:pactus.PublicKeyAggregationResponse) private static final pactus.UtilsOuterClass.PublicKeyAggregationResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.PublicKeyAggregationResponse(); } public static pactus.UtilsOuterClass.PublicKeyAggregationResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public PublicKeyAggregationResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.PublicKeyAggregationResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignatureAggregationRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignatureAggregationRequest) com.google.protobuf.MessageOrBuilder { /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return A list containing the signatures. */ java.util.List getSignaturesList(); /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return The count of signatures. */ int getSignaturesCount(); /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index of the element to return. * @return The signatures at the given index. */ java.lang.String getSignatures(int index); /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index of the value to return. * @return The bytes of the signatures at the given index. */ com.google.protobuf.ByteString getSignaturesBytes(int index); } /** *
   * Request message for aggregating multiple BLS signatures.
   * 
* * Protobuf type {@code pactus.SignatureAggregationRequest} */ public static final class SignatureAggregationRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignatureAggregationRequest) SignatureAggregationRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignatureAggregationRequest"); } // Use SignatureAggregationRequest.newBuilder() to construct. private SignatureAggregationRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignatureAggregationRequest() { signatures_ = com.google.protobuf.LazyStringArrayList.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignatureAggregationRequest.class, pactus.UtilsOuterClass.SignatureAggregationRequest.Builder.class); } public static final int SIGNATURES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList signatures_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return A list containing the signatures. */ public com.google.protobuf.ProtocolStringList getSignaturesList() { return signatures_; } /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return The count of signatures. */ public int getSignaturesCount() { return signatures_.size(); } /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index of the element to return. * @return The signatures at the given index. */ public java.lang.String getSignatures(int index) { return signatures_.get(index); } /** *
     * List of BLS signatures to be aggregated.
     * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index of the value to return. * @return The bytes of the signatures at the given index. */ public com.google.protobuf.ByteString getSignaturesBytes(int index) { return signatures_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < signatures_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 1, signatures_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < signatures_.size(); i++) { dataSize += computeStringSizeNoTag(signatures_.getRaw(i)); } size += dataSize; size += 1 * getSignaturesList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.SignatureAggregationRequest)) { return super.equals(obj); } pactus.UtilsOuterClass.SignatureAggregationRequest other = (pactus.UtilsOuterClass.SignatureAggregationRequest) obj; if (!getSignaturesList() .equals(other.getSignaturesList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getSignaturesCount() > 0) { hash = (37 * hash) + SIGNATURES_FIELD_NUMBER; hash = (53 * hash) + getSignaturesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignatureAggregationRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.SignatureAggregationRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for aggregating multiple BLS signatures.
     * 
* * Protobuf type {@code pactus.SignatureAggregationRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignatureAggregationRequest) pactus.UtilsOuterClass.SignatureAggregationRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignatureAggregationRequest.class, pactus.UtilsOuterClass.SignatureAggregationRequest.Builder.class); } // Construct using pactus.UtilsOuterClass.SignatureAggregationRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; signatures_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationRequest_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationRequest getDefaultInstanceForType() { return pactus.UtilsOuterClass.SignatureAggregationRequest.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationRequest build() { pactus.UtilsOuterClass.SignatureAggregationRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationRequest buildPartial() { pactus.UtilsOuterClass.SignatureAggregationRequest result = new pactus.UtilsOuterClass.SignatureAggregationRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.SignatureAggregationRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { signatures_.makeImmutable(); result.signatures_ = signatures_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.SignatureAggregationRequest) { return mergeFrom((pactus.UtilsOuterClass.SignatureAggregationRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.SignatureAggregationRequest other) { if (other == pactus.UtilsOuterClass.SignatureAggregationRequest.getDefaultInstance()) return this; if (!other.signatures_.isEmpty()) { if (signatures_.isEmpty()) { signatures_ = other.signatures_; bitField0_ |= 0x00000001; } else { ensureSignaturesIsMutable(); signatures_.addAll(other.signatures_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); ensureSignaturesIsMutable(); signatures_.add(s); break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.LazyStringArrayList signatures_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureSignaturesIsMutable() { if (!signatures_.isModifiable()) { signatures_ = new com.google.protobuf.LazyStringArrayList(signatures_); } bitField0_ |= 0x00000001; } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return A list containing the signatures. */ public com.google.protobuf.ProtocolStringList getSignaturesList() { signatures_.makeImmutable(); return signatures_; } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return The count of signatures. */ public int getSignaturesCount() { return signatures_.size(); } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index of the element to return. * @return The signatures at the given index. */ public java.lang.String getSignatures(int index) { return signatures_.get(index); } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index of the value to return. * @return The bytes of the signatures at the given index. */ public com.google.protobuf.ByteString getSignaturesBytes(int index) { return signatures_.getByteString(index); } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param index The index to set the value at. * @param value The signatures to set. * @return This builder for chaining. */ public Builder setSignatures( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSignaturesIsMutable(); signatures_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param value The signatures to add. * @return This builder for chaining. */ public Builder addSignatures( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSignaturesIsMutable(); signatures_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param values The signatures to add. * @return This builder for chaining. */ public Builder addAllSignatures( java.lang.Iterable values) { ensureSignaturesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, signatures_); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @return This builder for chaining. */ public Builder clearSignatures() { signatures_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001);; onChanged(); return this; } /** *
       * List of BLS signatures to be aggregated.
       * 
* * repeated string signatures = 1 [json_name = "signatures"]; * @param value The bytes of the signatures to add. * @return This builder for chaining. */ public Builder addSignaturesBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureSignaturesIsMutable(); signatures_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignatureAggregationRequest) } // @@protoc_insertion_point(class_scope:pactus.SignatureAggregationRequest) private static final pactus.UtilsOuterClass.SignatureAggregationRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.SignatureAggregationRequest(); } public static pactus.UtilsOuterClass.SignatureAggregationRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignatureAggregationRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignatureAggregationResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignatureAggregationResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The aggregated BLS signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The aggregated BLS signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); } /** *
   * Response message contains the aggregated BLS signature.
   * 
* * Protobuf type {@code pactus.SignatureAggregationResponse} */ public static final class SignatureAggregationResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignatureAggregationResponse) SignatureAggregationResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignatureAggregationResponse"); } // Use SignatureAggregationResponse.newBuilder() to construct. private SignatureAggregationResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignatureAggregationResponse() { signature_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignatureAggregationResponse.class, pactus.UtilsOuterClass.SignatureAggregationResponse.Builder.class); } public static final int SIGNATURE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The aggregated BLS signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The aggregated BLS signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, signature_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, signature_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.UtilsOuterClass.SignatureAggregationResponse)) { return super.equals(obj); } pactus.UtilsOuterClass.SignatureAggregationResponse other = (pactus.UtilsOuterClass.SignatureAggregationResponse) obj; if (!getSignature() .equals(other.getSignature())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.UtilsOuterClass.SignatureAggregationResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.UtilsOuterClass.SignatureAggregationResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the aggregated BLS signature.
     * 
* * Protobuf type {@code pactus.SignatureAggregationResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignatureAggregationResponse) pactus.UtilsOuterClass.SignatureAggregationResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.UtilsOuterClass.SignatureAggregationResponse.class, pactus.UtilsOuterClass.SignatureAggregationResponse.Builder.class); } // Construct using pactus.UtilsOuterClass.SignatureAggregationResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; signature_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.UtilsOuterClass.internal_static_pactus_SignatureAggregationResponse_descriptor; } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationResponse getDefaultInstanceForType() { return pactus.UtilsOuterClass.SignatureAggregationResponse.getDefaultInstance(); } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationResponse build() { pactus.UtilsOuterClass.SignatureAggregationResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationResponse buildPartial() { pactus.UtilsOuterClass.SignatureAggregationResponse result = new pactus.UtilsOuterClass.SignatureAggregationResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.UtilsOuterClass.SignatureAggregationResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.signature_ = signature_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.UtilsOuterClass.SignatureAggregationResponse) { return mergeFrom((pactus.UtilsOuterClass.SignatureAggregationResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.UtilsOuterClass.SignatureAggregationResponse other) { if (other == pactus.UtilsOuterClass.SignatureAggregationResponse.getDefaultInstance()) return this; if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object signature_ = ""; /** *
       * The aggregated BLS signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The aggregated BLS signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The aggregated BLS signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The aggregated BLS signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The aggregated BLS signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignatureAggregationResponse) } // @@protoc_insertion_point(class_scope:pactus.SignatureAggregationResponse) private static final pactus.UtilsOuterClass.SignatureAggregationResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.UtilsOuterClass.SignatureAggregationResponse(); } public static pactus.UtilsOuterClass.SignatureAggregationResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignatureAggregationResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.UtilsOuterClass.SignatureAggregationResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignMessageWithPrivateKeyRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignMessageWithPrivateKeyRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignMessageWithPrivateKeyResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignMessageWithPrivateKeyResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_VerifyMessageRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_VerifyMessageRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_VerifyMessageResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_VerifyMessageResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PublicKeyAggregationRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PublicKeyAggregationRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_PublicKeyAggregationResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_PublicKeyAggregationResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignatureAggregationRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignatureAggregationRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignatureAggregationResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignatureAggregationResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\013utils.proto\022\006pactus\"]\n SignMessageWith" + "PrivateKeyRequest\022\037\n\013private_key\030\001 \001(\tR\n" + "privateKey\022\030\n\007message\030\002 \001(\tR\007message\"A\n!" + "SignMessageWithPrivateKeyResponse\022\034\n\tsig" + "nature\030\001 \001(\tR\tsignature\"m\n\024VerifyMessage" + "Request\022\030\n\007message\030\001 \001(\tR\007message\022\034\n\tsig" + "nature\030\002 \001(\tR\tsignature\022\035\n\npublic_key\030\003 " + "\001(\tR\tpublicKey\"2\n\025VerifyMessageResponse\022" + "\031\n\010is_valid\030\001 \001(\010R\007isValid\">\n\033PublicKeyA" + "ggregationRequest\022\037\n\013public_keys\030\001 \003(\tR\n" + "publicKeys\"W\n\034PublicKeyAggregationRespon" + "se\022\035\n\npublic_key\030\001 \001(\tR\tpublicKey\022\030\n\007add" + "ress\030\002 \001(\tR\007address\"=\n\033SignatureAggregat" + "ionRequest\022\036\n\nsignatures\030\001 \003(\tR\nsignatur" + "es\"<\n\034SignatureAggregationResponse\022\034\n\tsi" + "gnature\030\001 \001(\tR\tsignature2\215\003\n\005Utils\022p\n\031Si" + "gnMessageWithPrivateKey\022(.pactus.SignMes" + "sageWithPrivateKeyRequest\032).pactus.SignM" + "essageWithPrivateKeyResponse\022L\n\rVerifyMe" + "ssage\022\034.pactus.VerifyMessageRequest\032\035.pa" + "ctus.VerifyMessageResponse\022a\n\024PublicKeyA" + "ggregation\022#.pactus.PublicKeyAggregation" + "Request\032$.pactus.PublicKeyAggregationRes" + "ponse\022a\n\024SignatureAggregation\022#.pactus.S" + "ignatureAggregationRequest\032$.pactus.Sign" + "atureAggregationResponseB:\n\006pactusZ0gith" + "ub.com/pactus-project/pactus/www/grpc/pa" + "ctusb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_pactus_SignMessageWithPrivateKeyRequest_descriptor = getDescriptor().getMessageType(0); internal_static_pactus_SignMessageWithPrivateKeyRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignMessageWithPrivateKeyRequest_descriptor, new java.lang.String[] { "PrivateKey", "Message", }); internal_static_pactus_SignMessageWithPrivateKeyResponse_descriptor = getDescriptor().getMessageType(1); internal_static_pactus_SignMessageWithPrivateKeyResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignMessageWithPrivateKeyResponse_descriptor, new java.lang.String[] { "Signature", }); internal_static_pactus_VerifyMessageRequest_descriptor = getDescriptor().getMessageType(2); internal_static_pactus_VerifyMessageRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_VerifyMessageRequest_descriptor, new java.lang.String[] { "Message", "Signature", "PublicKey", }); internal_static_pactus_VerifyMessageResponse_descriptor = getDescriptor().getMessageType(3); internal_static_pactus_VerifyMessageResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_VerifyMessageResponse_descriptor, new java.lang.String[] { "IsValid", }); internal_static_pactus_PublicKeyAggregationRequest_descriptor = getDescriptor().getMessageType(4); internal_static_pactus_PublicKeyAggregationRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PublicKeyAggregationRequest_descriptor, new java.lang.String[] { "PublicKeys", }); internal_static_pactus_PublicKeyAggregationResponse_descriptor = getDescriptor().getMessageType(5); internal_static_pactus_PublicKeyAggregationResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_PublicKeyAggregationResponse_descriptor, new java.lang.String[] { "PublicKey", "Address", }); internal_static_pactus_SignatureAggregationRequest_descriptor = getDescriptor().getMessageType(6); internal_static_pactus_SignatureAggregationRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignatureAggregationRequest_descriptor, new java.lang.String[] { "Signatures", }); internal_static_pactus_SignatureAggregationResponse_descriptor = getDescriptor().getMessageType(7); internal_static_pactus_SignatureAggregationResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignatureAggregationResponse_descriptor, new java.lang.String[] { "Signature", }); descriptor.resolveAllFeaturesImmutable(); } // @@protoc_insertion_point(outer_class_scope) } ================================================ FILE: www/grpc/gen/java/pactus/WalletGrpc.java ================================================ package pactus; import static io.grpc.MethodDescriptor.generateFullMethodName; /** *
 * Wallet service provides RPC methods for wallet management operations.
 * 
*/ @io.grpc.stub.annotations.GrpcGenerated public final class WalletGrpc { private WalletGrpc() {} public static final java.lang.String SERVICE_NAME = "pactus.Wallet"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor getCreateWalletMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateWallet", requestType = pactus.WalletOuterClass.CreateWalletRequest.class, responseType = pactus.WalletOuterClass.CreateWalletResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getCreateWalletMethod() { io.grpc.MethodDescriptor getCreateWalletMethod; if ((getCreateWalletMethod = WalletGrpc.getCreateWalletMethod) == null) { synchronized (WalletGrpc.class) { if ((getCreateWalletMethod = WalletGrpc.getCreateWalletMethod) == null) { WalletGrpc.getCreateWalletMethod = getCreateWalletMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateWallet")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.CreateWalletRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.CreateWalletResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("CreateWallet")) .build(); } } } return getCreateWalletMethod; } private static volatile io.grpc.MethodDescriptor getRestoreWalletMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "RestoreWallet", requestType = pactus.WalletOuterClass.RestoreWalletRequest.class, responseType = pactus.WalletOuterClass.RestoreWalletResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getRestoreWalletMethod() { io.grpc.MethodDescriptor getRestoreWalletMethod; if ((getRestoreWalletMethod = WalletGrpc.getRestoreWalletMethod) == null) { synchronized (WalletGrpc.class) { if ((getRestoreWalletMethod = WalletGrpc.getRestoreWalletMethod) == null) { WalletGrpc.getRestoreWalletMethod = getRestoreWalletMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "RestoreWallet")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.RestoreWalletRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.RestoreWalletResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("RestoreWallet")) .build(); } } } return getRestoreWalletMethod; } private static volatile io.grpc.MethodDescriptor getLoadWalletMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "LoadWallet", requestType = pactus.WalletOuterClass.LoadWalletRequest.class, responseType = pactus.WalletOuterClass.LoadWalletResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getLoadWalletMethod() { io.grpc.MethodDescriptor getLoadWalletMethod; if ((getLoadWalletMethod = WalletGrpc.getLoadWalletMethod) == null) { synchronized (WalletGrpc.class) { if ((getLoadWalletMethod = WalletGrpc.getLoadWalletMethod) == null) { WalletGrpc.getLoadWalletMethod = getLoadWalletMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "LoadWallet")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.LoadWalletRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.LoadWalletResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("LoadWallet")) .build(); } } } return getLoadWalletMethod; } private static volatile io.grpc.MethodDescriptor getUnloadWalletMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UnloadWallet", requestType = pactus.WalletOuterClass.UnloadWalletRequest.class, responseType = pactus.WalletOuterClass.UnloadWalletResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getUnloadWalletMethod() { io.grpc.MethodDescriptor getUnloadWalletMethod; if ((getUnloadWalletMethod = WalletGrpc.getUnloadWalletMethod) == null) { synchronized (WalletGrpc.class) { if ((getUnloadWalletMethod = WalletGrpc.getUnloadWalletMethod) == null) { WalletGrpc.getUnloadWalletMethod = getUnloadWalletMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "UnloadWallet")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.UnloadWalletRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.UnloadWalletResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("UnloadWallet")) .build(); } } } return getUnloadWalletMethod; } private static volatile io.grpc.MethodDescriptor getListWalletsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListWallets", requestType = pactus.WalletOuterClass.ListWalletsRequest.class, responseType = pactus.WalletOuterClass.ListWalletsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getListWalletsMethod() { io.grpc.MethodDescriptor getListWalletsMethod; if ((getListWalletsMethod = WalletGrpc.getListWalletsMethod) == null) { synchronized (WalletGrpc.class) { if ((getListWalletsMethod = WalletGrpc.getListWalletsMethod) == null) { WalletGrpc.getListWalletsMethod = getListWalletsMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListWallets")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.ListWalletsRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.ListWalletsResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("ListWallets")) .build(); } } } return getListWalletsMethod; } private static volatile io.grpc.MethodDescriptor getGetWalletInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetWalletInfo", requestType = pactus.WalletOuterClass.GetWalletInfoRequest.class, responseType = pactus.WalletOuterClass.GetWalletInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetWalletInfoMethod() { io.grpc.MethodDescriptor getGetWalletInfoMethod; if ((getGetWalletInfoMethod = WalletGrpc.getGetWalletInfoMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetWalletInfoMethod = WalletGrpc.getGetWalletInfoMethod) == null) { WalletGrpc.getGetWalletInfoMethod = getGetWalletInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetWalletInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetWalletInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetWalletInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetWalletInfo")) .build(); } } } return getGetWalletInfoMethod; } private static volatile io.grpc.MethodDescriptor getUpdatePasswordMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdatePassword", requestType = pactus.WalletOuterClass.UpdatePasswordRequest.class, responseType = pactus.WalletOuterClass.UpdatePasswordResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getUpdatePasswordMethod() { io.grpc.MethodDescriptor getUpdatePasswordMethod; if ((getUpdatePasswordMethod = WalletGrpc.getUpdatePasswordMethod) == null) { synchronized (WalletGrpc.class) { if ((getUpdatePasswordMethod = WalletGrpc.getUpdatePasswordMethod) == null) { WalletGrpc.getUpdatePasswordMethod = getUpdatePasswordMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdatePassword")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.UpdatePasswordRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.UpdatePasswordResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("UpdatePassword")) .build(); } } } return getUpdatePasswordMethod; } private static volatile io.grpc.MethodDescriptor getGetTotalBalanceMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetTotalBalance", requestType = pactus.WalletOuterClass.GetTotalBalanceRequest.class, responseType = pactus.WalletOuterClass.GetTotalBalanceResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetTotalBalanceMethod() { io.grpc.MethodDescriptor getGetTotalBalanceMethod; if ((getGetTotalBalanceMethod = WalletGrpc.getGetTotalBalanceMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetTotalBalanceMethod = WalletGrpc.getGetTotalBalanceMethod) == null) { WalletGrpc.getGetTotalBalanceMethod = getGetTotalBalanceMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetTotalBalance")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetTotalBalanceRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetTotalBalanceResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetTotalBalance")) .build(); } } } return getGetTotalBalanceMethod; } private static volatile io.grpc.MethodDescriptor getGetTotalStakeMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetTotalStake", requestType = pactus.WalletOuterClass.GetTotalStakeRequest.class, responseType = pactus.WalletOuterClass.GetTotalStakeResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetTotalStakeMethod() { io.grpc.MethodDescriptor getGetTotalStakeMethod; if ((getGetTotalStakeMethod = WalletGrpc.getGetTotalStakeMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetTotalStakeMethod = WalletGrpc.getGetTotalStakeMethod) == null) { WalletGrpc.getGetTotalStakeMethod = getGetTotalStakeMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetTotalStake")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetTotalStakeRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetTotalStakeResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetTotalStake")) .build(); } } } return getGetTotalStakeMethod; } private static volatile io.grpc.MethodDescriptor getGetValidatorAddressMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetValidatorAddress", requestType = pactus.WalletOuterClass.GetValidatorAddressRequest.class, responseType = pactus.WalletOuterClass.GetValidatorAddressResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetValidatorAddressMethod() { io.grpc.MethodDescriptor getGetValidatorAddressMethod; if ((getGetValidatorAddressMethod = WalletGrpc.getGetValidatorAddressMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetValidatorAddressMethod = WalletGrpc.getGetValidatorAddressMethod) == null) { WalletGrpc.getGetValidatorAddressMethod = getGetValidatorAddressMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetValidatorAddress")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetValidatorAddressRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetValidatorAddressResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetValidatorAddress")) .build(); } } } return getGetValidatorAddressMethod; } private static volatile io.grpc.MethodDescriptor getGetAddressInfoMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetAddressInfo", requestType = pactus.WalletOuterClass.GetAddressInfoRequest.class, responseType = pactus.WalletOuterClass.GetAddressInfoResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetAddressInfoMethod() { io.grpc.MethodDescriptor getGetAddressInfoMethod; if ((getGetAddressInfoMethod = WalletGrpc.getGetAddressInfoMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetAddressInfoMethod = WalletGrpc.getGetAddressInfoMethod) == null) { WalletGrpc.getGetAddressInfoMethod = getGetAddressInfoMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetAddressInfo")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetAddressInfoRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetAddressInfoResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetAddressInfo")) .build(); } } } return getGetAddressInfoMethod; } private static volatile io.grpc.MethodDescriptor getSetAddressLabelMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SetAddressLabel", requestType = pactus.WalletOuterClass.SetAddressLabelRequest.class, responseType = pactus.WalletOuterClass.SetAddressLabelResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getSetAddressLabelMethod() { io.grpc.MethodDescriptor getSetAddressLabelMethod; if ((getSetAddressLabelMethod = WalletGrpc.getSetAddressLabelMethod) == null) { synchronized (WalletGrpc.class) { if ((getSetAddressLabelMethod = WalletGrpc.getSetAddressLabelMethod) == null) { WalletGrpc.getSetAddressLabelMethod = getSetAddressLabelMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetAddressLabel")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SetAddressLabelRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SetAddressLabelResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("SetAddressLabel")) .build(); } } } return getSetAddressLabelMethod; } private static volatile io.grpc.MethodDescriptor getGetNewAddressMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetNewAddress", requestType = pactus.WalletOuterClass.GetNewAddressRequest.class, responseType = pactus.WalletOuterClass.GetNewAddressResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetNewAddressMethod() { io.grpc.MethodDescriptor getGetNewAddressMethod; if ((getGetNewAddressMethod = WalletGrpc.getGetNewAddressMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetNewAddressMethod = WalletGrpc.getGetNewAddressMethod) == null) { WalletGrpc.getGetNewAddressMethod = getGetNewAddressMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetNewAddress")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetNewAddressRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetNewAddressResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetNewAddress")) .build(); } } } return getGetNewAddressMethod; } private static volatile io.grpc.MethodDescriptor getListAddressesMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListAddresses", requestType = pactus.WalletOuterClass.ListAddressesRequest.class, responseType = pactus.WalletOuterClass.ListAddressesResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getListAddressesMethod() { io.grpc.MethodDescriptor getListAddressesMethod; if ((getListAddressesMethod = WalletGrpc.getListAddressesMethod) == null) { synchronized (WalletGrpc.class) { if ((getListAddressesMethod = WalletGrpc.getListAddressesMethod) == null) { WalletGrpc.getListAddressesMethod = getListAddressesMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListAddresses")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.ListAddressesRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.ListAddressesResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("ListAddresses")) .build(); } } } return getListAddressesMethod; } private static volatile io.grpc.MethodDescriptor getSignMessageMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SignMessage", requestType = pactus.WalletOuterClass.SignMessageRequest.class, responseType = pactus.WalletOuterClass.SignMessageResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getSignMessageMethod() { io.grpc.MethodDescriptor getSignMessageMethod; if ((getSignMessageMethod = WalletGrpc.getSignMessageMethod) == null) { synchronized (WalletGrpc.class) { if ((getSignMessageMethod = WalletGrpc.getSignMessageMethod) == null) { WalletGrpc.getSignMessageMethod = getSignMessageMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SignMessage")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SignMessageRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SignMessageResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("SignMessage")) .build(); } } } return getSignMessageMethod; } private static volatile io.grpc.MethodDescriptor getSignRawTransactionMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SignRawTransaction", requestType = pactus.WalletOuterClass.SignRawTransactionRequest.class, responseType = pactus.WalletOuterClass.SignRawTransactionResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getSignRawTransactionMethod() { io.grpc.MethodDescriptor getSignRawTransactionMethod; if ((getSignRawTransactionMethod = WalletGrpc.getSignRawTransactionMethod) == null) { synchronized (WalletGrpc.class) { if ((getSignRawTransactionMethod = WalletGrpc.getSignRawTransactionMethod) == null) { WalletGrpc.getSignRawTransactionMethod = getSignRawTransactionMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SignRawTransaction")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SignRawTransactionRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SignRawTransactionResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("SignRawTransaction")) .build(); } } } return getSignRawTransactionMethod; } private static volatile io.grpc.MethodDescriptor getListTransactionsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListTransactions", requestType = pactus.WalletOuterClass.ListTransactionsRequest.class, responseType = pactus.WalletOuterClass.ListTransactionsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getListTransactionsMethod() { io.grpc.MethodDescriptor getListTransactionsMethod; if ((getListTransactionsMethod = WalletGrpc.getListTransactionsMethod) == null) { synchronized (WalletGrpc.class) { if ((getListTransactionsMethod = WalletGrpc.getListTransactionsMethod) == null) { WalletGrpc.getListTransactionsMethod = getListTransactionsMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListTransactions")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.ListTransactionsRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.ListTransactionsResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("ListTransactions")) .build(); } } } return getListTransactionsMethod; } private static volatile io.grpc.MethodDescriptor getSetDefaultFeeMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SetDefaultFee", requestType = pactus.WalletOuterClass.SetDefaultFeeRequest.class, responseType = pactus.WalletOuterClass.SetDefaultFeeResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getSetDefaultFeeMethod() { io.grpc.MethodDescriptor getSetDefaultFeeMethod; if ((getSetDefaultFeeMethod = WalletGrpc.getSetDefaultFeeMethod) == null) { synchronized (WalletGrpc.class) { if ((getSetDefaultFeeMethod = WalletGrpc.getSetDefaultFeeMethod) == null) { WalletGrpc.getSetDefaultFeeMethod = getSetDefaultFeeMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetDefaultFee")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SetDefaultFeeRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.SetDefaultFeeResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("SetDefaultFee")) .build(); } } } return getSetDefaultFeeMethod; } private static volatile io.grpc.MethodDescriptor getGetMnemonicMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetMnemonic", requestType = pactus.WalletOuterClass.GetMnemonicRequest.class, responseType = pactus.WalletOuterClass.GetMnemonicResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetMnemonicMethod() { io.grpc.MethodDescriptor getGetMnemonicMethod; if ((getGetMnemonicMethod = WalletGrpc.getGetMnemonicMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetMnemonicMethod = WalletGrpc.getGetMnemonicMethod) == null) { WalletGrpc.getGetMnemonicMethod = getGetMnemonicMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetMnemonic")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetMnemonicRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetMnemonicResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetMnemonic")) .build(); } } } return getGetMnemonicMethod; } private static volatile io.grpc.MethodDescriptor getGetPrivateKeyMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetPrivateKey", requestType = pactus.WalletOuterClass.GetPrivateKeyRequest.class, responseType = pactus.WalletOuterClass.GetPrivateKeyResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor getGetPrivateKeyMethod() { io.grpc.MethodDescriptor getGetPrivateKeyMethod; if ((getGetPrivateKeyMethod = WalletGrpc.getGetPrivateKeyMethod) == null) { synchronized (WalletGrpc.class) { if ((getGetPrivateKeyMethod = WalletGrpc.getGetPrivateKeyMethod) == null) { WalletGrpc.getGetPrivateKeyMethod = getGetPrivateKeyMethod = io.grpc.MethodDescriptor.newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetPrivateKey")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetPrivateKeyRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( pactus.WalletOuterClass.GetPrivateKeyResponse.getDefaultInstance())) .setSchemaDescriptor(new WalletMethodDescriptorSupplier("GetPrivateKey")) .build(); } } } return getGetPrivateKeyMethod; } /** * Creates a new async stub that supports all call types for the service */ public static WalletStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public WalletStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletStub(channel, callOptions); } }; return WalletStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static WalletBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public WalletBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletBlockingV2Stub(channel, callOptions); } }; return WalletBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static WalletBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public WalletBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletBlockingStub(channel, callOptions); } }; return WalletBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static WalletFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory factory = new io.grpc.stub.AbstractStub.StubFactory() { @java.lang.Override public WalletFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletFutureStub(channel, callOptions); } }; return WalletFutureStub.newStub(factory, channel); } /** *
   * Wallet service provides RPC methods for wallet management operations.
   * 
*/ public interface AsyncService { /** *
     * CreateWallet creates a new wallet with the specified parameters.
     * 
*/ default void createWallet(pactus.WalletOuterClass.CreateWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCreateWalletMethod(), responseObserver); } /** *
     * RestoreWallet restores an existing wallet with the given mnemonic.
     * 
*/ default void restoreWallet(pactus.WalletOuterClass.RestoreWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getRestoreWalletMethod(), responseObserver); } /** *
     * LoadWallet loads an existing wallet with the given name.
     * deprecated: It will be removed in a future version.
     * 
*/ default void loadWallet(pactus.WalletOuterClass.LoadWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getLoadWalletMethod(), responseObserver); } /** *
     * UnloadWallet unloads a currently loaded wallet with the specified name.
     * deprecated: It will be removed in a future version.
     * 
*/ default void unloadWallet(pactus.WalletOuterClass.UnloadWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUnloadWalletMethod(), responseObserver); } /** *
     * ListWallets returns a list of all available wallets.
     * 
*/ default void listWallets(pactus.WalletOuterClass.ListWalletsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getListWalletsMethod(), responseObserver); } /** *
     * GetWalletInfo returns detailed information about a specific wallet.
     * 
*/ default void getWalletInfo(pactus.WalletOuterClass.GetWalletInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetWalletInfoMethod(), responseObserver); } /** *
     * UpdatePassword updates the password of an existing wallet.
     * 
*/ default void updatePassword(pactus.WalletOuterClass.UpdatePasswordRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getUpdatePasswordMethod(), responseObserver); } /** *
     * GetTotalBalance returns the total available balance of the wallet.
     * 
*/ default void getTotalBalance(pactus.WalletOuterClass.GetTotalBalanceRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetTotalBalanceMethod(), responseObserver); } /** *
     * GetTotalStake returns the total stake amount in the wallet.
     * 
*/ default void getTotalStake(pactus.WalletOuterClass.GetTotalStakeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetTotalStakeMethod(), responseObserver); } /** *
     * GetValidatorAddress retrieves the validator address associated with a public key.
     * Deprecated: Will move into utils.
     * 
*/ default void getValidatorAddress(pactus.WalletOuterClass.GetValidatorAddressRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetValidatorAddressMethod(), responseObserver); } /** *
     * GetAddressInfo returns detailed information about a specific address.
     * 
*/ default void getAddressInfo(pactus.WalletOuterClass.GetAddressInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetAddressInfoMethod(), responseObserver); } /** *
     * SetAddressLabel sets or updates the label for a given address.
     * 
*/ default void setAddressLabel(pactus.WalletOuterClass.SetAddressLabelRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetAddressLabelMethod(), responseObserver); } /** *
     * GetNewAddress generates a new address for the specified wallet.
     * 
*/ default void getNewAddress(pactus.WalletOuterClass.GetNewAddressRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetNewAddressMethod(), responseObserver); } /** *
     * ListAddresses returns all addresses in the specified wallet.
     * 
*/ default void listAddresses(pactus.WalletOuterClass.ListAddressesRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getListAddressesMethod(), responseObserver); } /** *
     * SignMessage signs an arbitrary message using a wallet's private key.
     * 
*/ default void signMessage(pactus.WalletOuterClass.SignMessageRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSignMessageMethod(), responseObserver); } /** *
     * SignRawTransaction signs a raw transaction for a specified wallet.
     * 
*/ default void signRawTransaction(pactus.WalletOuterClass.SignRawTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSignRawTransactionMethod(), responseObserver); } /** *
     * ListTransactions returns a list of transactions for a wallet,
     * optionally filtered by a specific address, with pagination support.
     * 
*/ default void listTransactions(pactus.WalletOuterClass.ListTransactionsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getListTransactionsMethod(), responseObserver); } /** *
     * SetDefaultFee sets the default fee for the wallet.
     * 
*/ default void setDefaultFee(pactus.WalletOuterClass.SetDefaultFeeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getSetDefaultFeeMethod(), responseObserver); } /** *
     * GetMnemonic returns the mnemonic (seed phrase) for the wallet.
     * 
*/ default void getMnemonic(pactus.WalletOuterClass.GetMnemonicRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetMnemonicMethod(), responseObserver); } /** *
     * GetPrivateKey returns the private key for a given address.
     * 
*/ default void getPrivateKey(pactus.WalletOuterClass.GetPrivateKeyRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetPrivateKeyMethod(), responseObserver); } } /** * Base class for the server implementation of the service Wallet. *
   * Wallet service provides RPC methods for wallet management operations.
   * 
*/ public static abstract class WalletImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return WalletGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service Wallet. *
   * Wallet service provides RPC methods for wallet management operations.
   * 
*/ public static final class WalletStub extends io.grpc.stub.AbstractAsyncStub { private WalletStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected WalletStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletStub(channel, callOptions); } /** *
     * CreateWallet creates a new wallet with the specified parameters.
     * 
*/ public void createWallet(pactus.WalletOuterClass.CreateWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateWalletMethod(), getCallOptions()), request, responseObserver); } /** *
     * RestoreWallet restores an existing wallet with the given mnemonic.
     * 
*/ public void restoreWallet(pactus.WalletOuterClass.RestoreWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getRestoreWalletMethod(), getCallOptions()), request, responseObserver); } /** *
     * LoadWallet loads an existing wallet with the given name.
     * deprecated: It will be removed in a future version.
     * 
*/ public void loadWallet(pactus.WalletOuterClass.LoadWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getLoadWalletMethod(), getCallOptions()), request, responseObserver); } /** *
     * UnloadWallet unloads a currently loaded wallet with the specified name.
     * deprecated: It will be removed in a future version.
     * 
*/ public void unloadWallet(pactus.WalletOuterClass.UnloadWalletRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUnloadWalletMethod(), getCallOptions()), request, responseObserver); } /** *
     * ListWallets returns a list of all available wallets.
     * 
*/ public void listWallets(pactus.WalletOuterClass.ListWalletsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListWalletsMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetWalletInfo returns detailed information about a specific wallet.
     * 
*/ public void getWalletInfo(pactus.WalletOuterClass.GetWalletInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetWalletInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * UpdatePassword updates the password of an existing wallet.
     * 
*/ public void updatePassword(pactus.WalletOuterClass.UpdatePasswordRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUpdatePasswordMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetTotalBalance returns the total available balance of the wallet.
     * 
*/ public void getTotalBalance(pactus.WalletOuterClass.GetTotalBalanceRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetTotalBalanceMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetTotalStake returns the total stake amount in the wallet.
     * 
*/ public void getTotalStake(pactus.WalletOuterClass.GetTotalStakeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetTotalStakeMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetValidatorAddress retrieves the validator address associated with a public key.
     * Deprecated: Will move into utils.
     * 
*/ public void getValidatorAddress(pactus.WalletOuterClass.GetValidatorAddressRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetValidatorAddressMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetAddressInfo returns detailed information about a specific address.
     * 
*/ public void getAddressInfo(pactus.WalletOuterClass.GetAddressInfoRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetAddressInfoMethod(), getCallOptions()), request, responseObserver); } /** *
     * SetAddressLabel sets or updates the label for a given address.
     * 
*/ public void setAddressLabel(pactus.WalletOuterClass.SetAddressLabelRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getSetAddressLabelMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetNewAddress generates a new address for the specified wallet.
     * 
*/ public void getNewAddress(pactus.WalletOuterClass.GetNewAddressRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetNewAddressMethod(), getCallOptions()), request, responseObserver); } /** *
     * ListAddresses returns all addresses in the specified wallet.
     * 
*/ public void listAddresses(pactus.WalletOuterClass.ListAddressesRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListAddressesMethod(), getCallOptions()), request, responseObserver); } /** *
     * SignMessage signs an arbitrary message using a wallet's private key.
     * 
*/ public void signMessage(pactus.WalletOuterClass.SignMessageRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getSignMessageMethod(), getCallOptions()), request, responseObserver); } /** *
     * SignRawTransaction signs a raw transaction for a specified wallet.
     * 
*/ public void signRawTransaction(pactus.WalletOuterClass.SignRawTransactionRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getSignRawTransactionMethod(), getCallOptions()), request, responseObserver); } /** *
     * ListTransactions returns a list of transactions for a wallet,
     * optionally filtered by a specific address, with pagination support.
     * 
*/ public void listTransactions(pactus.WalletOuterClass.ListTransactionsRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListTransactionsMethod(), getCallOptions()), request, responseObserver); } /** *
     * SetDefaultFee sets the default fee for the wallet.
     * 
*/ public void setDefaultFee(pactus.WalletOuterClass.SetDefaultFeeRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getSetDefaultFeeMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetMnemonic returns the mnemonic (seed phrase) for the wallet.
     * 
*/ public void getMnemonic(pactus.WalletOuterClass.GetMnemonicRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetMnemonicMethod(), getCallOptions()), request, responseObserver); } /** *
     * GetPrivateKey returns the private key for a given address.
     * 
*/ public void getPrivateKey(pactus.WalletOuterClass.GetPrivateKeyRequest request, io.grpc.stub.StreamObserver responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetPrivateKeyMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Wallet. *
   * Wallet service provides RPC methods for wallet management operations.
   * 
*/ public static final class WalletBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub { private WalletBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected WalletBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletBlockingV2Stub(channel, callOptions); } /** *
     * CreateWallet creates a new wallet with the specified parameters.
     * 
*/ public pactus.WalletOuterClass.CreateWalletResponse createWallet(pactus.WalletOuterClass.CreateWalletRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getCreateWalletMethod(), getCallOptions(), request); } /** *
     * RestoreWallet restores an existing wallet with the given mnemonic.
     * 
*/ public pactus.WalletOuterClass.RestoreWalletResponse restoreWallet(pactus.WalletOuterClass.RestoreWalletRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getRestoreWalletMethod(), getCallOptions(), request); } /** *
     * LoadWallet loads an existing wallet with the given name.
     * deprecated: It will be removed in a future version.
     * 
*/ public pactus.WalletOuterClass.LoadWalletResponse loadWallet(pactus.WalletOuterClass.LoadWalletRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getLoadWalletMethod(), getCallOptions(), request); } /** *
     * UnloadWallet unloads a currently loaded wallet with the specified name.
     * deprecated: It will be removed in a future version.
     * 
*/ public pactus.WalletOuterClass.UnloadWalletResponse unloadWallet(pactus.WalletOuterClass.UnloadWalletRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getUnloadWalletMethod(), getCallOptions(), request); } /** *
     * ListWallets returns a list of all available wallets.
     * 
*/ public pactus.WalletOuterClass.ListWalletsResponse listWallets(pactus.WalletOuterClass.ListWalletsRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getListWalletsMethod(), getCallOptions(), request); } /** *
     * GetWalletInfo returns detailed information about a specific wallet.
     * 
*/ public pactus.WalletOuterClass.GetWalletInfoResponse getWalletInfo(pactus.WalletOuterClass.GetWalletInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetWalletInfoMethod(), getCallOptions(), request); } /** *
     * UpdatePassword updates the password of an existing wallet.
     * 
*/ public pactus.WalletOuterClass.UpdatePasswordResponse updatePassword(pactus.WalletOuterClass.UpdatePasswordRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getUpdatePasswordMethod(), getCallOptions(), request); } /** *
     * GetTotalBalance returns the total available balance of the wallet.
     * 
*/ public pactus.WalletOuterClass.GetTotalBalanceResponse getTotalBalance(pactus.WalletOuterClass.GetTotalBalanceRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetTotalBalanceMethod(), getCallOptions(), request); } /** *
     * GetTotalStake returns the total stake amount in the wallet.
     * 
*/ public pactus.WalletOuterClass.GetTotalStakeResponse getTotalStake(pactus.WalletOuterClass.GetTotalStakeRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetTotalStakeMethod(), getCallOptions(), request); } /** *
     * GetValidatorAddress retrieves the validator address associated with a public key.
     * Deprecated: Will move into utils.
     * 
*/ public pactus.WalletOuterClass.GetValidatorAddressResponse getValidatorAddress(pactus.WalletOuterClass.GetValidatorAddressRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetValidatorAddressMethod(), getCallOptions(), request); } /** *
     * GetAddressInfo returns detailed information about a specific address.
     * 
*/ public pactus.WalletOuterClass.GetAddressInfoResponse getAddressInfo(pactus.WalletOuterClass.GetAddressInfoRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetAddressInfoMethod(), getCallOptions(), request); } /** *
     * SetAddressLabel sets or updates the label for a given address.
     * 
*/ public pactus.WalletOuterClass.SetAddressLabelResponse setAddressLabel(pactus.WalletOuterClass.SetAddressLabelRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getSetAddressLabelMethod(), getCallOptions(), request); } /** *
     * GetNewAddress generates a new address for the specified wallet.
     * 
*/ public pactus.WalletOuterClass.GetNewAddressResponse getNewAddress(pactus.WalletOuterClass.GetNewAddressRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetNewAddressMethod(), getCallOptions(), request); } /** *
     * ListAddresses returns all addresses in the specified wallet.
     * 
*/ public pactus.WalletOuterClass.ListAddressesResponse listAddresses(pactus.WalletOuterClass.ListAddressesRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getListAddressesMethod(), getCallOptions(), request); } /** *
     * SignMessage signs an arbitrary message using a wallet's private key.
     * 
*/ public pactus.WalletOuterClass.SignMessageResponse signMessage(pactus.WalletOuterClass.SignMessageRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getSignMessageMethod(), getCallOptions(), request); } /** *
     * SignRawTransaction signs a raw transaction for a specified wallet.
     * 
*/ public pactus.WalletOuterClass.SignRawTransactionResponse signRawTransaction(pactus.WalletOuterClass.SignRawTransactionRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getSignRawTransactionMethod(), getCallOptions(), request); } /** *
     * ListTransactions returns a list of transactions for a wallet,
     * optionally filtered by a specific address, with pagination support.
     * 
*/ public pactus.WalletOuterClass.ListTransactionsResponse listTransactions(pactus.WalletOuterClass.ListTransactionsRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getListTransactionsMethod(), getCallOptions(), request); } /** *
     * SetDefaultFee sets the default fee for the wallet.
     * 
*/ public pactus.WalletOuterClass.SetDefaultFeeResponse setDefaultFee(pactus.WalletOuterClass.SetDefaultFeeRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getSetDefaultFeeMethod(), getCallOptions(), request); } /** *
     * GetMnemonic returns the mnemonic (seed phrase) for the wallet.
     * 
*/ public pactus.WalletOuterClass.GetMnemonicResponse getMnemonic(pactus.WalletOuterClass.GetMnemonicRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetMnemonicMethod(), getCallOptions(), request); } /** *
     * GetPrivateKey returns the private key for a given address.
     * 
*/ public pactus.WalletOuterClass.GetPrivateKeyResponse getPrivateKey(pactus.WalletOuterClass.GetPrivateKeyRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetPrivateKeyMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Wallet. *
   * Wallet service provides RPC methods for wallet management operations.
   * 
*/ public static final class WalletBlockingStub extends io.grpc.stub.AbstractBlockingStub { private WalletBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected WalletBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletBlockingStub(channel, callOptions); } /** *
     * CreateWallet creates a new wallet with the specified parameters.
     * 
*/ public pactus.WalletOuterClass.CreateWalletResponse createWallet(pactus.WalletOuterClass.CreateWalletRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateWalletMethod(), getCallOptions(), request); } /** *
     * RestoreWallet restores an existing wallet with the given mnemonic.
     * 
*/ public pactus.WalletOuterClass.RestoreWalletResponse restoreWallet(pactus.WalletOuterClass.RestoreWalletRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getRestoreWalletMethod(), getCallOptions(), request); } /** *
     * LoadWallet loads an existing wallet with the given name.
     * deprecated: It will be removed in a future version.
     * 
*/ public pactus.WalletOuterClass.LoadWalletResponse loadWallet(pactus.WalletOuterClass.LoadWalletRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getLoadWalletMethod(), getCallOptions(), request); } /** *
     * UnloadWallet unloads a currently loaded wallet with the specified name.
     * deprecated: It will be removed in a future version.
     * 
*/ public pactus.WalletOuterClass.UnloadWalletResponse unloadWallet(pactus.WalletOuterClass.UnloadWalletRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUnloadWalletMethod(), getCallOptions(), request); } /** *
     * ListWallets returns a list of all available wallets.
     * 
*/ public pactus.WalletOuterClass.ListWalletsResponse listWallets(pactus.WalletOuterClass.ListWalletsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListWalletsMethod(), getCallOptions(), request); } /** *
     * GetWalletInfo returns detailed information about a specific wallet.
     * 
*/ public pactus.WalletOuterClass.GetWalletInfoResponse getWalletInfo(pactus.WalletOuterClass.GetWalletInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetWalletInfoMethod(), getCallOptions(), request); } /** *
     * UpdatePassword updates the password of an existing wallet.
     * 
*/ public pactus.WalletOuterClass.UpdatePasswordResponse updatePassword(pactus.WalletOuterClass.UpdatePasswordRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdatePasswordMethod(), getCallOptions(), request); } /** *
     * GetTotalBalance returns the total available balance of the wallet.
     * 
*/ public pactus.WalletOuterClass.GetTotalBalanceResponse getTotalBalance(pactus.WalletOuterClass.GetTotalBalanceRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetTotalBalanceMethod(), getCallOptions(), request); } /** *
     * GetTotalStake returns the total stake amount in the wallet.
     * 
*/ public pactus.WalletOuterClass.GetTotalStakeResponse getTotalStake(pactus.WalletOuterClass.GetTotalStakeRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetTotalStakeMethod(), getCallOptions(), request); } /** *
     * GetValidatorAddress retrieves the validator address associated with a public key.
     * Deprecated: Will move into utils.
     * 
*/ public pactus.WalletOuterClass.GetValidatorAddressResponse getValidatorAddress(pactus.WalletOuterClass.GetValidatorAddressRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetValidatorAddressMethod(), getCallOptions(), request); } /** *
     * GetAddressInfo returns detailed information about a specific address.
     * 
*/ public pactus.WalletOuterClass.GetAddressInfoResponse getAddressInfo(pactus.WalletOuterClass.GetAddressInfoRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetAddressInfoMethod(), getCallOptions(), request); } /** *
     * SetAddressLabel sets or updates the label for a given address.
     * 
*/ public pactus.WalletOuterClass.SetAddressLabelResponse setAddressLabel(pactus.WalletOuterClass.SetAddressLabelRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getSetAddressLabelMethod(), getCallOptions(), request); } /** *
     * GetNewAddress generates a new address for the specified wallet.
     * 
*/ public pactus.WalletOuterClass.GetNewAddressResponse getNewAddress(pactus.WalletOuterClass.GetNewAddressRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetNewAddressMethod(), getCallOptions(), request); } /** *
     * ListAddresses returns all addresses in the specified wallet.
     * 
*/ public pactus.WalletOuterClass.ListAddressesResponse listAddresses(pactus.WalletOuterClass.ListAddressesRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListAddressesMethod(), getCallOptions(), request); } /** *
     * SignMessage signs an arbitrary message using a wallet's private key.
     * 
*/ public pactus.WalletOuterClass.SignMessageResponse signMessage(pactus.WalletOuterClass.SignMessageRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getSignMessageMethod(), getCallOptions(), request); } /** *
     * SignRawTransaction signs a raw transaction for a specified wallet.
     * 
*/ public pactus.WalletOuterClass.SignRawTransactionResponse signRawTransaction(pactus.WalletOuterClass.SignRawTransactionRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getSignRawTransactionMethod(), getCallOptions(), request); } /** *
     * ListTransactions returns a list of transactions for a wallet,
     * optionally filtered by a specific address, with pagination support.
     * 
*/ public pactus.WalletOuterClass.ListTransactionsResponse listTransactions(pactus.WalletOuterClass.ListTransactionsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListTransactionsMethod(), getCallOptions(), request); } /** *
     * SetDefaultFee sets the default fee for the wallet.
     * 
*/ public pactus.WalletOuterClass.SetDefaultFeeResponse setDefaultFee(pactus.WalletOuterClass.SetDefaultFeeRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getSetDefaultFeeMethod(), getCallOptions(), request); } /** *
     * GetMnemonic returns the mnemonic (seed phrase) for the wallet.
     * 
*/ public pactus.WalletOuterClass.GetMnemonicResponse getMnemonic(pactus.WalletOuterClass.GetMnemonicRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetMnemonicMethod(), getCallOptions(), request); } /** *
     * GetPrivateKey returns the private key for a given address.
     * 
*/ public pactus.WalletOuterClass.GetPrivateKeyResponse getPrivateKey(pactus.WalletOuterClass.GetPrivateKeyRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetPrivateKeyMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service Wallet. *
   * Wallet service provides RPC methods for wallet management operations.
   * 
*/ public static final class WalletFutureStub extends io.grpc.stub.AbstractFutureStub { private WalletFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected WalletFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new WalletFutureStub(channel, callOptions); } /** *
     * CreateWallet creates a new wallet with the specified parameters.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture createWallet( pactus.WalletOuterClass.CreateWalletRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateWalletMethod(), getCallOptions()), request); } /** *
     * RestoreWallet restores an existing wallet with the given mnemonic.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture restoreWallet( pactus.WalletOuterClass.RestoreWalletRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getRestoreWalletMethod(), getCallOptions()), request); } /** *
     * LoadWallet loads an existing wallet with the given name.
     * deprecated: It will be removed in a future version.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture loadWallet( pactus.WalletOuterClass.LoadWalletRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getLoadWalletMethod(), getCallOptions()), request); } /** *
     * UnloadWallet unloads a currently loaded wallet with the specified name.
     * deprecated: It will be removed in a future version.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture unloadWallet( pactus.WalletOuterClass.UnloadWalletRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUnloadWalletMethod(), getCallOptions()), request); } /** *
     * ListWallets returns a list of all available wallets.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture listWallets( pactus.WalletOuterClass.ListWalletsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListWalletsMethod(), getCallOptions()), request); } /** *
     * GetWalletInfo returns detailed information about a specific wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getWalletInfo( pactus.WalletOuterClass.GetWalletInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetWalletInfoMethod(), getCallOptions()), request); } /** *
     * UpdatePassword updates the password of an existing wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture updatePassword( pactus.WalletOuterClass.UpdatePasswordRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUpdatePasswordMethod(), getCallOptions()), request); } /** *
     * GetTotalBalance returns the total available balance of the wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getTotalBalance( pactus.WalletOuterClass.GetTotalBalanceRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetTotalBalanceMethod(), getCallOptions()), request); } /** *
     * GetTotalStake returns the total stake amount in the wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getTotalStake( pactus.WalletOuterClass.GetTotalStakeRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetTotalStakeMethod(), getCallOptions()), request); } /** *
     * GetValidatorAddress retrieves the validator address associated with a public key.
     * Deprecated: Will move into utils.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getValidatorAddress( pactus.WalletOuterClass.GetValidatorAddressRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetValidatorAddressMethod(), getCallOptions()), request); } /** *
     * GetAddressInfo returns detailed information about a specific address.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getAddressInfo( pactus.WalletOuterClass.GetAddressInfoRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetAddressInfoMethod(), getCallOptions()), request); } /** *
     * SetAddressLabel sets or updates the label for a given address.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture setAddressLabel( pactus.WalletOuterClass.SetAddressLabelRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getSetAddressLabelMethod(), getCallOptions()), request); } /** *
     * GetNewAddress generates a new address for the specified wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getNewAddress( pactus.WalletOuterClass.GetNewAddressRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetNewAddressMethod(), getCallOptions()), request); } /** *
     * ListAddresses returns all addresses in the specified wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture listAddresses( pactus.WalletOuterClass.ListAddressesRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListAddressesMethod(), getCallOptions()), request); } /** *
     * SignMessage signs an arbitrary message using a wallet's private key.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture signMessage( pactus.WalletOuterClass.SignMessageRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getSignMessageMethod(), getCallOptions()), request); } /** *
     * SignRawTransaction signs a raw transaction for a specified wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture signRawTransaction( pactus.WalletOuterClass.SignRawTransactionRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getSignRawTransactionMethod(), getCallOptions()), request); } /** *
     * ListTransactions returns a list of transactions for a wallet,
     * optionally filtered by a specific address, with pagination support.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture listTransactions( pactus.WalletOuterClass.ListTransactionsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListTransactionsMethod(), getCallOptions()), request); } /** *
     * SetDefaultFee sets the default fee for the wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture setDefaultFee( pactus.WalletOuterClass.SetDefaultFeeRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getSetDefaultFeeMethod(), getCallOptions()), request); } /** *
     * GetMnemonic returns the mnemonic (seed phrase) for the wallet.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getMnemonic( pactus.WalletOuterClass.GetMnemonicRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetMnemonicMethod(), getCallOptions()), request); } /** *
     * GetPrivateKey returns the private key for a given address.
     * 
*/ public com.google.common.util.concurrent.ListenableFuture getPrivateKey( pactus.WalletOuterClass.GetPrivateKeyRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetPrivateKeyMethod(), getCallOptions()), request); } } private static final int METHODID_CREATE_WALLET = 0; private static final int METHODID_RESTORE_WALLET = 1; private static final int METHODID_LOAD_WALLET = 2; private static final int METHODID_UNLOAD_WALLET = 3; private static final int METHODID_LIST_WALLETS = 4; private static final int METHODID_GET_WALLET_INFO = 5; private static final int METHODID_UPDATE_PASSWORD = 6; private static final int METHODID_GET_TOTAL_BALANCE = 7; private static final int METHODID_GET_TOTAL_STAKE = 8; private static final int METHODID_GET_VALIDATOR_ADDRESS = 9; private static final int METHODID_GET_ADDRESS_INFO = 10; private static final int METHODID_SET_ADDRESS_LABEL = 11; private static final int METHODID_GET_NEW_ADDRESS = 12; private static final int METHODID_LIST_ADDRESSES = 13; private static final int METHODID_SIGN_MESSAGE = 14; private static final int METHODID_SIGN_RAW_TRANSACTION = 15; private static final int METHODID_LIST_TRANSACTIONS = 16; private static final int METHODID_SET_DEFAULT_FEE = 17; private static final int METHODID_GET_MNEMONIC = 18; private static final int METHODID_GET_PRIVATE_KEY = 19; private static final class MethodHandlers implements io.grpc.stub.ServerCalls.UnaryMethod, io.grpc.stub.ServerCalls.ServerStreamingMethod, io.grpc.stub.ServerCalls.ClientStreamingMethod, io.grpc.stub.ServerCalls.BidiStreamingMethod { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { case METHODID_CREATE_WALLET: serviceImpl.createWallet((pactus.WalletOuterClass.CreateWalletRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_RESTORE_WALLET: serviceImpl.restoreWallet((pactus.WalletOuterClass.RestoreWalletRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_LOAD_WALLET: serviceImpl.loadWallet((pactus.WalletOuterClass.LoadWalletRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_UNLOAD_WALLET: serviceImpl.unloadWallet((pactus.WalletOuterClass.UnloadWalletRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_LIST_WALLETS: serviceImpl.listWallets((pactus.WalletOuterClass.ListWalletsRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_WALLET_INFO: serviceImpl.getWalletInfo((pactus.WalletOuterClass.GetWalletInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_UPDATE_PASSWORD: serviceImpl.updatePassword((pactus.WalletOuterClass.UpdatePasswordRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_TOTAL_BALANCE: serviceImpl.getTotalBalance((pactus.WalletOuterClass.GetTotalBalanceRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_TOTAL_STAKE: serviceImpl.getTotalStake((pactus.WalletOuterClass.GetTotalStakeRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_VALIDATOR_ADDRESS: serviceImpl.getValidatorAddress((pactus.WalletOuterClass.GetValidatorAddressRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_ADDRESS_INFO: serviceImpl.getAddressInfo((pactus.WalletOuterClass.GetAddressInfoRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_SET_ADDRESS_LABEL: serviceImpl.setAddressLabel((pactus.WalletOuterClass.SetAddressLabelRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_NEW_ADDRESS: serviceImpl.getNewAddress((pactus.WalletOuterClass.GetNewAddressRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_LIST_ADDRESSES: serviceImpl.listAddresses((pactus.WalletOuterClass.ListAddressesRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_SIGN_MESSAGE: serviceImpl.signMessage((pactus.WalletOuterClass.SignMessageRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_SIGN_RAW_TRANSACTION: serviceImpl.signRawTransaction((pactus.WalletOuterClass.SignRawTransactionRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_LIST_TRANSACTIONS: serviceImpl.listTransactions((pactus.WalletOuterClass.ListTransactionsRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_SET_DEFAULT_FEE: serviceImpl.setDefaultFee((pactus.WalletOuterClass.SetDefaultFeeRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_MNEMONIC: serviceImpl.getMnemonic((pactus.WalletOuterClass.GetMnemonicRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; case METHODID_GET_PRIVATE_KEY: serviceImpl.getPrivateKey((pactus.WalletOuterClass.GetPrivateKeyRequest) request, (io.grpc.stub.StreamObserver) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver invoke( io.grpc.stub.StreamObserver responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getCreateWalletMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.CreateWalletRequest, pactus.WalletOuterClass.CreateWalletResponse>( service, METHODID_CREATE_WALLET))) .addMethod( getRestoreWalletMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.RestoreWalletRequest, pactus.WalletOuterClass.RestoreWalletResponse>( service, METHODID_RESTORE_WALLET))) .addMethod( getLoadWalletMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.LoadWalletRequest, pactus.WalletOuterClass.LoadWalletResponse>( service, METHODID_LOAD_WALLET))) .addMethod( getUnloadWalletMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.UnloadWalletRequest, pactus.WalletOuterClass.UnloadWalletResponse>( service, METHODID_UNLOAD_WALLET))) .addMethod( getListWalletsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.ListWalletsRequest, pactus.WalletOuterClass.ListWalletsResponse>( service, METHODID_LIST_WALLETS))) .addMethod( getGetWalletInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetWalletInfoRequest, pactus.WalletOuterClass.GetWalletInfoResponse>( service, METHODID_GET_WALLET_INFO))) .addMethod( getUpdatePasswordMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.UpdatePasswordRequest, pactus.WalletOuterClass.UpdatePasswordResponse>( service, METHODID_UPDATE_PASSWORD))) .addMethod( getGetTotalBalanceMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetTotalBalanceRequest, pactus.WalletOuterClass.GetTotalBalanceResponse>( service, METHODID_GET_TOTAL_BALANCE))) .addMethod( getGetTotalStakeMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetTotalStakeRequest, pactus.WalletOuterClass.GetTotalStakeResponse>( service, METHODID_GET_TOTAL_STAKE))) .addMethod( getGetValidatorAddressMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetValidatorAddressRequest, pactus.WalletOuterClass.GetValidatorAddressResponse>( service, METHODID_GET_VALIDATOR_ADDRESS))) .addMethod( getGetAddressInfoMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetAddressInfoRequest, pactus.WalletOuterClass.GetAddressInfoResponse>( service, METHODID_GET_ADDRESS_INFO))) .addMethod( getSetAddressLabelMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.SetAddressLabelRequest, pactus.WalletOuterClass.SetAddressLabelResponse>( service, METHODID_SET_ADDRESS_LABEL))) .addMethod( getGetNewAddressMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetNewAddressRequest, pactus.WalletOuterClass.GetNewAddressResponse>( service, METHODID_GET_NEW_ADDRESS))) .addMethod( getListAddressesMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.ListAddressesRequest, pactus.WalletOuterClass.ListAddressesResponse>( service, METHODID_LIST_ADDRESSES))) .addMethod( getSignMessageMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.SignMessageRequest, pactus.WalletOuterClass.SignMessageResponse>( service, METHODID_SIGN_MESSAGE))) .addMethod( getSignRawTransactionMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.SignRawTransactionRequest, pactus.WalletOuterClass.SignRawTransactionResponse>( service, METHODID_SIGN_RAW_TRANSACTION))) .addMethod( getListTransactionsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.ListTransactionsRequest, pactus.WalletOuterClass.ListTransactionsResponse>( service, METHODID_LIST_TRANSACTIONS))) .addMethod( getSetDefaultFeeMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.SetDefaultFeeRequest, pactus.WalletOuterClass.SetDefaultFeeResponse>( service, METHODID_SET_DEFAULT_FEE))) .addMethod( getGetMnemonicMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetMnemonicRequest, pactus.WalletOuterClass.GetMnemonicResponse>( service, METHODID_GET_MNEMONIC))) .addMethod( getGetPrivateKeyMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< pactus.WalletOuterClass.GetPrivateKeyRequest, pactus.WalletOuterClass.GetPrivateKeyResponse>( service, METHODID_GET_PRIVATE_KEY))) .build(); } private static abstract class WalletBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { WalletBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return pactus.WalletOuterClass.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Wallet"); } } private static final class WalletFileDescriptorSupplier extends WalletBaseDescriptorSupplier { WalletFileDescriptorSupplier() {} } private static final class WalletMethodDescriptorSupplier extends WalletBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; WalletMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (WalletGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new WalletFileDescriptorSupplier()) .addMethod(getCreateWalletMethod()) .addMethod(getRestoreWalletMethod()) .addMethod(getLoadWalletMethod()) .addMethod(getUnloadWalletMethod()) .addMethod(getListWalletsMethod()) .addMethod(getGetWalletInfoMethod()) .addMethod(getUpdatePasswordMethod()) .addMethod(getGetTotalBalanceMethod()) .addMethod(getGetTotalStakeMethod()) .addMethod(getGetValidatorAddressMethod()) .addMethod(getGetAddressInfoMethod()) .addMethod(getSetAddressLabelMethod()) .addMethod(getGetNewAddressMethod()) .addMethod(getListAddressesMethod()) .addMethod(getSignMessageMethod()) .addMethod(getSignRawTransactionMethod()) .addMethod(getListTransactionsMethod()) .addMethod(getSetDefaultFeeMethod()) .addMethod(getGetMnemonicMethod()) .addMethod(getGetPrivateKeyMethod()) .build(); } } } return result; } } ================================================ FILE: www/grpc/gen/java/pactus/WalletOuterClass.java ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: wallet.proto // Protobuf Java Version: 4.33.2 package pactus; @com.google.protobuf.Generated public final class WalletOuterClass extends com.google.protobuf.GeneratedFile { private WalletOuterClass() {} static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "WalletOuterClass"); } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** *
   * AddressType defines different types of blockchain addresses.
   * 
* * Protobuf enum {@code pactus.AddressType} */ public enum AddressType implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Treasury address type.
     * Should not be used to generate new addresses.
     * 
* * ADDRESS_TYPE_TREASURY = 0; */ ADDRESS_TYPE_TREASURY(0), /** *
     * Validator address type used for validator nodes.
     * 
* * ADDRESS_TYPE_VALIDATOR = 1; */ ADDRESS_TYPE_VALIDATOR(1), /** *
     * Account address type with BLS signature scheme.
     * 
* * ADDRESS_TYPE_BLS_ACCOUNT = 2; */ ADDRESS_TYPE_BLS_ACCOUNT(2), /** *
     * Account address type with Ed25519 signature scheme.
     * Note: Generating a new Ed25519 address requires the wallet password.
     * 
* * ADDRESS_TYPE_ED25519_ACCOUNT = 3; */ ADDRESS_TYPE_ED25519_ACCOUNT(3), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "AddressType"); } /** *
     * Treasury address type.
     * Should not be used to generate new addresses.
     * 
* * ADDRESS_TYPE_TREASURY = 0; */ public static final int ADDRESS_TYPE_TREASURY_VALUE = 0; /** *
     * Validator address type used for validator nodes.
     * 
* * ADDRESS_TYPE_VALIDATOR = 1; */ public static final int ADDRESS_TYPE_VALIDATOR_VALUE = 1; /** *
     * Account address type with BLS signature scheme.
     * 
* * ADDRESS_TYPE_BLS_ACCOUNT = 2; */ public static final int ADDRESS_TYPE_BLS_ACCOUNT_VALUE = 2; /** *
     * Account address type with Ed25519 signature scheme.
     * Note: Generating a new Ed25519 address requires the wallet password.
     * 
* * ADDRESS_TYPE_ED25519_ACCOUNT = 3; */ public static final int ADDRESS_TYPE_ED25519_ACCOUNT_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static AddressType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static AddressType forNumber(int value) { switch (value) { case 0: return ADDRESS_TYPE_TREASURY; case 1: return ADDRESS_TYPE_VALIDATOR; case 2: return ADDRESS_TYPE_BLS_ACCOUNT; case 3: return ADDRESS_TYPE_ED25519_ACCOUNT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< AddressType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public AddressType findValueByNumber(int number) { return AddressType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.WalletOuterClass.getDescriptor().getEnumTypes().get(0); } private static final AddressType[] VALUES = values(); public static AddressType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private AddressType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.AddressType) } /** *
   * TxDirection indicates the direction of a transaction relative to the wallet.
   * 
* * Protobuf enum {@code pactus.TxDirection} */ public enum TxDirection implements com.google.protobuf.ProtocolMessageEnum { /** *
     * include both incoming and outgoing transactions.
     * 
* * TX_DIRECTION_ANY = 0; */ TX_DIRECTION_ANY(0), /** *
     * Include only incoming transactions where the wallet receives funds.
     * 
* * TX_DIRECTION_INCOMING = 1; */ TX_DIRECTION_INCOMING(1), /** *
     * Include only outgoing transactions where the wallet sends funds.
     * 
* * TX_DIRECTION_OUTGOING = 2; */ TX_DIRECTION_OUTGOING(2), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "TxDirection"); } /** *
     * include both incoming and outgoing transactions.
     * 
* * TX_DIRECTION_ANY = 0; */ public static final int TX_DIRECTION_ANY_VALUE = 0; /** *
     * Include only incoming transactions where the wallet receives funds.
     * 
* * TX_DIRECTION_INCOMING = 1; */ public static final int TX_DIRECTION_INCOMING_VALUE = 1; /** *
     * Include only outgoing transactions where the wallet sends funds.
     * 
* * TX_DIRECTION_OUTGOING = 2; */ public static final int TX_DIRECTION_OUTGOING_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TxDirection valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static TxDirection forNumber(int value) { switch (value) { case 0: return TX_DIRECTION_ANY; case 1: return TX_DIRECTION_INCOMING; case 2: return TX_DIRECTION_OUTGOING; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< TxDirection> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public TxDirection findValueByNumber(int number) { return TxDirection.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.WalletOuterClass.getDescriptor().getEnumTypes().get(1); } private static final TxDirection[] VALUES = values(); public static TxDirection valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TxDirection(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.TxDirection) } /** *
   * TransactionStatus defines the status of a transaction.
   * 
* * Protobuf enum {@code pactus.TransactionStatus} */ public enum TransactionStatus implements com.google.protobuf.ProtocolMessageEnum { /** *
     * Pending status for transactions in the mempool.
     * 
* * TRANSACTION_STATUS_PENDING = 0; */ TRANSACTION_STATUS_PENDING(0), /** *
     * Confirmed status for transactions included in a block.
     * 
* * TRANSACTION_STATUS_CONFIRMED = 1; */ TRANSACTION_STATUS_CONFIRMED(1), /** *
     * Failed status for transactions that were not successful.
     * 
* * TRANSACTION_STATUS_FAILED = -1; */ TRANSACTION_STATUS_FAILED(-1), UNRECOGNIZED(-1), ; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "TransactionStatus"); } /** *
     * Pending status for transactions in the mempool.
     * 
* * TRANSACTION_STATUS_PENDING = 0; */ public static final int TRANSACTION_STATUS_PENDING_VALUE = 0; /** *
     * Confirmed status for transactions included in a block.
     * 
* * TRANSACTION_STATUS_CONFIRMED = 1; */ public static final int TRANSACTION_STATUS_CONFIRMED_VALUE = 1; /** *
     * Failed status for transactions that were not successful.
     * 
* * TRANSACTION_STATUS_FAILED = -1; */ public static final int TRANSACTION_STATUS_FAILED_VALUE = -1; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TransactionStatus valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static TransactionStatus forNumber(int value) { switch (value) { case 0: return TRANSACTION_STATUS_PENDING; case 1: return TRANSACTION_STATUS_CONFIRMED; case -1: return TRANSACTION_STATUS_FAILED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< TransactionStatus> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public TransactionStatus findValueByNumber(int number) { return TransactionStatus.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return pactus.WalletOuterClass.getDescriptor().getEnumTypes().get(2); } private static final TransactionStatus[] VALUES = values(); public static TransactionStatus valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TransactionStatus(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:pactus.TransactionStatus) } public interface AddressInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.AddressInfo) com.google.protobuf.MessageOrBuilder { /** *
     * The address string.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address string.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The public key associated with the address.
     * 
* * string public_key = 2 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key associated with the address.
     * 
* * string public_key = 2 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); /** *
     * A human-readable label associated with the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The label. */ java.lang.String getLabel(); /** *
     * A human-readable label associated with the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ com.google.protobuf.ByteString getLabelBytes(); /** *
     * The Hierarchical Deterministic (HD) path of the address within the wallet.
     * 
* * string path = 4 [json_name = "path"]; * @return The path. */ java.lang.String getPath(); /** *
     * The Hierarchical Deterministic (HD) path of the address within the wallet.
     * 
* * string path = 4 [json_name = "path"]; * @return The bytes for path. */ com.google.protobuf.ByteString getPathBytes(); } /** *
   * AddressInfo contains detailed information about a wallet address.
   * 
* * Protobuf type {@code pactus.AddressInfo} */ public static final class AddressInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.AddressInfo) AddressInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "AddressInfo"); } // Use AddressInfo.newBuilder() to construct. private AddressInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private AddressInfo() { address_ = ""; publicKey_ = ""; label_ = ""; path_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_AddressInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_AddressInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.AddressInfo.class, pactus.WalletOuterClass.AddressInfo.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address string.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address string.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PUBLIC_KEY_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key associated with the address.
     * 
* * string public_key = 2 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key associated with the address.
     * 
* * string public_key = 2 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LABEL_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object label_ = ""; /** *
     * A human-readable label associated with the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The label. */ @java.lang.Override public java.lang.String getLabel() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } } /** *
     * A human-readable label associated with the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ @java.lang.Override public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PATH_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object path_ = ""; /** *
     * The Hierarchical Deterministic (HD) path of the address within the wallet.
     * 
* * string path = 4 [json_name = "path"]; * @return The path. */ @java.lang.Override public java.lang.String getPath() { java.lang.Object ref = path_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); path_ = s; return s; } } /** *
     * The Hierarchical Deterministic (HD) path of the address within the wallet.
     * 
* * string path = 4 [json_name = "path"]; * @return The bytes for path. */ @java.lang.Override public com.google.protobuf.ByteString getPathBytes() { java.lang.Object ref = path_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); path_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, publicKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, label_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(path_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, path_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, publicKey_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, label_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(path_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, path_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.AddressInfo)) { return super.equals(obj); } pactus.WalletOuterClass.AddressInfo other = (pactus.WalletOuterClass.AddressInfo) obj; if (!getAddress() .equals(other.getAddress())) return false; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (!getLabel() .equals(other.getLabel())) return false; if (!getPath() .equals(other.getPath())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (37 * hash) + LABEL_FIELD_NUMBER; hash = (53 * hash) + getLabel().hashCode(); hash = (37 * hash) + PATH_FIELD_NUMBER; hash = (53 * hash) + getPath().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.AddressInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.AddressInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.AddressInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.AddressInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.AddressInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.AddressInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.AddressInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.AddressInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.AddressInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.AddressInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.AddressInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.AddressInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.AddressInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * AddressInfo contains detailed information about a wallet address.
     * 
* * Protobuf type {@code pactus.AddressInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.AddressInfo) pactus.WalletOuterClass.AddressInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_AddressInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_AddressInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.AddressInfo.class, pactus.WalletOuterClass.AddressInfo.Builder.class); } // Construct using pactus.WalletOuterClass.AddressInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; publicKey_ = ""; label_ = ""; path_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_AddressInfo_descriptor; } @java.lang.Override public pactus.WalletOuterClass.AddressInfo getDefaultInstanceForType() { return pactus.WalletOuterClass.AddressInfo.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.AddressInfo build() { pactus.WalletOuterClass.AddressInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.AddressInfo buildPartial() { pactus.WalletOuterClass.AddressInfo result = new pactus.WalletOuterClass.AddressInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.AddressInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.publicKey_ = publicKey_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.label_ = label_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.path_ = path_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.AddressInfo) { return mergeFrom((pactus.WalletOuterClass.AddressInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.AddressInfo other) { if (other == pactus.WalletOuterClass.AddressInfo.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getLabel().isEmpty()) { label_ = other.label_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getPath().isEmpty()) { path_ = other.path_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { label_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { path_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The address string.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address string.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address string.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The address string.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The address string.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object publicKey_ = ""; /** *
       * The public key associated with the address.
       * 
* * string public_key = 2 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key associated with the address.
       * 
* * string public_key = 2 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key associated with the address.
       * 
* * string public_key = 2 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The public key associated with the address.
       * 
* * string public_key = 2 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The public key associated with the address.
       * 
* * string public_key = 2 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object label_ = ""; /** *
       * A human-readable label associated with the address.
       * 
* * string label = 3 [json_name = "label"]; * @return The label. */ public java.lang.String getLabel() { java.lang.Object ref = label_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A human-readable label associated with the address.
       * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A human-readable label associated with the address.
       * 
* * string label = 3 [json_name = "label"]; * @param value The label to set. * @return This builder for chaining. */ public Builder setLabel( java.lang.String value) { if (value == null) { throw new NullPointerException(); } label_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * A human-readable label associated with the address.
       * 
* * string label = 3 [json_name = "label"]; * @return This builder for chaining. */ public Builder clearLabel() { label_ = getDefaultInstance().getLabel(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * A human-readable label associated with the address.
       * 
* * string label = 3 [json_name = "label"]; * @param value The bytes for label to set. * @return This builder for chaining. */ public Builder setLabelBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); label_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object path_ = ""; /** *
       * The Hierarchical Deterministic (HD) path of the address within the wallet.
       * 
* * string path = 4 [json_name = "path"]; * @return The path. */ public java.lang.String getPath() { java.lang.Object ref = path_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); path_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The Hierarchical Deterministic (HD) path of the address within the wallet.
       * 
* * string path = 4 [json_name = "path"]; * @return The bytes for path. */ public com.google.protobuf.ByteString getPathBytes() { java.lang.Object ref = path_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); path_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The Hierarchical Deterministic (HD) path of the address within the wallet.
       * 
* * string path = 4 [json_name = "path"]; * @param value The path to set. * @return This builder for chaining. */ public Builder setPath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } path_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The Hierarchical Deterministic (HD) path of the address within the wallet.
       * 
* * string path = 4 [json_name = "path"]; * @return This builder for chaining. */ public Builder clearPath() { path_ = getDefaultInstance().getPath(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The Hierarchical Deterministic (HD) path of the address within the wallet.
       * 
* * string path = 4 [json_name = "path"]; * @param value The bytes for path to set. * @return This builder for chaining. */ public Builder setPathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); path_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.AddressInfo) } // @@protoc_insertion_point(class_scope:pactus.AddressInfo) private static final pactus.WalletOuterClass.AddressInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.AddressInfo(); } public static pactus.WalletOuterClass.AddressInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public AddressInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.AddressInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetNewAddressRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetNewAddressRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to generate a new address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to generate a new address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The type of address to generate.
     * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return The enum numeric value on the wire for addressType. */ int getAddressTypeValue(); /** *
     * The type of address to generate.
     * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return The addressType. */ pactus.WalletOuterClass.AddressType getAddressType(); /** *
     * A label for the new address.
     * 
* * string label = 3 [json_name = "label"]; * @return The label. */ java.lang.String getLabel(); /** *
     * A label for the new address.
     * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ com.google.protobuf.ByteString getLabelBytes(); /** *
     * Password for the new address. It's required when address_type is Ed25519 type.
     * 
* * string password = 4 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Password for the new address. It's required when address_type is Ed25519 type.
     * 
* * string password = 4 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); } /** *
   * Request message for generating a new wallet address.
   * 
* * Protobuf type {@code pactus.GetNewAddressRequest} */ public static final class GetNewAddressRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetNewAddressRequest) GetNewAddressRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetNewAddressRequest"); } // Use GetNewAddressRequest.newBuilder() to construct. private GetNewAddressRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetNewAddressRequest() { walletName_ = ""; addressType_ = 0; label_ = ""; password_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetNewAddressRequest.class, pactus.WalletOuterClass.GetNewAddressRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to generate a new address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to generate a new address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_TYPE_FIELD_NUMBER = 2; private int addressType_ = 0; /** *
     * The type of address to generate.
     * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return The enum numeric value on the wire for addressType. */ @java.lang.Override public int getAddressTypeValue() { return addressType_; } /** *
     * The type of address to generate.
     * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return The addressType. */ @java.lang.Override public pactus.WalletOuterClass.AddressType getAddressType() { pactus.WalletOuterClass.AddressType result = pactus.WalletOuterClass.AddressType.forNumber(addressType_); return result == null ? pactus.WalletOuterClass.AddressType.UNRECOGNIZED : result; } public static final int LABEL_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object label_ = ""; /** *
     * A label for the new address.
     * 
* * string label = 3 [json_name = "label"]; * @return The label. */ @java.lang.Override public java.lang.String getLabel() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } } /** *
     * A label for the new address.
     * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ @java.lang.Override public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Password for the new address. It's required when address_type is Ed25519 type.
     * 
* * string password = 4 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Password for the new address. It's required when address_type is Ed25519 type.
     * 
* * string password = 4 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (addressType_ != pactus.WalletOuterClass.AddressType.ADDRESS_TYPE_TREASURY.getNumber()) { output.writeEnum(2, addressType_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, label_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, password_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (addressType_ != pactus.WalletOuterClass.AddressType.ADDRESS_TYPE_TREASURY.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, addressType_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, label_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, password_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetNewAddressRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetNewAddressRequest other = (pactus.WalletOuterClass.GetNewAddressRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (addressType_ != other.addressType_) return false; if (!getLabel() .equals(other.getLabel())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + ADDRESS_TYPE_FIELD_NUMBER; hash = (53 * hash) + addressType_; hash = (37 * hash) + LABEL_FIELD_NUMBER; hash = (53 * hash) + getLabel().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetNewAddressRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetNewAddressRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetNewAddressRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for generating a new wallet address.
     * 
* * Protobuf type {@code pactus.GetNewAddressRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetNewAddressRequest) pactus.WalletOuterClass.GetNewAddressRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetNewAddressRequest.class, pactus.WalletOuterClass.GetNewAddressRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetNewAddressRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; addressType_ = 0; label_ = ""; password_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetNewAddressRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressRequest build() { pactus.WalletOuterClass.GetNewAddressRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressRequest buildPartial() { pactus.WalletOuterClass.GetNewAddressRequest result = new pactus.WalletOuterClass.GetNewAddressRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetNewAddressRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.addressType_ = addressType_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.label_ = label_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.password_ = password_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetNewAddressRequest) { return mergeFrom((pactus.WalletOuterClass.GetNewAddressRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetNewAddressRequest other) { if (other == pactus.WalletOuterClass.GetNewAddressRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.addressType_ != 0) { setAddressTypeValue(other.getAddressTypeValue()); } if (!other.getLabel().isEmpty()) { label_ = other.label_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { addressType_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { label_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to generate a new address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to generate a new address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to generate a new address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to generate a new address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to generate a new address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int addressType_ = 0; /** *
       * The type of address to generate.
       * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return The enum numeric value on the wire for addressType. */ @java.lang.Override public int getAddressTypeValue() { return addressType_; } /** *
       * The type of address to generate.
       * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @param value The enum numeric value on the wire for addressType to set. * @return This builder for chaining. */ public Builder setAddressTypeValue(int value) { addressType_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The type of address to generate.
       * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return The addressType. */ @java.lang.Override public pactus.WalletOuterClass.AddressType getAddressType() { pactus.WalletOuterClass.AddressType result = pactus.WalletOuterClass.AddressType.forNumber(addressType_); return result == null ? pactus.WalletOuterClass.AddressType.UNRECOGNIZED : result; } /** *
       * The type of address to generate.
       * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @param value The addressType to set. * @return This builder for chaining. */ public Builder setAddressType(pactus.WalletOuterClass.AddressType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; addressType_ = value.getNumber(); onChanged(); return this; } /** *
       * The type of address to generate.
       * 
* * .pactus.AddressType address_type = 2 [json_name = "addressType"]; * @return This builder for chaining. */ public Builder clearAddressType() { bitField0_ = (bitField0_ & ~0x00000002); addressType_ = 0; onChanged(); return this; } private java.lang.Object label_ = ""; /** *
       * A label for the new address.
       * 
* * string label = 3 [json_name = "label"]; * @return The label. */ public java.lang.String getLabel() { java.lang.Object ref = label_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A label for the new address.
       * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A label for the new address.
       * 
* * string label = 3 [json_name = "label"]; * @param value The label to set. * @return This builder for chaining. */ public Builder setLabel( java.lang.String value) { if (value == null) { throw new NullPointerException(); } label_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * A label for the new address.
       * 
* * string label = 3 [json_name = "label"]; * @return This builder for chaining. */ public Builder clearLabel() { label_ = getDefaultInstance().getLabel(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * A label for the new address.
       * 
* * string label = 3 [json_name = "label"]; * @param value The bytes for label to set. * @return This builder for chaining. */ public Builder setLabelBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); label_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Password for the new address. It's required when address_type is Ed25519 type.
       * 
* * string password = 4 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Password for the new address. It's required when address_type is Ed25519 type.
       * 
* * string password = 4 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Password for the new address. It's required when address_type is Ed25519 type.
       * 
* * string password = 4 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * Password for the new address. It's required when address_type is Ed25519 type.
       * 
* * string password = 4 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * Password for the new address. It's required when address_type is Ed25519 type.
       * 
* * string password = 4 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetNewAddressRequest) } // @@protoc_insertion_point(class_scope:pactus.GetNewAddressRequest) private static final pactus.WalletOuterClass.GetNewAddressRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetNewAddressRequest(); } public static pactus.WalletOuterClass.GetNewAddressRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetNewAddressRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetNewAddressResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetNewAddressResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet where address was generated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet where address was generated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Detailed information about the new address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return Whether the addr field is set. */ boolean hasAddr(); /** *
     * Detailed information about the new address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return The addr. */ pactus.WalletOuterClass.AddressInfo getAddr(); /** *
     * Detailed information about the new address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ pactus.WalletOuterClass.AddressInfoOrBuilder getAddrOrBuilder(); } /** *
   * Response message contains newly generated address information.
   * 
* * Protobuf type {@code pactus.GetNewAddressResponse} */ public static final class GetNewAddressResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetNewAddressResponse) GetNewAddressResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetNewAddressResponse"); } // Use GetNewAddressResponse.newBuilder() to construct. private GetNewAddressResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetNewAddressResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetNewAddressResponse.class, pactus.WalletOuterClass.GetNewAddressResponse.Builder.class); } private int bitField0_; public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet where address was generated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet where address was generated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDR_FIELD_NUMBER = 2; private pactus.WalletOuterClass.AddressInfo addr_; /** *
     * Detailed information about the new address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return Whether the addr field is set. */ @java.lang.Override public boolean hasAddr() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Detailed information about the new address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return The addr. */ @java.lang.Override public pactus.WalletOuterClass.AddressInfo getAddr() { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } /** *
     * Detailed information about the new address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ @java.lang.Override public pactus.WalletOuterClass.AddressInfoOrBuilder getAddrOrBuilder() { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getAddr()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getAddr()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetNewAddressResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetNewAddressResponse other = (pactus.WalletOuterClass.GetNewAddressResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (hasAddr() != other.hasAddr()) return false; if (hasAddr()) { if (!getAddr() .equals(other.getAddr())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); if (hasAddr()) { hash = (37 * hash) + ADDR_FIELD_NUMBER; hash = (53 * hash) + getAddr().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetNewAddressResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetNewAddressResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetNewAddressResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains newly generated address information.
     * 
* * Protobuf type {@code pactus.GetNewAddressResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetNewAddressResponse) pactus.WalletOuterClass.GetNewAddressResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetNewAddressResponse.class, pactus.WalletOuterClass.GetNewAddressResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetNewAddressResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetAddrFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; addr_ = null; if (addrBuilder_ != null) { addrBuilder_.dispose(); addrBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetNewAddressResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetNewAddressResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressResponse build() { pactus.WalletOuterClass.GetNewAddressResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressResponse buildPartial() { pactus.WalletOuterClass.GetNewAddressResponse result = new pactus.WalletOuterClass.GetNewAddressResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetNewAddressResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.addr_ = addrBuilder_ == null ? addr_ : addrBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetNewAddressResponse) { return mergeFrom((pactus.WalletOuterClass.GetNewAddressResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetNewAddressResponse other) { if (other == pactus.WalletOuterClass.GetNewAddressResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasAddr()) { mergeAddr(other.getAddr()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( internalGetAddrFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet where address was generated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet where address was generated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet where address was generated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet where address was generated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet where address was generated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private pactus.WalletOuterClass.AddressInfo addr_; private com.google.protobuf.SingleFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder> addrBuilder_; /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return Whether the addr field is set. */ public boolean hasAddr() { return ((bitField0_ & 0x00000002) != 0); } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return The addr. */ public pactus.WalletOuterClass.AddressInfo getAddr() { if (addrBuilder_ == null) { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } else { return addrBuilder_.getMessage(); } } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder setAddr(pactus.WalletOuterClass.AddressInfo value) { if (addrBuilder_ == null) { if (value == null) { throw new NullPointerException(); } addr_ = value; } else { addrBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder setAddr( pactus.WalletOuterClass.AddressInfo.Builder builderForValue) { if (addrBuilder_ == null) { addr_ = builderForValue.build(); } else { addrBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder mergeAddr(pactus.WalletOuterClass.AddressInfo value) { if (addrBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && addr_ != null && addr_ != pactus.WalletOuterClass.AddressInfo.getDefaultInstance()) { getAddrBuilder().mergeFrom(value); } else { addr_ = value; } } else { addrBuilder_.mergeFrom(value); } if (addr_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder clearAddr() { bitField0_ = (bitField0_ & ~0x00000002); addr_ = null; if (addrBuilder_ != null) { addrBuilder_.dispose(); addrBuilder_ = null; } onChanged(); return this; } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public pactus.WalletOuterClass.AddressInfo.Builder getAddrBuilder() { bitField0_ |= 0x00000002; onChanged(); return internalGetAddrFieldBuilder().getBuilder(); } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public pactus.WalletOuterClass.AddressInfoOrBuilder getAddrOrBuilder() { if (addrBuilder_ != null) { return addrBuilder_.getMessageOrBuilder(); } else { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } } /** *
       * Detailed information about the new address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder> internalGetAddrFieldBuilder() { if (addrBuilder_ == null) { addrBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder>( getAddr(), getParentForChildren(), isClean()); addr_ = null; } return addrBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetNewAddressResponse) } // @@protoc_insertion_point(class_scope:pactus.GetNewAddressResponse) private static final pactus.WalletOuterClass.GetNewAddressResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetNewAddressResponse(); } public static pactus.WalletOuterClass.GetNewAddressResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetNewAddressResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetNewAddressResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RestoreWalletRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.RestoreWalletRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name for the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name for the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The mnemonic. */ java.lang.String getMnemonic(); /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ com.google.protobuf.ByteString getMnemonicBytes(); /** *
     * Password to secure the restored wallet.
     * 
* * string password = 3 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Password to secure the restored wallet.
     * 
* * string password = 3 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); } /** *
   * Request message for restoring a wallet from mnemonic (seed phrase).
   * 
* * Protobuf type {@code pactus.RestoreWalletRequest} */ public static final class RestoreWalletRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.RestoreWalletRequest) RestoreWalletRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "RestoreWalletRequest"); } // Use RestoreWalletRequest.newBuilder() to construct. private RestoreWalletRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private RestoreWalletRequest() { walletName_ = ""; mnemonic_ = ""; password_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.RestoreWalletRequest.class, pactus.WalletOuterClass.RestoreWalletRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name for the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name for the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MNEMONIC_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object mnemonic_ = ""; /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The mnemonic. */ @java.lang.Override public java.lang.String getMnemonic() { java.lang.Object ref = mnemonic_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mnemonic_ = s; return s; } } /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ @java.lang.Override public com.google.protobuf.ByteString getMnemonicBytes() { java.lang.Object ref = mnemonic_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); mnemonic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Password to secure the restored wallet.
     * 
* * string password = 3 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Password to secure the restored wallet.
     * 
* * string password = 3 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(mnemonic_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, mnemonic_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, password_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(mnemonic_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, mnemonic_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, password_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.RestoreWalletRequest)) { return super.equals(obj); } pactus.WalletOuterClass.RestoreWalletRequest other = (pactus.WalletOuterClass.RestoreWalletRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getMnemonic() .equals(other.getMnemonic())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + MNEMONIC_FIELD_NUMBER; hash = (53 * hash) + getMnemonic().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.RestoreWalletRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.RestoreWalletRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.RestoreWalletRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for restoring a wallet from mnemonic (seed phrase).
     * 
* * Protobuf type {@code pactus.RestoreWalletRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.RestoreWalletRequest) pactus.WalletOuterClass.RestoreWalletRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.RestoreWalletRequest.class, pactus.WalletOuterClass.RestoreWalletRequest.Builder.class); } // Construct using pactus.WalletOuterClass.RestoreWalletRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; mnemonic_ = ""; password_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.RestoreWalletRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletRequest build() { pactus.WalletOuterClass.RestoreWalletRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletRequest buildPartial() { pactus.WalletOuterClass.RestoreWalletRequest result = new pactus.WalletOuterClass.RestoreWalletRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.RestoreWalletRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.mnemonic_ = mnemonic_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.password_ = password_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.RestoreWalletRequest) { return mergeFrom((pactus.WalletOuterClass.RestoreWalletRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.RestoreWalletRequest other) { if (other == pactus.WalletOuterClass.RestoreWalletRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getMnemonic().isEmpty()) { mnemonic_ = other.mnemonic_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { mnemonic_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name for the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name for the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name for the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name for the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name for the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object mnemonic_ = ""; /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The mnemonic. */ public java.lang.String getMnemonic() { java.lang.Object ref = mnemonic_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mnemonic_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ public com.google.protobuf.ByteString getMnemonicBytes() { java.lang.Object ref = mnemonic_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); mnemonic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @param value The mnemonic to set. * @return This builder for chaining. */ public Builder setMnemonic( java.lang.String value) { if (value == null) { throw new NullPointerException(); } mnemonic_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return This builder for chaining. */ public Builder clearMnemonic() { mnemonic_ = getDefaultInstance().getMnemonic(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @param value The bytes for mnemonic to set. * @return This builder for chaining. */ public Builder setMnemonicBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); mnemonic_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Password to secure the restored wallet.
       * 
* * string password = 3 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Password to secure the restored wallet.
       * 
* * string password = 3 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Password to secure the restored wallet.
       * 
* * string password = 3 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Password to secure the restored wallet.
       * 
* * string password = 3 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * Password to secure the restored wallet.
       * 
* * string password = 3 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.RestoreWalletRequest) } // @@protoc_insertion_point(class_scope:pactus.RestoreWalletRequest) private static final pactus.WalletOuterClass.RestoreWalletRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.RestoreWalletRequest(); } public static pactus.WalletOuterClass.RestoreWalletRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public RestoreWalletRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RestoreWalletResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.RestoreWalletResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Response message confirming wallet restoration.
   * 
* * Protobuf type {@code pactus.RestoreWalletResponse} */ public static final class RestoreWalletResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.RestoreWalletResponse) RestoreWalletResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "RestoreWalletResponse"); } // Use RestoreWalletResponse.newBuilder() to construct. private RestoreWalletResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private RestoreWalletResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.RestoreWalletResponse.class, pactus.WalletOuterClass.RestoreWalletResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the restored wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.RestoreWalletResponse)) { return super.equals(obj); } pactus.WalletOuterClass.RestoreWalletResponse other = (pactus.WalletOuterClass.RestoreWalletResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.RestoreWalletResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.RestoreWalletResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.RestoreWalletResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message confirming wallet restoration.
     * 
* * Protobuf type {@code pactus.RestoreWalletResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.RestoreWalletResponse) pactus.WalletOuterClass.RestoreWalletResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.RestoreWalletResponse.class, pactus.WalletOuterClass.RestoreWalletResponse.Builder.class); } // Construct using pactus.WalletOuterClass.RestoreWalletResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_RestoreWalletResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.RestoreWalletResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletResponse build() { pactus.WalletOuterClass.RestoreWalletResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletResponse buildPartial() { pactus.WalletOuterClass.RestoreWalletResponse result = new pactus.WalletOuterClass.RestoreWalletResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.RestoreWalletResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.RestoreWalletResponse) { return mergeFrom((pactus.WalletOuterClass.RestoreWalletResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.RestoreWalletResponse other) { if (other == pactus.WalletOuterClass.RestoreWalletResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the restored wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.RestoreWalletResponse) } // @@protoc_insertion_point(class_scope:pactus.RestoreWalletResponse) private static final pactus.WalletOuterClass.RestoreWalletResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.RestoreWalletResponse(); } public static pactus.WalletOuterClass.RestoreWalletResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public RestoreWalletResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.RestoreWalletResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CreateWalletRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CreateWalletRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Password to secure the new wallet.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Password to secure the new wallet.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); } /** *
   * Request message for creating a new wallet.
   * 
* * Protobuf type {@code pactus.CreateWalletRequest} */ public static final class CreateWalletRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CreateWalletRequest) CreateWalletRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CreateWalletRequest"); } // Use CreateWalletRequest.newBuilder() to construct. private CreateWalletRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CreateWalletRequest() { walletName_ = ""; password_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.CreateWalletRequest.class, pactus.WalletOuterClass.CreateWalletRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Password to secure the new wallet.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Password to secure the new wallet.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, password_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, password_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.CreateWalletRequest)) { return super.equals(obj); } pactus.WalletOuterClass.CreateWalletRequest other = (pactus.WalletOuterClass.CreateWalletRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.CreateWalletRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.CreateWalletRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.CreateWalletRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for creating a new wallet.
     * 
* * Protobuf type {@code pactus.CreateWalletRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CreateWalletRequest) pactus.WalletOuterClass.CreateWalletRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.CreateWalletRequest.class, pactus.WalletOuterClass.CreateWalletRequest.Builder.class); } // Construct using pactus.WalletOuterClass.CreateWalletRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; password_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.CreateWalletRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.CreateWalletRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.CreateWalletRequest build() { pactus.WalletOuterClass.CreateWalletRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.CreateWalletRequest buildPartial() { pactus.WalletOuterClass.CreateWalletRequest result = new pactus.WalletOuterClass.CreateWalletRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.CreateWalletRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.password_ = password_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.CreateWalletRequest) { return mergeFrom((pactus.WalletOuterClass.CreateWalletRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.CreateWalletRequest other) { if (other == pactus.WalletOuterClass.CreateWalletRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Password to secure the new wallet.
       * 
* * string password = 2 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Password to secure the new wallet.
       * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Password to secure the new wallet.
       * 
* * string password = 2 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Password to secure the new wallet.
       * 
* * string password = 2 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Password to secure the new wallet.
       * 
* * string password = 2 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CreateWalletRequest) } // @@protoc_insertion_point(class_scope:pactus.CreateWalletRequest) private static final pactus.WalletOuterClass.CreateWalletRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.CreateWalletRequest(); } public static pactus.WalletOuterClass.CreateWalletRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CreateWalletRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.CreateWalletRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface CreateWalletResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.CreateWalletResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The mnemonic. */ java.lang.String getMnemonic(); /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ com.google.protobuf.ByteString getMnemonicBytes(); } /** *
   * Response message contains wallet recovery mnemonic (seed phrase).
   * 
* * Protobuf type {@code pactus.CreateWalletResponse} */ public static final class CreateWalletResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.CreateWalletResponse) CreateWalletResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "CreateWalletResponse"); } // Use CreateWalletResponse.newBuilder() to construct. private CreateWalletResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private CreateWalletResponse() { walletName_ = ""; mnemonic_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.CreateWalletResponse.class, pactus.WalletOuterClass.CreateWalletResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name for the new wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MNEMONIC_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object mnemonic_ = ""; /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The mnemonic. */ @java.lang.Override public java.lang.String getMnemonic() { java.lang.Object ref = mnemonic_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mnemonic_ = s; return s; } } /** *
     * The mnemonic (seed phrase) for wallet recovery.
     * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ @java.lang.Override public com.google.protobuf.ByteString getMnemonicBytes() { java.lang.Object ref = mnemonic_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); mnemonic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(mnemonic_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, mnemonic_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(mnemonic_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, mnemonic_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.CreateWalletResponse)) { return super.equals(obj); } pactus.WalletOuterClass.CreateWalletResponse other = (pactus.WalletOuterClass.CreateWalletResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getMnemonic() .equals(other.getMnemonic())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + MNEMONIC_FIELD_NUMBER; hash = (53 * hash) + getMnemonic().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.CreateWalletResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.CreateWalletResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.CreateWalletResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains wallet recovery mnemonic (seed phrase).
     * 
* * Protobuf type {@code pactus.CreateWalletResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.CreateWalletResponse) pactus.WalletOuterClass.CreateWalletResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.CreateWalletResponse.class, pactus.WalletOuterClass.CreateWalletResponse.Builder.class); } // Construct using pactus.WalletOuterClass.CreateWalletResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; mnemonic_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_CreateWalletResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.CreateWalletResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.CreateWalletResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.CreateWalletResponse build() { pactus.WalletOuterClass.CreateWalletResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.CreateWalletResponse buildPartial() { pactus.WalletOuterClass.CreateWalletResponse result = new pactus.WalletOuterClass.CreateWalletResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.CreateWalletResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.mnemonic_ = mnemonic_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.CreateWalletResponse) { return mergeFrom((pactus.WalletOuterClass.CreateWalletResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.CreateWalletResponse other) { if (other == pactus.WalletOuterClass.CreateWalletResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getMnemonic().isEmpty()) { mnemonic_ = other.mnemonic_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { mnemonic_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name for the new wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object mnemonic_ = ""; /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The mnemonic. */ public java.lang.String getMnemonic() { java.lang.Object ref = mnemonic_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mnemonic_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ public com.google.protobuf.ByteString getMnemonicBytes() { java.lang.Object ref = mnemonic_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); mnemonic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @param value The mnemonic to set. * @return This builder for chaining. */ public Builder setMnemonic( java.lang.String value) { if (value == null) { throw new NullPointerException(); } mnemonic_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @return This builder for chaining. */ public Builder clearMnemonic() { mnemonic_ = getDefaultInstance().getMnemonic(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The mnemonic (seed phrase) for wallet recovery.
       * 
* * string mnemonic = 2 [json_name = "mnemonic"]; * @param value The bytes for mnemonic to set. * @return This builder for chaining. */ public Builder setMnemonicBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); mnemonic_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.CreateWalletResponse) } // @@protoc_insertion_point(class_scope:pactus.CreateWalletResponse) private static final pactus.WalletOuterClass.CreateWalletResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.CreateWalletResponse(); } public static pactus.WalletOuterClass.CreateWalletResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public CreateWalletResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.CreateWalletResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface LoadWalletRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.LoadWalletRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to load.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to load.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Request message for loading an existing wallet.
   * Deprecated: It will be removed in a future version.
   * 
* * Protobuf type {@code pactus.LoadWalletRequest} */ public static final class LoadWalletRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.LoadWalletRequest) LoadWalletRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "LoadWalletRequest"); } // Use LoadWalletRequest.newBuilder() to construct. private LoadWalletRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private LoadWalletRequest() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.LoadWalletRequest.class, pactus.WalletOuterClass.LoadWalletRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to load.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to load.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.LoadWalletRequest)) { return super.equals(obj); } pactus.WalletOuterClass.LoadWalletRequest other = (pactus.WalletOuterClass.LoadWalletRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.LoadWalletRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.LoadWalletRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.LoadWalletRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for loading an existing wallet.
     * Deprecated: It will be removed in a future version.
     * 
* * Protobuf type {@code pactus.LoadWalletRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.LoadWalletRequest) pactus.WalletOuterClass.LoadWalletRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.LoadWalletRequest.class, pactus.WalletOuterClass.LoadWalletRequest.Builder.class); } // Construct using pactus.WalletOuterClass.LoadWalletRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.LoadWalletRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.LoadWalletRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.LoadWalletRequest build() { pactus.WalletOuterClass.LoadWalletRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.LoadWalletRequest buildPartial() { pactus.WalletOuterClass.LoadWalletRequest result = new pactus.WalletOuterClass.LoadWalletRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.LoadWalletRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.LoadWalletRequest) { return mergeFrom((pactus.WalletOuterClass.LoadWalletRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.LoadWalletRequest other) { if (other == pactus.WalletOuterClass.LoadWalletRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to load.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to load.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to load.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to load.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to load.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.LoadWalletRequest) } // @@protoc_insertion_point(class_scope:pactus.LoadWalletRequest) private static final pactus.WalletOuterClass.LoadWalletRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.LoadWalletRequest(); } public static pactus.WalletOuterClass.LoadWalletRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public LoadWalletRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.LoadWalletRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface LoadWalletResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.LoadWalletResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the loaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the loaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Response message confirming wallet loaded.
   * Deprecated: It will be removed in a future version.
   * 
* * Protobuf type {@code pactus.LoadWalletResponse} */ public static final class LoadWalletResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.LoadWalletResponse) LoadWalletResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "LoadWalletResponse"); } // Use LoadWalletResponse.newBuilder() to construct. private LoadWalletResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private LoadWalletResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.LoadWalletResponse.class, pactus.WalletOuterClass.LoadWalletResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the loaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the loaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.LoadWalletResponse)) { return super.equals(obj); } pactus.WalletOuterClass.LoadWalletResponse other = (pactus.WalletOuterClass.LoadWalletResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.LoadWalletResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.LoadWalletResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.LoadWalletResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message confirming wallet loaded.
     * Deprecated: It will be removed in a future version.
     * 
* * Protobuf type {@code pactus.LoadWalletResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.LoadWalletResponse) pactus.WalletOuterClass.LoadWalletResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.LoadWalletResponse.class, pactus.WalletOuterClass.LoadWalletResponse.Builder.class); } // Construct using pactus.WalletOuterClass.LoadWalletResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_LoadWalletResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.LoadWalletResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.LoadWalletResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.LoadWalletResponse build() { pactus.WalletOuterClass.LoadWalletResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.LoadWalletResponse buildPartial() { pactus.WalletOuterClass.LoadWalletResponse result = new pactus.WalletOuterClass.LoadWalletResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.LoadWalletResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.LoadWalletResponse) { return mergeFrom((pactus.WalletOuterClass.LoadWalletResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.LoadWalletResponse other) { if (other == pactus.WalletOuterClass.LoadWalletResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the loaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the loaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the loaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the loaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the loaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.LoadWalletResponse) } // @@protoc_insertion_point(class_scope:pactus.LoadWalletResponse) private static final pactus.WalletOuterClass.LoadWalletResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.LoadWalletResponse(); } public static pactus.WalletOuterClass.LoadWalletResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public LoadWalletResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.LoadWalletResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface UnloadWalletRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.UnloadWalletRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to unload.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to unload.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Request message for unloading a wallet.
   * Deprecated: It will be removed in a future version.
   * 
* * Protobuf type {@code pactus.UnloadWalletRequest} */ public static final class UnloadWalletRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.UnloadWalletRequest) UnloadWalletRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "UnloadWalletRequest"); } // Use UnloadWalletRequest.newBuilder() to construct. private UnloadWalletRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private UnloadWalletRequest() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UnloadWalletRequest.class, pactus.WalletOuterClass.UnloadWalletRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to unload.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to unload.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.UnloadWalletRequest)) { return super.equals(obj); } pactus.WalletOuterClass.UnloadWalletRequest other = (pactus.WalletOuterClass.UnloadWalletRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UnloadWalletRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UnloadWalletRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.UnloadWalletRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for unloading a wallet.
     * Deprecated: It will be removed in a future version.
     * 
* * Protobuf type {@code pactus.UnloadWalletRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.UnloadWalletRequest) pactus.WalletOuterClass.UnloadWalletRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UnloadWalletRequest.class, pactus.WalletOuterClass.UnloadWalletRequest.Builder.class); } // Construct using pactus.WalletOuterClass.UnloadWalletRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.UnloadWalletRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletRequest build() { pactus.WalletOuterClass.UnloadWalletRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletRequest buildPartial() { pactus.WalletOuterClass.UnloadWalletRequest result = new pactus.WalletOuterClass.UnloadWalletRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.UnloadWalletRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.UnloadWalletRequest) { return mergeFrom((pactus.WalletOuterClass.UnloadWalletRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.UnloadWalletRequest other) { if (other == pactus.WalletOuterClass.UnloadWalletRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to unload.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to unload.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to unload.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to unload.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to unload.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.UnloadWalletRequest) } // @@protoc_insertion_point(class_scope:pactus.UnloadWalletRequest) private static final pactus.WalletOuterClass.UnloadWalletRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.UnloadWalletRequest(); } public static pactus.WalletOuterClass.UnloadWalletRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public UnloadWalletRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface UnloadWalletResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.UnloadWalletResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the unloaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the unloaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Response message confirming wallet unloading.
   * Deprecated: It will be removed in a future version.
   * 
* * Protobuf type {@code pactus.UnloadWalletResponse} */ public static final class UnloadWalletResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.UnloadWalletResponse) UnloadWalletResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "UnloadWalletResponse"); } // Use UnloadWalletResponse.newBuilder() to construct. private UnloadWalletResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private UnloadWalletResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UnloadWalletResponse.class, pactus.WalletOuterClass.UnloadWalletResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the unloaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the unloaded wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.UnloadWalletResponse)) { return super.equals(obj); } pactus.WalletOuterClass.UnloadWalletResponse other = (pactus.WalletOuterClass.UnloadWalletResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UnloadWalletResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UnloadWalletResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.UnloadWalletResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message confirming wallet unloading.
     * Deprecated: It will be removed in a future version.
     * 
* * Protobuf type {@code pactus.UnloadWalletResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.UnloadWalletResponse) pactus.WalletOuterClass.UnloadWalletResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UnloadWalletResponse.class, pactus.WalletOuterClass.UnloadWalletResponse.Builder.class); } // Construct using pactus.WalletOuterClass.UnloadWalletResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_UnloadWalletResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.UnloadWalletResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletResponse build() { pactus.WalletOuterClass.UnloadWalletResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletResponse buildPartial() { pactus.WalletOuterClass.UnloadWalletResponse result = new pactus.WalletOuterClass.UnloadWalletResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.UnloadWalletResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.UnloadWalletResponse) { return mergeFrom((pactus.WalletOuterClass.UnloadWalletResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.UnloadWalletResponse other) { if (other == pactus.WalletOuterClass.UnloadWalletResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the unloaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the unloaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the unloaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the unloaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the unloaded wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.UnloadWalletResponse) } // @@protoc_insertion_point(class_scope:pactus.UnloadWalletResponse) private static final pactus.WalletOuterClass.UnloadWalletResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.UnloadWalletResponse(); } public static pactus.WalletOuterClass.UnloadWalletResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public UnloadWalletResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.UnloadWalletResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorAddressRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorAddressRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The public key of the validator.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ java.lang.String getPublicKey(); /** *
     * The public key of the validator.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ com.google.protobuf.ByteString getPublicKeyBytes(); } /** *
   * Request message for obtaining the validator address associated with a public key.
   * 
* * Protobuf type {@code pactus.GetValidatorAddressRequest} */ public static final class GetValidatorAddressRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorAddressRequest) GetValidatorAddressRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorAddressRequest"); } // Use GetValidatorAddressRequest.newBuilder() to construct. private GetValidatorAddressRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorAddressRequest() { publicKey_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetValidatorAddressRequest.class, pactus.WalletOuterClass.GetValidatorAddressRequest.Builder.class); } public static final int PUBLIC_KEY_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object publicKey_ = ""; /** *
     * The public key of the validator.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ @java.lang.Override public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } } /** *
     * The public key of the validator.
     * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, publicKey_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(publicKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, publicKey_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetValidatorAddressRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetValidatorAddressRequest other = (pactus.WalletOuterClass.GetValidatorAddressRequest) obj; if (!getPublicKey() .equals(other.getPublicKey())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PUBLIC_KEY_FIELD_NUMBER; hash = (53 * hash) + getPublicKey().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetValidatorAddressRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetValidatorAddressRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for obtaining the validator address associated with a public key.
     * 
* * Protobuf type {@code pactus.GetValidatorAddressRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorAddressRequest) pactus.WalletOuterClass.GetValidatorAddressRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetValidatorAddressRequest.class, pactus.WalletOuterClass.GetValidatorAddressRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetValidatorAddressRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; publicKey_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetValidatorAddressRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressRequest build() { pactus.WalletOuterClass.GetValidatorAddressRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressRequest buildPartial() { pactus.WalletOuterClass.GetValidatorAddressRequest result = new pactus.WalletOuterClass.GetValidatorAddressRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetValidatorAddressRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.publicKey_ = publicKey_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetValidatorAddressRequest) { return mergeFrom((pactus.WalletOuterClass.GetValidatorAddressRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetValidatorAddressRequest other) { if (other == pactus.WalletOuterClass.GetValidatorAddressRequest.getDefaultInstance()) return this; if (!other.getPublicKey().isEmpty()) { publicKey_ = other.publicKey_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { publicKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object publicKey_ = ""; /** *
       * The public key of the validator.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The publicKey. */ public java.lang.String getPublicKey() { java.lang.Object ref = publicKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The public key of the validator.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return The bytes for publicKey. */ public com.google.protobuf.ByteString getPublicKeyBytes() { java.lang.Object ref = publicKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The public key of the validator.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The public key of the validator.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @return This builder for chaining. */ public Builder clearPublicKey() { publicKey_ = getDefaultInstance().getPublicKey(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The public key of the validator.
       * 
* * string public_key = 1 [json_name = "publicKey"]; * @param value The bytes for publicKey to set. * @return This builder for chaining. */ public Builder setPublicKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorAddressRequest) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorAddressRequest) private static final pactus.WalletOuterClass.GetValidatorAddressRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetValidatorAddressRequest(); } public static pactus.WalletOuterClass.GetValidatorAddressRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorAddressRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetValidatorAddressResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetValidatorAddressResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The validator address associated with the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The validator address associated with the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Response message containing the validator address corresponding to a public key.
   * 
* * Protobuf type {@code pactus.GetValidatorAddressResponse} */ public static final class GetValidatorAddressResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetValidatorAddressResponse) GetValidatorAddressResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetValidatorAddressResponse"); } // Use GetValidatorAddressResponse.newBuilder() to construct. private GetValidatorAddressResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetValidatorAddressResponse() { address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetValidatorAddressResponse.class, pactus.WalletOuterClass.GetValidatorAddressResponse.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The validator address associated with the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The validator address associated with the public key.
     * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetValidatorAddressResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetValidatorAddressResponse other = (pactus.WalletOuterClass.GetValidatorAddressResponse) obj; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetValidatorAddressResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetValidatorAddressResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message containing the validator address corresponding to a public key.
     * 
* * Protobuf type {@code pactus.GetValidatorAddressResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetValidatorAddressResponse) pactus.WalletOuterClass.GetValidatorAddressResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetValidatorAddressResponse.class, pactus.WalletOuterClass.GetValidatorAddressResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetValidatorAddressResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetValidatorAddressResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetValidatorAddressResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressResponse build() { pactus.WalletOuterClass.GetValidatorAddressResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressResponse buildPartial() { pactus.WalletOuterClass.GetValidatorAddressResponse result = new pactus.WalletOuterClass.GetValidatorAddressResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetValidatorAddressResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetValidatorAddressResponse) { return mergeFrom((pactus.WalletOuterClass.GetValidatorAddressResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetValidatorAddressResponse other) { if (other == pactus.WalletOuterClass.GetValidatorAddressResponse.getDefaultInstance()) return this; if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object address_ = ""; /** *
       * The validator address associated with the public key.
       * 
* * string address = 1 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The validator address associated with the public key.
       * 
* * string address = 1 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The validator address associated with the public key.
       * 
* * string address = 1 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The validator address associated with the public key.
       * 
* * string address = 1 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The validator address associated with the public key.
       * 
* * string address = 1 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetValidatorAddressResponse) } // @@protoc_insertion_point(class_scope:pactus.GetValidatorAddressResponse) private static final pactus.WalletOuterClass.GetValidatorAddressResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetValidatorAddressResponse(); } public static pactus.WalletOuterClass.GetValidatorAddressResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetValidatorAddressResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetValidatorAddressResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignRawTransactionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignRawTransactionRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet used for signing.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet used for signing.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The raw transaction data to be signed.
     * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return The rawTransaction. */ java.lang.String getRawTransaction(); /** *
     * The raw transaction data to be signed.
     * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ com.google.protobuf.ByteString getRawTransactionBytes(); /** *
     * Wallet password required for signing.
     * 
* * string password = 3 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Wallet password required for signing.
     * 
* * string password = 3 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); } /** *
   * Request message for signing a raw transaction.
   * 
* * Protobuf type {@code pactus.SignRawTransactionRequest} */ public static final class SignRawTransactionRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignRawTransactionRequest) SignRawTransactionRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignRawTransactionRequest"); } // Use SignRawTransactionRequest.newBuilder() to construct. private SignRawTransactionRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignRawTransactionRequest() { walletName_ = ""; rawTransaction_ = ""; password_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignRawTransactionRequest.class, pactus.WalletOuterClass.SignRawTransactionRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet used for signing.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet used for signing.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RAW_TRANSACTION_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object rawTransaction_ = ""; /** *
     * The raw transaction data to be signed.
     * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return The rawTransaction. */ @java.lang.Override public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } } /** *
     * The raw transaction data to be signed.
     * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Wallet password required for signing.
     * 
* * string password = 3 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Wallet password required for signing.
     * 
* * string password = 3 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, rawTransaction_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, password_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(rawTransaction_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, rawTransaction_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, password_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SignRawTransactionRequest)) { return super.equals(obj); } pactus.WalletOuterClass.SignRawTransactionRequest other = (pactus.WalletOuterClass.SignRawTransactionRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getRawTransaction() .equals(other.getRawTransaction())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + RAW_TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getRawTransaction().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignRawTransactionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SignRawTransactionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for signing a raw transaction.
     * 
* * Protobuf type {@code pactus.SignRawTransactionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignRawTransactionRequest) pactus.WalletOuterClass.SignRawTransactionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignRawTransactionRequest.class, pactus.WalletOuterClass.SignRawTransactionRequest.Builder.class); } // Construct using pactus.WalletOuterClass.SignRawTransactionRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; rawTransaction_ = ""; password_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.SignRawTransactionRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionRequest build() { pactus.WalletOuterClass.SignRawTransactionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionRequest buildPartial() { pactus.WalletOuterClass.SignRawTransactionRequest result = new pactus.WalletOuterClass.SignRawTransactionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SignRawTransactionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.rawTransaction_ = rawTransaction_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.password_ = password_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SignRawTransactionRequest) { return mergeFrom((pactus.WalletOuterClass.SignRawTransactionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SignRawTransactionRequest other) { if (other == pactus.WalletOuterClass.SignRawTransactionRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getRawTransaction().isEmpty()) { rawTransaction_ = other.rawTransaction_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { rawTransaction_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet used for signing.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet used for signing.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet used for signing.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet used for signing.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet used for signing.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object rawTransaction_ = ""; /** *
       * The raw transaction data to be signed.
       * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return The rawTransaction. */ public java.lang.String getRawTransaction() { java.lang.Object ref = rawTransaction_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawTransaction_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The raw transaction data to be signed.
       * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return The bytes for rawTransaction. */ public com.google.protobuf.ByteString getRawTransactionBytes() { java.lang.Object ref = rawTransaction_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); rawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The raw transaction data to be signed.
       * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @param value The rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransaction( java.lang.String value) { if (value == null) { throw new NullPointerException(); } rawTransaction_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The raw transaction data to be signed.
       * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @return This builder for chaining. */ public Builder clearRawTransaction() { rawTransaction_ = getDefaultInstance().getRawTransaction(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The raw transaction data to be signed.
       * 
* * string raw_transaction = 2 [json_name = "rawTransaction"]; * @param value The bytes for rawTransaction to set. * @return This builder for chaining. */ public Builder setRawTransactionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); rawTransaction_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Wallet password required for signing.
       * 
* * string password = 3 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Wallet password required for signing.
       * 
* * string password = 3 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Wallet password required for signing.
       * 
* * string password = 3 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Wallet password required for signing.
       * 
* * string password = 3 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * Wallet password required for signing.
       * 
* * string password = 3 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignRawTransactionRequest) } // @@protoc_insertion_point(class_scope:pactus.SignRawTransactionRequest) private static final pactus.WalletOuterClass.SignRawTransactionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SignRawTransactionRequest(); } public static pactus.WalletOuterClass.SignRawTransactionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignRawTransactionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignRawTransactionResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignRawTransactionResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The ID of the signed transaction.
     * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return The transactionId. */ java.lang.String getTransactionId(); /** *
     * The ID of the signed transaction.
     * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return The bytes for transactionId. */ com.google.protobuf.ByteString getTransactionIdBytes(); /** *
     * The signed raw transaction data.
     * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return The signedRawTransaction. */ java.lang.String getSignedRawTransaction(); /** *
     * The signed raw transaction data.
     * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return The bytes for signedRawTransaction. */ com.google.protobuf.ByteString getSignedRawTransactionBytes(); } /** *
   * Response message contains the transaction ID and signed raw transaction.
   * 
* * Protobuf type {@code pactus.SignRawTransactionResponse} */ public static final class SignRawTransactionResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignRawTransactionResponse) SignRawTransactionResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignRawTransactionResponse"); } // Use SignRawTransactionResponse.newBuilder() to construct. private SignRawTransactionResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignRawTransactionResponse() { transactionId_ = ""; signedRawTransaction_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignRawTransactionResponse.class, pactus.WalletOuterClass.SignRawTransactionResponse.Builder.class); } public static final int TRANSACTION_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object transactionId_ = ""; /** *
     * The ID of the signed transaction.
     * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return The transactionId. */ @java.lang.Override public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); transactionId_ = s; return s; } } /** *
     * The ID of the signed transaction.
     * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return The bytes for transactionId. */ @java.lang.Override public com.google.protobuf.ByteString getTransactionIdBytes() { java.lang.Object ref = transactionId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SIGNED_RAW_TRANSACTION_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object signedRawTransaction_ = ""; /** *
     * The signed raw transaction data.
     * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return The signedRawTransaction. */ @java.lang.Override public java.lang.String getSignedRawTransaction() { java.lang.Object ref = signedRawTransaction_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signedRawTransaction_ = s; return s; } } /** *
     * The signed raw transaction data.
     * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return The bytes for signedRawTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getSignedRawTransactionBytes() { java.lang.Object ref = signedRawTransaction_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signedRawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(transactionId_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, transactionId_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signedRawTransaction_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, signedRawTransaction_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(transactionId_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, transactionId_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signedRawTransaction_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, signedRawTransaction_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SignRawTransactionResponse)) { return super.equals(obj); } pactus.WalletOuterClass.SignRawTransactionResponse other = (pactus.WalletOuterClass.SignRawTransactionResponse) obj; if (!getTransactionId() .equals(other.getTransactionId())) return false; if (!getSignedRawTransaction() .equals(other.getSignedRawTransaction())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRANSACTION_ID_FIELD_NUMBER; hash = (53 * hash) + getTransactionId().hashCode(); hash = (37 * hash) + SIGNED_RAW_TRANSACTION_FIELD_NUMBER; hash = (53 * hash) + getSignedRawTransaction().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignRawTransactionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SignRawTransactionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the transaction ID and signed raw transaction.
     * 
* * Protobuf type {@code pactus.SignRawTransactionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignRawTransactionResponse) pactus.WalletOuterClass.SignRawTransactionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignRawTransactionResponse.class, pactus.WalletOuterClass.SignRawTransactionResponse.Builder.class); } // Construct using pactus.WalletOuterClass.SignRawTransactionResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; transactionId_ = ""; signedRawTransaction_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SignRawTransactionResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.SignRawTransactionResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionResponse build() { pactus.WalletOuterClass.SignRawTransactionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionResponse buildPartial() { pactus.WalletOuterClass.SignRawTransactionResponse result = new pactus.WalletOuterClass.SignRawTransactionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SignRawTransactionResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.transactionId_ = transactionId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.signedRawTransaction_ = signedRawTransaction_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SignRawTransactionResponse) { return mergeFrom((pactus.WalletOuterClass.SignRawTransactionResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SignRawTransactionResponse other) { if (other == pactus.WalletOuterClass.SignRawTransactionResponse.getDefaultInstance()) return this; if (!other.getTransactionId().isEmpty()) { transactionId_ = other.transactionId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getSignedRawTransaction().isEmpty()) { signedRawTransaction_ = other.signedRawTransaction_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { transactionId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { signedRawTransaction_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object transactionId_ = ""; /** *
       * The ID of the signed transaction.
       * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return The transactionId. */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); transactionId_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The ID of the signed transaction.
       * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return The bytes for transactionId. */ public com.google.protobuf.ByteString getTransactionIdBytes() { java.lang.Object ref = transactionId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The ID of the signed transaction.
       * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @param value The transactionId to set. * @return This builder for chaining. */ public Builder setTransactionId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } transactionId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The ID of the signed transaction.
       * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @return This builder for chaining. */ public Builder clearTransactionId() { transactionId_ = getDefaultInstance().getTransactionId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The ID of the signed transaction.
       * 
* * string transaction_id = 1 [json_name = "transactionId"]; * @param value The bytes for transactionId to set. * @return This builder for chaining. */ public Builder setTransactionIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); transactionId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object signedRawTransaction_ = ""; /** *
       * The signed raw transaction data.
       * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return The signedRawTransaction. */ public java.lang.String getSignedRawTransaction() { java.lang.Object ref = signedRawTransaction_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signedRawTransaction_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signed raw transaction data.
       * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return The bytes for signedRawTransaction. */ public com.google.protobuf.ByteString getSignedRawTransactionBytes() { java.lang.Object ref = signedRawTransaction_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signedRawTransaction_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signed raw transaction data.
       * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @param value The signedRawTransaction to set. * @return This builder for chaining. */ public Builder setSignedRawTransaction( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signedRawTransaction_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The signed raw transaction data.
       * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @return This builder for chaining. */ public Builder clearSignedRawTransaction() { signedRawTransaction_ = getDefaultInstance().getSignedRawTransaction(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The signed raw transaction data.
       * 
* * string signed_raw_transaction = 2 [json_name = "signedRawTransaction"]; * @param value The bytes for signedRawTransaction to set. * @return This builder for chaining. */ public Builder setSignedRawTransactionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signedRawTransaction_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignRawTransactionResponse) } // @@protoc_insertion_point(class_scope:pactus.SignRawTransactionResponse) private static final pactus.WalletOuterClass.SignRawTransactionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SignRawTransactionResponse(); } public static pactus.WalletOuterClass.SignRawTransactionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignRawTransactionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SignRawTransactionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTotalBalanceRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTotalBalanceRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to get the total balance.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to get the total balance.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Request message for obtaining the total available balance of a wallet.
   * 
* * Protobuf type {@code pactus.GetTotalBalanceRequest} */ public static final class GetTotalBalanceRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTotalBalanceRequest) GetTotalBalanceRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTotalBalanceRequest"); } // Use GetTotalBalanceRequest.newBuilder() to construct. private GetTotalBalanceRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTotalBalanceRequest() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalBalanceRequest.class, pactus.WalletOuterClass.GetTotalBalanceRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to get the total balance.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to get the total balance.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetTotalBalanceRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetTotalBalanceRequest other = (pactus.WalletOuterClass.GetTotalBalanceRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalBalanceRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetTotalBalanceRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for obtaining the total available balance of a wallet.
     * 
* * Protobuf type {@code pactus.GetTotalBalanceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTotalBalanceRequest) pactus.WalletOuterClass.GetTotalBalanceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalBalanceRequest.class, pactus.WalletOuterClass.GetTotalBalanceRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetTotalBalanceRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetTotalBalanceRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceRequest build() { pactus.WalletOuterClass.GetTotalBalanceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceRequest buildPartial() { pactus.WalletOuterClass.GetTotalBalanceRequest result = new pactus.WalletOuterClass.GetTotalBalanceRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetTotalBalanceRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetTotalBalanceRequest) { return mergeFrom((pactus.WalletOuterClass.GetTotalBalanceRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetTotalBalanceRequest other) { if (other == pactus.WalletOuterClass.GetTotalBalanceRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to get the total balance.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to get the total balance.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to get the total balance.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to get the total balance.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to get the total balance.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetTotalBalanceRequest) } // @@protoc_insertion_point(class_scope:pactus.GetTotalBalanceRequest) private static final pactus.WalletOuterClass.GetTotalBalanceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetTotalBalanceRequest(); } public static pactus.WalletOuterClass.GetTotalBalanceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTotalBalanceRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTotalBalanceResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTotalBalanceResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The total balance of the wallet in NanoPAC.
     * 
* * int64 total_balance = 2 [json_name = "totalBalance"]; * @return The totalBalance. */ long getTotalBalance(); } /** *
   * Response message contains the total available balance of the wallet.
   * 
* * Protobuf type {@code pactus.GetTotalBalanceResponse} */ public static final class GetTotalBalanceResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTotalBalanceResponse) GetTotalBalanceResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTotalBalanceResponse"); } // Use GetTotalBalanceResponse.newBuilder() to construct. private GetTotalBalanceResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTotalBalanceResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalBalanceResponse.class, pactus.WalletOuterClass.GetTotalBalanceResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TOTAL_BALANCE_FIELD_NUMBER = 2; private long totalBalance_ = 0L; /** *
     * The total balance of the wallet in NanoPAC.
     * 
* * int64 total_balance = 2 [json_name = "totalBalance"]; * @return The totalBalance. */ @java.lang.Override public long getTotalBalance() { return totalBalance_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (totalBalance_ != 0L) { output.writeInt64(2, totalBalance_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (totalBalance_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, totalBalance_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetTotalBalanceResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetTotalBalanceResponse other = (pactus.WalletOuterClass.GetTotalBalanceResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (getTotalBalance() != other.getTotalBalance()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + TOTAL_BALANCE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTotalBalance()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalBalanceResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetTotalBalanceResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the total available balance of the wallet.
     * 
* * Protobuf type {@code pactus.GetTotalBalanceResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTotalBalanceResponse) pactus.WalletOuterClass.GetTotalBalanceResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalBalanceResponse.class, pactus.WalletOuterClass.GetTotalBalanceResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetTotalBalanceResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; totalBalance_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalBalanceResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetTotalBalanceResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceResponse build() { pactus.WalletOuterClass.GetTotalBalanceResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceResponse buildPartial() { pactus.WalletOuterClass.GetTotalBalanceResponse result = new pactus.WalletOuterClass.GetTotalBalanceResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetTotalBalanceResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.totalBalance_ = totalBalance_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetTotalBalanceResponse) { return mergeFrom((pactus.WalletOuterClass.GetTotalBalanceResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetTotalBalanceResponse other) { if (other == pactus.WalletOuterClass.GetTotalBalanceResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.getTotalBalance() != 0L) { setTotalBalance(other.getTotalBalance()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { totalBalance_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private long totalBalance_ ; /** *
       * The total balance of the wallet in NanoPAC.
       * 
* * int64 total_balance = 2 [json_name = "totalBalance"]; * @return The totalBalance. */ @java.lang.Override public long getTotalBalance() { return totalBalance_; } /** *
       * The total balance of the wallet in NanoPAC.
       * 
* * int64 total_balance = 2 [json_name = "totalBalance"]; * @param value The totalBalance to set. * @return This builder for chaining. */ public Builder setTotalBalance(long value) { totalBalance_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The total balance of the wallet in NanoPAC.
       * 
* * int64 total_balance = 2 [json_name = "totalBalance"]; * @return This builder for chaining. */ public Builder clearTotalBalance() { bitField0_ = (bitField0_ & ~0x00000002); totalBalance_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetTotalBalanceResponse) } // @@protoc_insertion_point(class_scope:pactus.GetTotalBalanceResponse) private static final pactus.WalletOuterClass.GetTotalBalanceResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetTotalBalanceResponse(); } public static pactus.WalletOuterClass.GetTotalBalanceResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTotalBalanceResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetTotalBalanceResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignMessageRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignMessageRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to sign with.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to sign with.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Wallet password required for signing.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Wallet password required for signing.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); /** *
     * The address whose private key should be used for signing the message.
     * 
* * string address = 3 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address whose private key should be used for signing the message.
     * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The arbitrary message to be signed.
     * 
* * string message = 4 [json_name = "message"]; * @return The message. */ java.lang.String getMessage(); /** *
     * The arbitrary message to be signed.
     * 
* * string message = 4 [json_name = "message"]; * @return The bytes for message. */ com.google.protobuf.ByteString getMessageBytes(); } /** *
   * Request message to sign an arbitrary message.
   * 
* * Protobuf type {@code pactus.SignMessageRequest} */ public static final class SignMessageRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignMessageRequest) SignMessageRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignMessageRequest"); } // Use SignMessageRequest.newBuilder() to construct. private SignMessageRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignMessageRequest() { walletName_ = ""; password_ = ""; address_ = ""; message_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignMessageRequest.class, pactus.WalletOuterClass.SignMessageRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to sign with.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to sign with.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Wallet password required for signing.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Wallet password required for signing.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address whose private key should be used for signing the message.
     * 
* * string address = 3 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address whose private key should be used for signing the message.
     * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MESSAGE_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object message_ = ""; /** *
     * The arbitrary message to be signed.
     * 
* * string message = 4 [json_name = "message"]; * @return The message. */ @java.lang.Override public java.lang.String getMessage() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } } /** *
     * The arbitrary message to be signed.
     * 
* * string message = 4 [json_name = "message"]; * @return The bytes for message. */ @java.lang.Override public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, password_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(message_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, message_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, password_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(message_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, message_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SignMessageRequest)) { return super.equals(obj); } pactus.WalletOuterClass.SignMessageRequest other = (pactus.WalletOuterClass.SignMessageRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getMessage() .equals(other.getMessage())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getMessage().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignMessageRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignMessageRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SignMessageRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message to sign an arbitrary message.
     * 
* * Protobuf type {@code pactus.SignMessageRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignMessageRequest) pactus.WalletOuterClass.SignMessageRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignMessageRequest.class, pactus.WalletOuterClass.SignMessageRequest.Builder.class); } // Construct using pactus.WalletOuterClass.SignMessageRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; password_ = ""; address_ = ""; message_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SignMessageRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.SignMessageRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SignMessageRequest build() { pactus.WalletOuterClass.SignMessageRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SignMessageRequest buildPartial() { pactus.WalletOuterClass.SignMessageRequest result = new pactus.WalletOuterClass.SignMessageRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SignMessageRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.password_ = password_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.message_ = message_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SignMessageRequest) { return mergeFrom((pactus.WalletOuterClass.SignMessageRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SignMessageRequest other) { if (other == pactus.WalletOuterClass.SignMessageRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getMessage().isEmpty()) { message_ = other.message_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { message_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to sign with.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to sign with.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to sign with.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to sign with.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to sign with.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Wallet password required for signing.
       * 
* * string password = 2 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Wallet password required for signing.
       * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Wallet password required for signing.
       * 
* * string password = 2 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Wallet password required for signing.
       * 
* * string password = 2 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Wallet password required for signing.
       * 
* * string password = 2 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address whose private key should be used for signing the message.
       * 
* * string address = 3 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address whose private key should be used for signing the message.
       * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address whose private key should be used for signing the message.
       * 
* * string address = 3 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The address whose private key should be used for signing the message.
       * 
* * string address = 3 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The address whose private key should be used for signing the message.
       * 
* * string address = 3 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object message_ = ""; /** *
       * The arbitrary message to be signed.
       * 
* * string message = 4 [json_name = "message"]; * @return The message. */ public java.lang.String getMessage() { java.lang.Object ref = message_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The arbitrary message to be signed.
       * 
* * string message = 4 [json_name = "message"]; * @return The bytes for message. */ public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The arbitrary message to be signed.
       * 
* * string message = 4 [json_name = "message"]; * @param value The message to set. * @return This builder for chaining. */ public Builder setMessage( java.lang.String value) { if (value == null) { throw new NullPointerException(); } message_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The arbitrary message to be signed.
       * 
* * string message = 4 [json_name = "message"]; * @return This builder for chaining. */ public Builder clearMessage() { message_ = getDefaultInstance().getMessage(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The arbitrary message to be signed.
       * 
* * string message = 4 [json_name = "message"]; * @param value The bytes for message to set. * @return This builder for chaining. */ public Builder setMessageBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); message_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignMessageRequest) } // @@protoc_insertion_point(class_scope:pactus.SignMessageRequest) private static final pactus.WalletOuterClass.SignMessageRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SignMessageRequest(); } public static pactus.WalletOuterClass.SignMessageRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignMessageRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SignMessageRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SignMessageResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SignMessageResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ java.lang.String getSignature(); /** *
     * The signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ com.google.protobuf.ByteString getSignatureBytes(); } /** *
   * Response message contains message signature.
   * 
* * Protobuf type {@code pactus.SignMessageResponse} */ public static final class SignMessageResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SignMessageResponse) SignMessageResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SignMessageResponse"); } // Use SignMessageResponse.newBuilder() to construct. private SignMessageResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SignMessageResponse() { signature_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignMessageResponse.class, pactus.WalletOuterClass.SignMessageResponse.Builder.class); } public static final int SIGNATURE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object signature_ = ""; /** *
     * The signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ @java.lang.Override public java.lang.String getSignature() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } } /** *
     * The signature in hexadecimal format.
     * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ @java.lang.Override public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, signature_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(signature_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, signature_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SignMessageResponse)) { return super.equals(obj); } pactus.WalletOuterClass.SignMessageResponse other = (pactus.WalletOuterClass.SignMessageResponse) obj; if (!getSignature() .equals(other.getSignature())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SIGNATURE_FIELD_NUMBER; hash = (53 * hash) + getSignature().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignMessageResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SignMessageResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SignMessageResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains message signature.
     * 
* * Protobuf type {@code pactus.SignMessageResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SignMessageResponse) pactus.WalletOuterClass.SignMessageResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SignMessageResponse.class, pactus.WalletOuterClass.SignMessageResponse.Builder.class); } // Construct using pactus.WalletOuterClass.SignMessageResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; signature_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SignMessageResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SignMessageResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.SignMessageResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SignMessageResponse build() { pactus.WalletOuterClass.SignMessageResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SignMessageResponse buildPartial() { pactus.WalletOuterClass.SignMessageResponse result = new pactus.WalletOuterClass.SignMessageResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SignMessageResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.signature_ = signature_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SignMessageResponse) { return mergeFrom((pactus.WalletOuterClass.SignMessageResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SignMessageResponse other) { if (other == pactus.WalletOuterClass.SignMessageResponse.getDefaultInstance()) return this; if (!other.getSignature().isEmpty()) { signature_ = other.signature_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { signature_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object signature_ = ""; /** *
       * The signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return The signature. */ public java.lang.String getSignature() { java.lang.Object ref = signature_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); signature_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return The bytes for signature. */ public com.google.protobuf.ByteString getSignatureBytes() { java.lang.Object ref = signature_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); signature_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @param value The signature to set. * @return This builder for chaining. */ public Builder setSignature( java.lang.String value) { if (value == null) { throw new NullPointerException(); } signature_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @return This builder for chaining. */ public Builder clearSignature() { signature_ = getDefaultInstance().getSignature(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The signature in hexadecimal format.
       * 
* * string signature = 1 [json_name = "signature"]; * @param value The bytes for signature to set. * @return This builder for chaining. */ public Builder setSignatureBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); signature_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SignMessageResponse) } // @@protoc_insertion_point(class_scope:pactus.SignMessageResponse) private static final pactus.WalletOuterClass.SignMessageResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SignMessageResponse(); } public static pactus.WalletOuterClass.SignMessageResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SignMessageResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SignMessageResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTotalStakeRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTotalStakeRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to get the total stake.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to get the total stake.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Request message for obtaining the total stake of a wallet.
   * 
* * Protobuf type {@code pactus.GetTotalStakeRequest} */ public static final class GetTotalStakeRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTotalStakeRequest) GetTotalStakeRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTotalStakeRequest"); } // Use GetTotalStakeRequest.newBuilder() to construct. private GetTotalStakeRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTotalStakeRequest() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalStakeRequest.class, pactus.WalletOuterClass.GetTotalStakeRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to get the total stake.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to get the total stake.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetTotalStakeRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetTotalStakeRequest other = (pactus.WalletOuterClass.GetTotalStakeRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalStakeRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetTotalStakeRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for obtaining the total stake of a wallet.
     * 
* * Protobuf type {@code pactus.GetTotalStakeRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTotalStakeRequest) pactus.WalletOuterClass.GetTotalStakeRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalStakeRequest.class, pactus.WalletOuterClass.GetTotalStakeRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetTotalStakeRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetTotalStakeRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeRequest build() { pactus.WalletOuterClass.GetTotalStakeRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeRequest buildPartial() { pactus.WalletOuterClass.GetTotalStakeRequest result = new pactus.WalletOuterClass.GetTotalStakeRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetTotalStakeRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetTotalStakeRequest) { return mergeFrom((pactus.WalletOuterClass.GetTotalStakeRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetTotalStakeRequest other) { if (other == pactus.WalletOuterClass.GetTotalStakeRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to get the total stake.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to get the total stake.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to get the total stake.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to get the total stake.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to get the total stake.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetTotalStakeRequest) } // @@protoc_insertion_point(class_scope:pactus.GetTotalStakeRequest) private static final pactus.WalletOuterClass.GetTotalStakeRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetTotalStakeRequest(); } public static pactus.WalletOuterClass.GetTotalStakeRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTotalStakeRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetTotalStakeResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetTotalStakeResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The total stake amount in NanoPAC.
     * 
* * int64 total_stake = 2 [json_name = "totalStake"]; * @return The totalStake. */ long getTotalStake(); } /** *
   * Response message contains the total stake of the wallet.
   * 
* * Protobuf type {@code pactus.GetTotalStakeResponse} */ public static final class GetTotalStakeResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetTotalStakeResponse) GetTotalStakeResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetTotalStakeResponse"); } // Use GetTotalStakeResponse.newBuilder() to construct. private GetTotalStakeResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetTotalStakeResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalStakeResponse.class, pactus.WalletOuterClass.GetTotalStakeResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TOTAL_STAKE_FIELD_NUMBER = 2; private long totalStake_ = 0L; /** *
     * The total stake amount in NanoPAC.
     * 
* * int64 total_stake = 2 [json_name = "totalStake"]; * @return The totalStake. */ @java.lang.Override public long getTotalStake() { return totalStake_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (totalStake_ != 0L) { output.writeInt64(2, totalStake_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (totalStake_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, totalStake_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetTotalStakeResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetTotalStakeResponse other = (pactus.WalletOuterClass.GetTotalStakeResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (getTotalStake() != other.getTotalStake()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + TOTAL_STAKE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTotalStake()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetTotalStakeResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetTotalStakeResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains the total stake of the wallet.
     * 
* * Protobuf type {@code pactus.GetTotalStakeResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetTotalStakeResponse) pactus.WalletOuterClass.GetTotalStakeResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetTotalStakeResponse.class, pactus.WalletOuterClass.GetTotalStakeResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetTotalStakeResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; totalStake_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetTotalStakeResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetTotalStakeResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeResponse build() { pactus.WalletOuterClass.GetTotalStakeResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeResponse buildPartial() { pactus.WalletOuterClass.GetTotalStakeResponse result = new pactus.WalletOuterClass.GetTotalStakeResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetTotalStakeResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.totalStake_ = totalStake_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetTotalStakeResponse) { return mergeFrom((pactus.WalletOuterClass.GetTotalStakeResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetTotalStakeResponse other) { if (other == pactus.WalletOuterClass.GetTotalStakeResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.getTotalStake() != 0L) { setTotalStake(other.getTotalStake()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { totalStake_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private long totalStake_ ; /** *
       * The total stake amount in NanoPAC.
       * 
* * int64 total_stake = 2 [json_name = "totalStake"]; * @return The totalStake. */ @java.lang.Override public long getTotalStake() { return totalStake_; } /** *
       * The total stake amount in NanoPAC.
       * 
* * int64 total_stake = 2 [json_name = "totalStake"]; * @param value The totalStake to set. * @return This builder for chaining. */ public Builder setTotalStake(long value) { totalStake_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The total stake amount in NanoPAC.
       * 
* * int64 total_stake = 2 [json_name = "totalStake"]; * @return This builder for chaining. */ public Builder clearTotalStake() { bitField0_ = (bitField0_ & ~0x00000002); totalStake_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetTotalStakeResponse) } // @@protoc_insertion_point(class_scope:pactus.GetTotalStakeResponse) private static final pactus.WalletOuterClass.GetTotalStakeResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetTotalStakeResponse(); } public static pactus.WalletOuterClass.GetTotalStakeResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetTotalStakeResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetTotalStakeResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetAddressInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetAddressInfoRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The address to query.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address to query.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Request message for getting address information.
   * 
* * Protobuf type {@code pactus.GetAddressInfoRequest} */ public static final class GetAddressInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetAddressInfoRequest) GetAddressInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetAddressInfoRequest"); } // Use GetAddressInfoRequest.newBuilder() to construct. private GetAddressInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetAddressInfoRequest() { walletName_ = ""; address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetAddressInfoRequest.class, pactus.WalletOuterClass.GetAddressInfoRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address to query.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address to query.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetAddressInfoRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetAddressInfoRequest other = (pactus.WalletOuterClass.GetAddressInfoRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetAddressInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetAddressInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for getting address information.
     * 
* * Protobuf type {@code pactus.GetAddressInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetAddressInfoRequest) pactus.WalletOuterClass.GetAddressInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetAddressInfoRequest.class, pactus.WalletOuterClass.GetAddressInfoRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetAddressInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetAddressInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoRequest build() { pactus.WalletOuterClass.GetAddressInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoRequest buildPartial() { pactus.WalletOuterClass.GetAddressInfoRequest result = new pactus.WalletOuterClass.GetAddressInfoRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetAddressInfoRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetAddressInfoRequest) { return mergeFrom((pactus.WalletOuterClass.GetAddressInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetAddressInfoRequest other) { if (other == pactus.WalletOuterClass.GetAddressInfoRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address to query.
       * 
* * string address = 2 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address to query.
       * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address to query.
       * 
* * string address = 2 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address to query.
       * 
* * string address = 2 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address to query.
       * 
* * string address = 2 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetAddressInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetAddressInfoRequest) private static final pactus.WalletOuterClass.GetAddressInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetAddressInfoRequest(); } public static pactus.WalletOuterClass.GetAddressInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetAddressInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetAddressInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetAddressInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Detailed information about the address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return Whether the addr field is set. */ boolean hasAddr(); /** *
     * Detailed information about the address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return The addr. */ pactus.WalletOuterClass.AddressInfo getAddr(); /** *
     * Detailed information about the address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ pactus.WalletOuterClass.AddressInfoOrBuilder getAddrOrBuilder(); } /** *
   * Response message contains address details.
   * 
* * Protobuf type {@code pactus.GetAddressInfoResponse} */ public static final class GetAddressInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetAddressInfoResponse) GetAddressInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetAddressInfoResponse"); } // Use GetAddressInfoResponse.newBuilder() to construct. private GetAddressInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetAddressInfoResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetAddressInfoResponse.class, pactus.WalletOuterClass.GetAddressInfoResponse.Builder.class); } private int bitField0_; public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDR_FIELD_NUMBER = 2; private pactus.WalletOuterClass.AddressInfo addr_; /** *
     * Detailed information about the address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return Whether the addr field is set. */ @java.lang.Override public boolean hasAddr() { return ((bitField0_ & 0x00000001) != 0); } /** *
     * Detailed information about the address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return The addr. */ @java.lang.Override public pactus.WalletOuterClass.AddressInfo getAddr() { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } /** *
     * Detailed information about the address.
     * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ @java.lang.Override public pactus.WalletOuterClass.AddressInfoOrBuilder getAddrOrBuilder() { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getAddr()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getAddr()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetAddressInfoResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetAddressInfoResponse other = (pactus.WalletOuterClass.GetAddressInfoResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (hasAddr() != other.hasAddr()) return false; if (hasAddr()) { if (!getAddr() .equals(other.getAddr())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); if (hasAddr()) { hash = (37 * hash) + ADDR_FIELD_NUMBER; hash = (53 * hash) + getAddr().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetAddressInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetAddressInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains address details.
     * 
* * Protobuf type {@code pactus.GetAddressInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetAddressInfoResponse) pactus.WalletOuterClass.GetAddressInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetAddressInfoResponse.class, pactus.WalletOuterClass.GetAddressInfoResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetAddressInfoResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage .alwaysUseFieldBuilders) { internalGetAddrFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; addr_ = null; if (addrBuilder_ != null) { addrBuilder_.dispose(); addrBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetAddressInfoResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetAddressInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoResponse build() { pactus.WalletOuterClass.GetAddressInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoResponse buildPartial() { pactus.WalletOuterClass.GetAddressInfoResponse result = new pactus.WalletOuterClass.GetAddressInfoResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetAddressInfoResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.addr_ = addrBuilder_ == null ? addr_ : addrBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetAddressInfoResponse) { return mergeFrom((pactus.WalletOuterClass.GetAddressInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetAddressInfoResponse other) { if (other == pactus.WalletOuterClass.GetAddressInfoResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasAddr()) { mergeAddr(other.getAddr()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( internalGetAddrFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private pactus.WalletOuterClass.AddressInfo addr_; private com.google.protobuf.SingleFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder> addrBuilder_; /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return Whether the addr field is set. */ public boolean hasAddr() { return ((bitField0_ & 0x00000002) != 0); } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; * @return The addr. */ public pactus.WalletOuterClass.AddressInfo getAddr() { if (addrBuilder_ == null) { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } else { return addrBuilder_.getMessage(); } } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder setAddr(pactus.WalletOuterClass.AddressInfo value) { if (addrBuilder_ == null) { if (value == null) { throw new NullPointerException(); } addr_ = value; } else { addrBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder setAddr( pactus.WalletOuterClass.AddressInfo.Builder builderForValue) { if (addrBuilder_ == null) { addr_ = builderForValue.build(); } else { addrBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder mergeAddr(pactus.WalletOuterClass.AddressInfo value) { if (addrBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && addr_ != null && addr_ != pactus.WalletOuterClass.AddressInfo.getDefaultInstance()) { getAddrBuilder().mergeFrom(value); } else { addr_ = value; } } else { addrBuilder_.mergeFrom(value); } if (addr_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public Builder clearAddr() { bitField0_ = (bitField0_ & ~0x00000002); addr_ = null; if (addrBuilder_ != null) { addrBuilder_.dispose(); addrBuilder_ = null; } onChanged(); return this; } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public pactus.WalletOuterClass.AddressInfo.Builder getAddrBuilder() { bitField0_ |= 0x00000002; onChanged(); return internalGetAddrFieldBuilder().getBuilder(); } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ public pactus.WalletOuterClass.AddressInfoOrBuilder getAddrOrBuilder() { if (addrBuilder_ != null) { return addrBuilder_.getMessageOrBuilder(); } else { return addr_ == null ? pactus.WalletOuterClass.AddressInfo.getDefaultInstance() : addr_; } } /** *
       * Detailed information about the address.
       * 
* * .pactus.AddressInfo addr = 2 [json_name = "addr"]; */ private com.google.protobuf.SingleFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder> internalGetAddrFieldBuilder() { if (addrBuilder_ == null) { addrBuilder_ = new com.google.protobuf.SingleFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder>( getAddr(), getParentForChildren(), isClean()); addr_ = null; } return addrBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.GetAddressInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetAddressInfoResponse) private static final pactus.WalletOuterClass.GetAddressInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetAddressInfoResponse(); } public static pactus.WalletOuterClass.GetAddressInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetAddressInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetAddressInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SetAddressLabelRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SetAddressLabelRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Wallet password required for modification.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Wallet password required for modification.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); /** *
     * The address to label.
     * 
* * string address = 3 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address to label.
     * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The new label for the address.
     * 
* * string label = 4 [json_name = "label"]; * @return The label. */ java.lang.String getLabel(); /** *
     * The new label for the address.
     * 
* * string label = 4 [json_name = "label"]; * @return The bytes for label. */ com.google.protobuf.ByteString getLabelBytes(); } /** *
   * Request message for setting address label.
   * 
* * Protobuf type {@code pactus.SetAddressLabelRequest} */ public static final class SetAddressLabelRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SetAddressLabelRequest) SetAddressLabelRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SetAddressLabelRequest"); } // Use SetAddressLabelRequest.newBuilder() to construct. private SetAddressLabelRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SetAddressLabelRequest() { walletName_ = ""; password_ = ""; address_ = ""; label_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetAddressLabelRequest.class, pactus.WalletOuterClass.SetAddressLabelRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Wallet password required for modification.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Wallet password required for modification.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address to label.
     * 
* * string address = 3 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address to label.
     * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LABEL_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object label_ = ""; /** *
     * The new label for the address.
     * 
* * string label = 4 [json_name = "label"]; * @return The label. */ @java.lang.Override public java.lang.String getLabel() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } } /** *
     * The new label for the address.
     * 
* * string label = 4 [json_name = "label"]; * @return The bytes for label. */ @java.lang.Override public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, password_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, label_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, password_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, label_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SetAddressLabelRequest)) { return super.equals(obj); } pactus.WalletOuterClass.SetAddressLabelRequest other = (pactus.WalletOuterClass.SetAddressLabelRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getLabel() .equals(other.getLabel())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + LABEL_FIELD_NUMBER; hash = (53 * hash) + getLabel().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetAddressLabelRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SetAddressLabelRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for setting address label.
     * 
* * Protobuf type {@code pactus.SetAddressLabelRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SetAddressLabelRequest) pactus.WalletOuterClass.SetAddressLabelRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetAddressLabelRequest.class, pactus.WalletOuterClass.SetAddressLabelRequest.Builder.class); } // Construct using pactus.WalletOuterClass.SetAddressLabelRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; password_ = ""; address_ = ""; label_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.SetAddressLabelRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelRequest build() { pactus.WalletOuterClass.SetAddressLabelRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelRequest buildPartial() { pactus.WalletOuterClass.SetAddressLabelRequest result = new pactus.WalletOuterClass.SetAddressLabelRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SetAddressLabelRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.password_ = password_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.label_ = label_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SetAddressLabelRequest) { return mergeFrom((pactus.WalletOuterClass.SetAddressLabelRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SetAddressLabelRequest other) { if (other == pactus.WalletOuterClass.SetAddressLabelRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getLabel().isEmpty()) { label_ = other.label_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { label_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Wallet password required for modification.
       * 
* * string password = 2 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Wallet password required for modification.
       * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Wallet password required for modification.
       * 
* * string password = 2 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Wallet password required for modification.
       * 
* * string password = 2 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Wallet password required for modification.
       * 
* * string password = 2 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address to label.
       * 
* * string address = 3 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address to label.
       * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address to label.
       * 
* * string address = 3 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The address to label.
       * 
* * string address = 3 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The address to label.
       * 
* * string address = 3 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object label_ = ""; /** *
       * The new label for the address.
       * 
* * string label = 4 [json_name = "label"]; * @return The label. */ public java.lang.String getLabel() { java.lang.Object ref = label_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The new label for the address.
       * 
* * string label = 4 [json_name = "label"]; * @return The bytes for label. */ public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The new label for the address.
       * 
* * string label = 4 [json_name = "label"]; * @param value The label to set. * @return This builder for chaining. */ public Builder setLabel( java.lang.String value) { if (value == null) { throw new NullPointerException(); } label_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The new label for the address.
       * 
* * string label = 4 [json_name = "label"]; * @return This builder for chaining. */ public Builder clearLabel() { label_ = getDefaultInstance().getLabel(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The new label for the address.
       * 
* * string label = 4 [json_name = "label"]; * @param value The bytes for label to set. * @return This builder for chaining. */ public Builder setLabelBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); label_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SetAddressLabelRequest) } // @@protoc_insertion_point(class_scope:pactus.SetAddressLabelRequest) private static final pactus.WalletOuterClass.SetAddressLabelRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SetAddressLabelRequest(); } public static pactus.WalletOuterClass.SetAddressLabelRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SetAddressLabelRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SetAddressLabelResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SetAddressLabelResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet where the address label was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet where the address label was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The address where the label was updated.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address where the label was updated.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * The new label for the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The label. */ java.lang.String getLabel(); /** *
     * The new label for the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ com.google.protobuf.ByteString getLabelBytes(); } /** *
   * Response message for updated address label.
   * 
* * Protobuf type {@code pactus.SetAddressLabelResponse} */ public static final class SetAddressLabelResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SetAddressLabelResponse) SetAddressLabelResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SetAddressLabelResponse"); } // Use SetAddressLabelResponse.newBuilder() to construct. private SetAddressLabelResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SetAddressLabelResponse() { walletName_ = ""; address_ = ""; label_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetAddressLabelResponse.class, pactus.WalletOuterClass.SetAddressLabelResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet where the address label was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet where the address label was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address where the label was updated.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address where the label was updated.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LABEL_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object label_ = ""; /** *
     * The new label for the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The label. */ @java.lang.Override public java.lang.String getLabel() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } } /** *
     * The new label for the address.
     * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ @java.lang.Override public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, label_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, address_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(label_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, label_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SetAddressLabelResponse)) { return super.equals(obj); } pactus.WalletOuterClass.SetAddressLabelResponse other = (pactus.WalletOuterClass.SetAddressLabelResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getLabel() .equals(other.getLabel())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + LABEL_FIELD_NUMBER; hash = (53 * hash) + getLabel().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetAddressLabelResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SetAddressLabelResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message for updated address label.
     * 
* * Protobuf type {@code pactus.SetAddressLabelResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SetAddressLabelResponse) pactus.WalletOuterClass.SetAddressLabelResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetAddressLabelResponse.class, pactus.WalletOuterClass.SetAddressLabelResponse.Builder.class); } // Construct using pactus.WalletOuterClass.SetAddressLabelResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; address_ = ""; label_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SetAddressLabelResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.SetAddressLabelResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelResponse build() { pactus.WalletOuterClass.SetAddressLabelResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelResponse buildPartial() { pactus.WalletOuterClass.SetAddressLabelResponse result = new pactus.WalletOuterClass.SetAddressLabelResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SetAddressLabelResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.label_ = label_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SetAddressLabelResponse) { return mergeFrom((pactus.WalletOuterClass.SetAddressLabelResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SetAddressLabelResponse other) { if (other == pactus.WalletOuterClass.SetAddressLabelResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getLabel().isEmpty()) { label_ = other.label_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { label_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet where the address label was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet where the address label was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet where the address label was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet where the address label was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet where the address label was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address where the label was updated.
       * 
* * string address = 2 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address where the label was updated.
       * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address where the label was updated.
       * 
* * string address = 2 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The address where the label was updated.
       * 
* * string address = 2 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The address where the label was updated.
       * 
* * string address = 2 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object label_ = ""; /** *
       * The new label for the address.
       * 
* * string label = 3 [json_name = "label"]; * @return The label. */ public java.lang.String getLabel() { java.lang.Object ref = label_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); label_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The new label for the address.
       * 
* * string label = 3 [json_name = "label"]; * @return The bytes for label. */ public com.google.protobuf.ByteString getLabelBytes() { java.lang.Object ref = label_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); label_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The new label for the address.
       * 
* * string label = 3 [json_name = "label"]; * @param value The label to set. * @return This builder for chaining. */ public Builder setLabel( java.lang.String value) { if (value == null) { throw new NullPointerException(); } label_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The new label for the address.
       * 
* * string label = 3 [json_name = "label"]; * @return This builder for chaining. */ public Builder clearLabel() { label_ = getDefaultInstance().getLabel(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The new label for the address.
       * 
* * string label = 3 [json_name = "label"]; * @param value The bytes for label to set. * @return This builder for chaining. */ public Builder setLabelBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); label_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SetAddressLabelResponse) } // @@protoc_insertion_point(class_scope:pactus.SetAddressLabelResponse) private static final pactus.WalletOuterClass.SetAddressLabelResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SetAddressLabelResponse(); } public static pactus.WalletOuterClass.SetAddressLabelResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SetAddressLabelResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SetAddressLabelResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListWalletsRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListWalletsRequest) com.google.protobuf.MessageOrBuilder { } /** *
   * Request message for listing wallets.
   * 
* * Protobuf type {@code pactus.ListWalletsRequest} */ public static final class ListWalletsRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListWalletsRequest) ListWalletsRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListWalletsRequest"); } // Use ListWalletsRequest.newBuilder() to construct. private ListWalletsRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListWalletsRequest() { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListWalletsRequest.class, pactus.WalletOuterClass.ListWalletsRequest.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.ListWalletsRequest)) { return super.equals(obj); } pactus.WalletOuterClass.ListWalletsRequest other = (pactus.WalletOuterClass.ListWalletsRequest) obj; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListWalletsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListWalletsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.ListWalletsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for listing wallets.
     * 
* * Protobuf type {@code pactus.ListWalletsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListWalletsRequest) pactus.WalletOuterClass.ListWalletsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListWalletsRequest.class, pactus.WalletOuterClass.ListWalletsRequest.Builder.class); } // Construct using pactus.WalletOuterClass.ListWalletsRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.ListWalletsRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.ListWalletsRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.ListWalletsRequest build() { pactus.WalletOuterClass.ListWalletsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.ListWalletsRequest buildPartial() { pactus.WalletOuterClass.ListWalletsRequest result = new pactus.WalletOuterClass.ListWalletsRequest(this); onBuilt(); return result; } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.ListWalletsRequest) { return mergeFrom((pactus.WalletOuterClass.ListWalletsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.ListWalletsRequest other) { if (other == pactus.WalletOuterClass.ListWalletsRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } // @@protoc_insertion_point(builder_scope:pactus.ListWalletsRequest) } // @@protoc_insertion_point(class_scope:pactus.ListWalletsRequest) private static final pactus.WalletOuterClass.ListWalletsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.ListWalletsRequest(); } public static pactus.WalletOuterClass.ListWalletsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListWalletsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.ListWalletsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListWalletsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListWalletsResponse) com.google.protobuf.MessageOrBuilder { /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return A list containing the wallets. */ java.util.List getWalletsList(); /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return The count of wallets. */ int getWalletsCount(); /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index of the element to return. * @return The wallets at the given index. */ java.lang.String getWallets(int index); /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index of the value to return. * @return The bytes of the wallets at the given index. */ com.google.protobuf.ByteString getWalletsBytes(int index); } /** *
   * Response message contains wallet names.
   * 
* * Protobuf type {@code pactus.ListWalletsResponse} */ public static final class ListWalletsResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListWalletsResponse) ListWalletsResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListWalletsResponse"); } // Use ListWalletsResponse.newBuilder() to construct. private ListWalletsResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListWalletsResponse() { wallets_ = com.google.protobuf.LazyStringArrayList.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListWalletsResponse.class, pactus.WalletOuterClass.ListWalletsResponse.Builder.class); } public static final int WALLETS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList wallets_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return A list containing the wallets. */ public com.google.protobuf.ProtocolStringList getWalletsList() { return wallets_; } /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return The count of wallets. */ public int getWalletsCount() { return wallets_.size(); } /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index of the element to return. * @return The wallets at the given index. */ public java.lang.String getWallets(int index) { return wallets_.get(index); } /** *
     * Array of wallet names.
     * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index of the value to return. * @return The bytes of the wallets at the given index. */ public com.google.protobuf.ByteString getWalletsBytes(int index) { return wallets_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < wallets_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 1, wallets_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < wallets_.size(); i++) { dataSize += computeStringSizeNoTag(wallets_.getRaw(i)); } size += dataSize; size += 1 * getWalletsList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.ListWalletsResponse)) { return super.equals(obj); } pactus.WalletOuterClass.ListWalletsResponse other = (pactus.WalletOuterClass.ListWalletsResponse) obj; if (!getWalletsList() .equals(other.getWalletsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getWalletsCount() > 0) { hash = (37 * hash) + WALLETS_FIELD_NUMBER; hash = (53 * hash) + getWalletsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListWalletsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListWalletsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.ListWalletsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains wallet names.
     * 
* * Protobuf type {@code pactus.ListWalletsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListWalletsResponse) pactus.WalletOuterClass.ListWalletsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListWalletsResponse.class, pactus.WalletOuterClass.ListWalletsResponse.Builder.class); } // Construct using pactus.WalletOuterClass.ListWalletsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; wallets_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_ListWalletsResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.ListWalletsResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.ListWalletsResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.ListWalletsResponse build() { pactus.WalletOuterClass.ListWalletsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.ListWalletsResponse buildPartial() { pactus.WalletOuterClass.ListWalletsResponse result = new pactus.WalletOuterClass.ListWalletsResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.ListWalletsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { wallets_.makeImmutable(); result.wallets_ = wallets_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.ListWalletsResponse) { return mergeFrom((pactus.WalletOuterClass.ListWalletsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.ListWalletsResponse other) { if (other == pactus.WalletOuterClass.ListWalletsResponse.getDefaultInstance()) return this; if (!other.wallets_.isEmpty()) { if (wallets_.isEmpty()) { wallets_ = other.wallets_; bitField0_ |= 0x00000001; } else { ensureWalletsIsMutable(); wallets_.addAll(other.wallets_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); ensureWalletsIsMutable(); wallets_.add(s); break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.LazyStringArrayList wallets_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureWalletsIsMutable() { if (!wallets_.isModifiable()) { wallets_ = new com.google.protobuf.LazyStringArrayList(wallets_); } bitField0_ |= 0x00000001; } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return A list containing the wallets. */ public com.google.protobuf.ProtocolStringList getWalletsList() { wallets_.makeImmutable(); return wallets_; } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return The count of wallets. */ public int getWalletsCount() { return wallets_.size(); } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index of the element to return. * @return The wallets at the given index. */ public java.lang.String getWallets(int index) { return wallets_.get(index); } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index of the value to return. * @return The bytes of the wallets at the given index. */ public com.google.protobuf.ByteString getWalletsBytes(int index) { return wallets_.getByteString(index); } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param index The index to set the value at. * @param value The wallets to set. * @return This builder for chaining. */ public Builder setWallets( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureWalletsIsMutable(); wallets_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param value The wallets to add. * @return This builder for chaining. */ public Builder addWallets( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureWalletsIsMutable(); wallets_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param values The wallets to add. * @return This builder for chaining. */ public Builder addAllWallets( java.lang.Iterable values) { ensureWalletsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, wallets_); bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @return This builder for chaining. */ public Builder clearWallets() { wallets_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001);; onChanged(); return this; } /** *
       * Array of wallet names.
       * 
* * repeated string wallets = 1 [json_name = "wallets"]; * @param value The bytes of the wallets to add. * @return This builder for chaining. */ public Builder addWalletsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureWalletsIsMutable(); wallets_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ListWalletsResponse) } // @@protoc_insertion_point(class_scope:pactus.ListWalletsResponse) private static final pactus.WalletOuterClass.ListWalletsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.ListWalletsResponse(); } public static pactus.WalletOuterClass.ListWalletsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListWalletsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.ListWalletsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetWalletInfoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetWalletInfoRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to query.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to query.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Request message for getting wallet information.
   * 
* * Protobuf type {@code pactus.GetWalletInfoRequest} */ public static final class GetWalletInfoRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetWalletInfoRequest) GetWalletInfoRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetWalletInfoRequest"); } // Use GetWalletInfoRequest.newBuilder() to construct. private GetWalletInfoRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetWalletInfoRequest() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetWalletInfoRequest.class, pactus.WalletOuterClass.GetWalletInfoRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to query.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to query.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetWalletInfoRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetWalletInfoRequest other = (pactus.WalletOuterClass.GetWalletInfoRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetWalletInfoRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetWalletInfoRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for getting wallet information.
     * 
* * Protobuf type {@code pactus.GetWalletInfoRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetWalletInfoRequest) pactus.WalletOuterClass.GetWalletInfoRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetWalletInfoRequest.class, pactus.WalletOuterClass.GetWalletInfoRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetWalletInfoRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetWalletInfoRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoRequest build() { pactus.WalletOuterClass.GetWalletInfoRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoRequest buildPartial() { pactus.WalletOuterClass.GetWalletInfoRequest result = new pactus.WalletOuterClass.GetWalletInfoRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetWalletInfoRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetWalletInfoRequest) { return mergeFrom((pactus.WalletOuterClass.GetWalletInfoRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetWalletInfoRequest other) { if (other == pactus.WalletOuterClass.GetWalletInfoRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to query.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to query.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to query.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to query.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to query.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetWalletInfoRequest) } // @@protoc_insertion_point(class_scope:pactus.GetWalletInfoRequest) private static final pactus.WalletOuterClass.GetWalletInfoRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetWalletInfoRequest(); } public static pactus.WalletOuterClass.GetWalletInfoRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetWalletInfoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetWalletInfoResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetWalletInfoResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The wallet format version.
     * 
* * int32 version = 2 [json_name = "version"]; * @return The version. */ int getVersion(); /** *
     * The network the wallet is connected to (e.g., mainnet, testnet).
     * 
* * string network = 3 [json_name = "network"]; * @return The network. */ java.lang.String getNetwork(); /** *
     * The network the wallet is connected to (e.g., mainnet, testnet).
     * 
* * string network = 3 [json_name = "network"]; * @return The bytes for network. */ com.google.protobuf.ByteString getNetworkBytes(); /** *
     * Indicates if the wallet is encrypted.
     * 
* * bool encrypted = 4 [json_name = "encrypted"]; * @return The encrypted. */ boolean getEncrypted(); /** *
     * A unique identifier of the wallet.
     * 
* * string uuid = 5 [json_name = "uuid"]; * @return The uuid. */ java.lang.String getUuid(); /** *
     * A unique identifier of the wallet.
     * 
* * string uuid = 5 [json_name = "uuid"]; * @return The bytes for uuid. */ com.google.protobuf.ByteString getUuidBytes(); /** *
     * Unix timestamp of wallet creation.
     * 
* * int64 created_at = 6 [json_name = "createdAt"]; * @return The createdAt. */ long getCreatedAt(); /** *
     * The default fee of the wallet.
     * 
* * int64 default_fee = 7 [json_name = "defaultFee"]; * @return The defaultFee. */ long getDefaultFee(); /** *
     * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
     * 
* * string driver = 8 [json_name = "driver"]; * @return The driver. */ java.lang.String getDriver(); /** *
     * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
     * 
* * string driver = 8 [json_name = "driver"]; * @return The bytes for driver. */ com.google.protobuf.ByteString getDriverBytes(); /** *
     * Path to the wallet file or storage location.
     * 
* * string path = 9 [json_name = "path"]; * @return The path. */ java.lang.String getPath(); /** *
     * Path to the wallet file or storage location.
     * 
* * string path = 9 [json_name = "path"]; * @return The bytes for path. */ com.google.protobuf.ByteString getPathBytes(); } /** *
   * Response message contains wallet details.
   * 
* * Protobuf type {@code pactus.GetWalletInfoResponse} */ public static final class GetWalletInfoResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetWalletInfoResponse) GetWalletInfoResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetWalletInfoResponse"); } // Use GetWalletInfoResponse.newBuilder() to construct. private GetWalletInfoResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetWalletInfoResponse() { walletName_ = ""; network_ = ""; uuid_ = ""; driver_ = ""; path_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetWalletInfoResponse.class, pactus.WalletOuterClass.GetWalletInfoResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERSION_FIELD_NUMBER = 2; private int version_ = 0; /** *
     * The wallet format version.
     * 
* * int32 version = 2 [json_name = "version"]; * @return The version. */ @java.lang.Override public int getVersion() { return version_; } public static final int NETWORK_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object network_ = ""; /** *
     * The network the wallet is connected to (e.g., mainnet, testnet).
     * 
* * string network = 3 [json_name = "network"]; * @return The network. */ @java.lang.Override public java.lang.String getNetwork() { java.lang.Object ref = network_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); network_ = s; return s; } } /** *
     * The network the wallet is connected to (e.g., mainnet, testnet).
     * 
* * string network = 3 [json_name = "network"]; * @return The bytes for network. */ @java.lang.Override public com.google.protobuf.ByteString getNetworkBytes() { java.lang.Object ref = network_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); network_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ENCRYPTED_FIELD_NUMBER = 4; private boolean encrypted_ = false; /** *
     * Indicates if the wallet is encrypted.
     * 
* * bool encrypted = 4 [json_name = "encrypted"]; * @return The encrypted. */ @java.lang.Override public boolean getEncrypted() { return encrypted_; } public static final int UUID_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object uuid_ = ""; /** *
     * A unique identifier of the wallet.
     * 
* * string uuid = 5 [json_name = "uuid"]; * @return The uuid. */ @java.lang.Override public java.lang.String getUuid() { java.lang.Object ref = uuid_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uuid_ = s; return s; } } /** *
     * A unique identifier of the wallet.
     * 
* * string uuid = 5 [json_name = "uuid"]; * @return The bytes for uuid. */ @java.lang.Override public com.google.protobuf.ByteString getUuidBytes() { java.lang.Object ref = uuid_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uuid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATED_AT_FIELD_NUMBER = 6; private long createdAt_ = 0L; /** *
     * Unix timestamp of wallet creation.
     * 
* * int64 created_at = 6 [json_name = "createdAt"]; * @return The createdAt. */ @java.lang.Override public long getCreatedAt() { return createdAt_; } public static final int DEFAULT_FEE_FIELD_NUMBER = 7; private long defaultFee_ = 0L; /** *
     * The default fee of the wallet.
     * 
* * int64 default_fee = 7 [json_name = "defaultFee"]; * @return The defaultFee. */ @java.lang.Override public long getDefaultFee() { return defaultFee_; } public static final int DRIVER_FIELD_NUMBER = 8; @SuppressWarnings("serial") private volatile java.lang.Object driver_ = ""; /** *
     * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
     * 
* * string driver = 8 [json_name = "driver"]; * @return The driver. */ @java.lang.Override public java.lang.String getDriver() { java.lang.Object ref = driver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); driver_ = s; return s; } } /** *
     * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
     * 
* * string driver = 8 [json_name = "driver"]; * @return The bytes for driver. */ @java.lang.Override public com.google.protobuf.ByteString getDriverBytes() { java.lang.Object ref = driver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); driver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PATH_FIELD_NUMBER = 9; @SuppressWarnings("serial") private volatile java.lang.Object path_ = ""; /** *
     * Path to the wallet file or storage location.
     * 
* * string path = 9 [json_name = "path"]; * @return The path. */ @java.lang.Override public java.lang.String getPath() { java.lang.Object ref = path_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); path_ = s; return s; } } /** *
     * Path to the wallet file or storage location.
     * 
* * string path = 9 [json_name = "path"]; * @return The bytes for path. */ @java.lang.Override public com.google.protobuf.ByteString getPathBytes() { java.lang.Object ref = path_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); path_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (version_ != 0) { output.writeInt32(2, version_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(network_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, network_); } if (encrypted_ != false) { output.writeBool(4, encrypted_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(uuid_)) { com.google.protobuf.GeneratedMessage.writeString(output, 5, uuid_); } if (createdAt_ != 0L) { output.writeInt64(6, createdAt_); } if (defaultFee_ != 0L) { output.writeInt64(7, defaultFee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(driver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 8, driver_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(path_)) { com.google.protobuf.GeneratedMessage.writeString(output, 9, path_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (version_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, version_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(network_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, network_); } if (encrypted_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, encrypted_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(uuid_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(5, uuid_); } if (createdAt_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, createdAt_); } if (defaultFee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, defaultFee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(driver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(8, driver_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(path_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(9, path_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetWalletInfoResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetWalletInfoResponse other = (pactus.WalletOuterClass.GetWalletInfoResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (getVersion() != other.getVersion()) return false; if (!getNetwork() .equals(other.getNetwork())) return false; if (getEncrypted() != other.getEncrypted()) return false; if (!getUuid() .equals(other.getUuid())) return false; if (getCreatedAt() != other.getCreatedAt()) return false; if (getDefaultFee() != other.getDefaultFee()) return false; if (!getDriver() .equals(other.getDriver())) return false; if (!getPath() .equals(other.getPath())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion(); hash = (37 * hash) + NETWORK_FIELD_NUMBER; hash = (53 * hash) + getNetwork().hashCode(); hash = (37 * hash) + ENCRYPTED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEncrypted()); hash = (37 * hash) + UUID_FIELD_NUMBER; hash = (53 * hash) + getUuid().hashCode(); hash = (37 * hash) + CREATED_AT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCreatedAt()); hash = (37 * hash) + DEFAULT_FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getDefaultFee()); hash = (37 * hash) + DRIVER_FIELD_NUMBER; hash = (53 * hash) + getDriver().hashCode(); hash = (37 * hash) + PATH_FIELD_NUMBER; hash = (53 * hash) + getPath().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetWalletInfoResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetWalletInfoResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains wallet details.
     * 
* * Protobuf type {@code pactus.GetWalletInfoResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetWalletInfoResponse) pactus.WalletOuterClass.GetWalletInfoResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetWalletInfoResponse.class, pactus.WalletOuterClass.GetWalletInfoResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetWalletInfoResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; version_ = 0; network_ = ""; encrypted_ = false; uuid_ = ""; createdAt_ = 0L; defaultFee_ = 0L; driver_ = ""; path_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetWalletInfoResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetWalletInfoResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoResponse build() { pactus.WalletOuterClass.GetWalletInfoResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoResponse buildPartial() { pactus.WalletOuterClass.GetWalletInfoResponse result = new pactus.WalletOuterClass.GetWalletInfoResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetWalletInfoResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.version_ = version_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.network_ = network_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.encrypted_ = encrypted_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.uuid_ = uuid_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.createdAt_ = createdAt_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.defaultFee_ = defaultFee_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.driver_ = driver_; } if (((from_bitField0_ & 0x00000100) != 0)) { result.path_ = path_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetWalletInfoResponse) { return mergeFrom((pactus.WalletOuterClass.GetWalletInfoResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetWalletInfoResponse other) { if (other == pactus.WalletOuterClass.GetWalletInfoResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.getVersion() != 0) { setVersion(other.getVersion()); } if (!other.getNetwork().isEmpty()) { network_ = other.network_; bitField0_ |= 0x00000004; onChanged(); } if (other.getEncrypted() != false) { setEncrypted(other.getEncrypted()); } if (!other.getUuid().isEmpty()) { uuid_ = other.uuid_; bitField0_ |= 0x00000010; onChanged(); } if (other.getCreatedAt() != 0L) { setCreatedAt(other.getCreatedAt()); } if (other.getDefaultFee() != 0L) { setDefaultFee(other.getDefaultFee()); } if (!other.getDriver().isEmpty()) { driver_ = other.driver_; bitField0_ |= 0x00000080; onChanged(); } if (!other.getPath().isEmpty()) { path_ = other.path_; bitField0_ |= 0x00000100; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { version_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { network_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { encrypted_ = input.readBool(); bitField0_ |= 0x00000008; break; } // case 32 case 42: { uuid_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 case 48: { createdAt_ = input.readInt64(); bitField0_ |= 0x00000020; break; } // case 48 case 56: { defaultFee_ = input.readInt64(); bitField0_ |= 0x00000040; break; } // case 56 case 66: { driver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000080; break; } // case 66 case 74: { path_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000100; break; } // case 74 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int version_ ; /** *
       * The wallet format version.
       * 
* * int32 version = 2 [json_name = "version"]; * @return The version. */ @java.lang.Override public int getVersion() { return version_; } /** *
       * The wallet format version.
       * 
* * int32 version = 2 [json_name = "version"]; * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(int value) { version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The wallet format version.
       * 
* * int32 version = 2 [json_name = "version"]; * @return This builder for chaining. */ public Builder clearVersion() { bitField0_ = (bitField0_ & ~0x00000002); version_ = 0; onChanged(); return this; } private java.lang.Object network_ = ""; /** *
       * The network the wallet is connected to (e.g., mainnet, testnet).
       * 
* * string network = 3 [json_name = "network"]; * @return The network. */ public java.lang.String getNetwork() { java.lang.Object ref = network_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); network_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The network the wallet is connected to (e.g., mainnet, testnet).
       * 
* * string network = 3 [json_name = "network"]; * @return The bytes for network. */ public com.google.protobuf.ByteString getNetworkBytes() { java.lang.Object ref = network_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); network_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The network the wallet is connected to (e.g., mainnet, testnet).
       * 
* * string network = 3 [json_name = "network"]; * @param value The network to set. * @return This builder for chaining. */ public Builder setNetwork( java.lang.String value) { if (value == null) { throw new NullPointerException(); } network_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The network the wallet is connected to (e.g., mainnet, testnet).
       * 
* * string network = 3 [json_name = "network"]; * @return This builder for chaining. */ public Builder clearNetwork() { network_ = getDefaultInstance().getNetwork(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The network the wallet is connected to (e.g., mainnet, testnet).
       * 
* * string network = 3 [json_name = "network"]; * @param value The bytes for network to set. * @return This builder for chaining. */ public Builder setNetworkBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); network_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private boolean encrypted_ ; /** *
       * Indicates if the wallet is encrypted.
       * 
* * bool encrypted = 4 [json_name = "encrypted"]; * @return The encrypted. */ @java.lang.Override public boolean getEncrypted() { return encrypted_; } /** *
       * Indicates if the wallet is encrypted.
       * 
* * bool encrypted = 4 [json_name = "encrypted"]; * @param value The encrypted to set. * @return This builder for chaining. */ public Builder setEncrypted(boolean value) { encrypted_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * Indicates if the wallet is encrypted.
       * 
* * bool encrypted = 4 [json_name = "encrypted"]; * @return This builder for chaining. */ public Builder clearEncrypted() { bitField0_ = (bitField0_ & ~0x00000008); encrypted_ = false; onChanged(); return this; } private java.lang.Object uuid_ = ""; /** *
       * A unique identifier of the wallet.
       * 
* * string uuid = 5 [json_name = "uuid"]; * @return The uuid. */ public java.lang.String getUuid() { java.lang.Object ref = uuid_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uuid_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A unique identifier of the wallet.
       * 
* * string uuid = 5 [json_name = "uuid"]; * @return The bytes for uuid. */ public com.google.protobuf.ByteString getUuidBytes() { java.lang.Object ref = uuid_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uuid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A unique identifier of the wallet.
       * 
* * string uuid = 5 [json_name = "uuid"]; * @param value The uuid to set. * @return This builder for chaining. */ public Builder setUuid( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uuid_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * A unique identifier of the wallet.
       * 
* * string uuid = 5 [json_name = "uuid"]; * @return This builder for chaining. */ public Builder clearUuid() { uuid_ = getDefaultInstance().getUuid(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** *
       * A unique identifier of the wallet.
       * 
* * string uuid = 5 [json_name = "uuid"]; * @param value The bytes for uuid to set. * @return This builder for chaining. */ public Builder setUuidBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uuid_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } private long createdAt_ ; /** *
       * Unix timestamp of wallet creation.
       * 
* * int64 created_at = 6 [json_name = "createdAt"]; * @return The createdAt. */ @java.lang.Override public long getCreatedAt() { return createdAt_; } /** *
       * Unix timestamp of wallet creation.
       * 
* * int64 created_at = 6 [json_name = "createdAt"]; * @param value The createdAt to set. * @return This builder for chaining. */ public Builder setCreatedAt(long value) { createdAt_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * Unix timestamp of wallet creation.
       * 
* * int64 created_at = 6 [json_name = "createdAt"]; * @return This builder for chaining. */ public Builder clearCreatedAt() { bitField0_ = (bitField0_ & ~0x00000020); createdAt_ = 0L; onChanged(); return this; } private long defaultFee_ ; /** *
       * The default fee of the wallet.
       * 
* * int64 default_fee = 7 [json_name = "defaultFee"]; * @return The defaultFee. */ @java.lang.Override public long getDefaultFee() { return defaultFee_; } /** *
       * The default fee of the wallet.
       * 
* * int64 default_fee = 7 [json_name = "defaultFee"]; * @param value The defaultFee to set. * @return This builder for chaining. */ public Builder setDefaultFee(long value) { defaultFee_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * The default fee of the wallet.
       * 
* * int64 default_fee = 7 [json_name = "defaultFee"]; * @return This builder for chaining. */ public Builder clearDefaultFee() { bitField0_ = (bitField0_ & ~0x00000040); defaultFee_ = 0L; onChanged(); return this; } private java.lang.Object driver_ = ""; /** *
       * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
       * 
* * string driver = 8 [json_name = "driver"]; * @return The driver. */ public java.lang.String getDriver() { java.lang.Object ref = driver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); driver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
       * 
* * string driver = 8 [json_name = "driver"]; * @return The bytes for driver. */ public com.google.protobuf.ByteString getDriverBytes() { java.lang.Object ref = driver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); driver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
       * 
* * string driver = 8 [json_name = "driver"]; * @param value The driver to set. * @return This builder for chaining. */ public Builder setDriver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } driver_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
       * 
* * string driver = 8 [json_name = "driver"]; * @return This builder for chaining. */ public Builder clearDriver() { driver_ = getDefaultInstance().getDriver(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); return this; } /** *
       * The storage driver used by the wallet (e.g., SQLite, Legacy JSON ).
       * 
* * string driver = 8 [json_name = "driver"]; * @param value The bytes for driver to set. * @return This builder for chaining. */ public Builder setDriverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); driver_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } private java.lang.Object path_ = ""; /** *
       * Path to the wallet file or storage location.
       * 
* * string path = 9 [json_name = "path"]; * @return The path. */ public java.lang.String getPath() { java.lang.Object ref = path_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); path_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Path to the wallet file or storage location.
       * 
* * string path = 9 [json_name = "path"]; * @return The bytes for path. */ public com.google.protobuf.ByteString getPathBytes() { java.lang.Object ref = path_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); path_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Path to the wallet file or storage location.
       * 
* * string path = 9 [json_name = "path"]; * @param value The path to set. * @return This builder for chaining. */ public Builder setPath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } path_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * Path to the wallet file or storage location.
       * 
* * string path = 9 [json_name = "path"]; * @return This builder for chaining. */ public Builder clearPath() { path_ = getDefaultInstance().getPath(); bitField0_ = (bitField0_ & ~0x00000100); onChanged(); return this; } /** *
       * Path to the wallet file or storage location.
       * 
* * string path = 9 [json_name = "path"]; * @param value The bytes for path to set. * @return This builder for chaining. */ public Builder setPathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); path_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetWalletInfoResponse) } // @@protoc_insertion_point(class_scope:pactus.GetWalletInfoResponse) private static final pactus.WalletOuterClass.GetWalletInfoResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetWalletInfoResponse(); } public static pactus.WalletOuterClass.GetWalletInfoResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetWalletInfoResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetWalletInfoResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListAddressesRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListAddressesRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return A list containing the addressTypes. */ java.util.List getAddressTypesList(); /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return The count of addressTypes. */ int getAddressTypesCount(); /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index of the element to return. * @return The addressTypes at the given index. */ pactus.WalletOuterClass.AddressType getAddressTypes(int index); /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return A list containing the enum numeric values on the wire for addressTypes. */ java.util.List getAddressTypesValueList(); /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index of the value to return. * @return The enum numeric value on the wire of addressTypes at the given index. */ int getAddressTypesValue(int index); } /** *
   * Request message for listing wallet addresses.
   * 
* * Protobuf type {@code pactus.ListAddressesRequest} */ public static final class ListAddressesRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListAddressesRequest) ListAddressesRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListAddressesRequest"); } // Use ListAddressesRequest.newBuilder() to construct. private ListAddressesRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListAddressesRequest() { walletName_ = ""; addressTypes_ = emptyIntList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListAddressesRequest.class, pactus.WalletOuterClass.ListAddressesRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_TYPES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.Internal.IntList addressTypes_ = emptyIntList(); private static final com.google.protobuf.Internal.IntListAdapter.IntConverter< pactus.WalletOuterClass.AddressType> addressTypes_converter_ = new com.google.protobuf.Internal.IntListAdapter.IntConverter< pactus.WalletOuterClass.AddressType>() { public pactus.WalletOuterClass.AddressType convert(int from) { pactus.WalletOuterClass.AddressType result = pactus.WalletOuterClass.AddressType.forNumber(from); return result == null ? pactus.WalletOuterClass.AddressType.UNRECOGNIZED : result; } }; /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return A list containing the addressTypes. */ @java.lang.Override public java.util.List getAddressTypesList() { return new com.google.protobuf.Internal.IntListAdapter< pactus.WalletOuterClass.AddressType>(addressTypes_, addressTypes_converter_); } /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return The count of addressTypes. */ @java.lang.Override public int getAddressTypesCount() { return addressTypes_.size(); } /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index of the element to return. * @return The addressTypes at the given index. */ @java.lang.Override public pactus.WalletOuterClass.AddressType getAddressTypes(int index) { return addressTypes_converter_.convert(addressTypes_.getInt(index)); } /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return A list containing the enum numeric values on the wire for addressTypes. */ @java.lang.Override public java.util.List getAddressTypesValueList() { return addressTypes_; } /** *
     * Filter addresses by their types. If empty, all address types are included.
     * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index of the value to return. * @return The enum numeric value on the wire of addressTypes at the given index. */ @java.lang.Override public int getAddressTypesValue(int index) { return addressTypes_.getInt(index); } private int addressTypesMemoizedSerializedSize; private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (getAddressTypesList().size() > 0) { output.writeUInt32NoTag(18); output.writeUInt32NoTag(addressTypesMemoizedSerializedSize); } for (int i = 0; i < addressTypes_.size(); i++) { output.writeEnumNoTag(addressTypes_.getInt(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } { int dataSize = 0; for (int i = 0; i < addressTypes_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeEnumSizeNoTag(addressTypes_.getInt(i)); } size += dataSize; if (!getAddressTypesList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeUInt32SizeNoTag(dataSize); }addressTypesMemoizedSerializedSize = dataSize; } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.ListAddressesRequest)) { return super.equals(obj); } pactus.WalletOuterClass.ListAddressesRequest other = (pactus.WalletOuterClass.ListAddressesRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!addressTypes_.equals(other.addressTypes_)) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); if (getAddressTypesCount() > 0) { hash = (37 * hash) + ADDRESS_TYPES_FIELD_NUMBER; hash = (53 * hash) + addressTypes_.hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListAddressesRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListAddressesRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.ListAddressesRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for listing wallet addresses.
     * 
* * Protobuf type {@code pactus.ListAddressesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListAddressesRequest) pactus.WalletOuterClass.ListAddressesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListAddressesRequest.class, pactus.WalletOuterClass.ListAddressesRequest.Builder.class); } // Construct using pactus.WalletOuterClass.ListAddressesRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; addressTypes_ = emptyIntList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.ListAddressesRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.ListAddressesRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.ListAddressesRequest build() { pactus.WalletOuterClass.ListAddressesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.ListAddressesRequest buildPartial() { pactus.WalletOuterClass.ListAddressesRequest result = new pactus.WalletOuterClass.ListAddressesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.ListAddressesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { addressTypes_.makeImmutable(); result.addressTypes_ = addressTypes_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.ListAddressesRequest) { return mergeFrom((pactus.WalletOuterClass.ListAddressesRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.ListAddressesRequest other) { if (other == pactus.WalletOuterClass.ListAddressesRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.addressTypes_.isEmpty()) { if (addressTypes_.isEmpty()) { addressTypes_ = other.addressTypes_; addressTypes_.makeImmutable(); bitField0_ |= 0x00000002; } else { ensureAddressTypesIsMutable(); addressTypes_.addAll(other.addressTypes_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { int tmpRaw = input.readEnum(); ensureAddressTypesIsMutable(); addressTypes_.addInt(tmpRaw); break; } // case 16 case 18: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); ensureAddressTypesIsMutable(); while (input.getBytesUntilLimit() > 0) { addressTypes_.addInt(input.readEnum()); } input.popLimit(limit); break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.Internal.IntList addressTypes_ = emptyIntList(); private void ensureAddressTypesIsMutable() { if (!addressTypes_.isModifiable()) { addressTypes_ = makeMutableCopy(addressTypes_); } bitField0_ |= 0x00000002; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return A list containing the addressTypes. */ public java.util.List getAddressTypesList() { return new com.google.protobuf.Internal.IntListAdapter< pactus.WalletOuterClass.AddressType>(addressTypes_, addressTypes_converter_); } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return The count of addressTypes. */ public int getAddressTypesCount() { return addressTypes_.size(); } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index of the element to return. * @return The addressTypes at the given index. */ public pactus.WalletOuterClass.AddressType getAddressTypes(int index) { return addressTypes_converter_.convert(addressTypes_.getInt(index)); } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index to set the value at. * @param value The addressTypes to set. * @return This builder for chaining. */ public Builder setAddressTypes( int index, pactus.WalletOuterClass.AddressType value) { if (value == null) { throw new NullPointerException(); } ensureAddressTypesIsMutable(); addressTypes_.setInt(index, value.getNumber()); onChanged(); return this; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param value The addressTypes to add. * @return This builder for chaining. */ public Builder addAddressTypes(pactus.WalletOuterClass.AddressType value) { if (value == null) { throw new NullPointerException(); } ensureAddressTypesIsMutable(); addressTypes_.addInt(value.getNumber()); onChanged(); return this; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param values The addressTypes to add. * @return This builder for chaining. */ public Builder addAllAddressTypes( java.lang.Iterable values) { ensureAddressTypesIsMutable(); for (pactus.WalletOuterClass.AddressType value : values) { addressTypes_.addInt(value.getNumber()); } onChanged(); return this; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return This builder for chaining. */ public Builder clearAddressTypes() { addressTypes_ = emptyIntList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @return A list containing the enum numeric values on the wire for addressTypes. */ public java.util.List getAddressTypesValueList() { addressTypes_.makeImmutable(); return addressTypes_; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index of the value to return. * @return The enum numeric value on the wire of addressTypes at the given index. */ public int getAddressTypesValue(int index) { return addressTypes_.getInt(index); } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param index The index to set the value at. * @param value The enum numeric value on the wire for addressTypes to set. * @return This builder for chaining. */ public Builder setAddressTypesValue( int index, int value) { ensureAddressTypesIsMutable(); addressTypes_.setInt(index, value); onChanged(); return this; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param value The enum numeric value on the wire for addressTypes to add. * @return This builder for chaining. */ public Builder addAddressTypesValue(int value) { ensureAddressTypesIsMutable(); addressTypes_.addInt(value); onChanged(); return this; } /** *
       * Filter addresses by their types. If empty, all address types are included.
       * 
* * repeated .pactus.AddressType address_types = 2 [json_name = "addressTypes"]; * @param values The enum numeric values on the wire for addressTypes to add. * @return This builder for chaining. */ public Builder addAllAddressTypesValue( java.lang.Iterable values) { ensureAddressTypesIsMutable(); for (int value : values) { addressTypes_.addInt(value); } onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ListAddressesRequest) } // @@protoc_insertion_point(class_scope:pactus.ListAddressesRequest) private static final pactus.WalletOuterClass.ListAddressesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.ListAddressesRequest(); } public static pactus.WalletOuterClass.ListAddressesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListAddressesRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.ListAddressesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListAddressesResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListAddressesResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ java.util.List getAddrsList(); /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ pactus.WalletOuterClass.AddressInfo getAddrs(int index); /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ int getAddrsCount(); /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ java.util.List getAddrsOrBuilderList(); /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ pactus.WalletOuterClass.AddressInfoOrBuilder getAddrsOrBuilder( int index); } /** *
   * Response message contains wallet addresses.
   * 
* * Protobuf type {@code pactus.ListAddressesResponse} */ public static final class ListAddressesResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListAddressesResponse) ListAddressesResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListAddressesResponse"); } // Use ListAddressesResponse.newBuilder() to construct. private ListAddressesResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListAddressesResponse() { walletName_ = ""; addrs_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListAddressesResponse.class, pactus.WalletOuterClass.ListAddressesResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the queried wallet.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List addrs_; /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ @java.lang.Override public java.util.List getAddrsList() { return addrs_; } /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ @java.lang.Override public java.util.List getAddrsOrBuilderList() { return addrs_; } /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ @java.lang.Override public int getAddrsCount() { return addrs_.size(); } /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ @java.lang.Override public pactus.WalletOuterClass.AddressInfo getAddrs(int index) { return addrs_.get(index); } /** *
     * List of all addresses in the wallet with their details.
     * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ @java.lang.Override public pactus.WalletOuterClass.AddressInfoOrBuilder getAddrsOrBuilder( int index) { return addrs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } for (int i = 0; i < addrs_.size(); i++) { output.writeMessage(2, addrs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } for (int i = 0; i < addrs_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, addrs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.ListAddressesResponse)) { return super.equals(obj); } pactus.WalletOuterClass.ListAddressesResponse other = (pactus.WalletOuterClass.ListAddressesResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getAddrsList() .equals(other.getAddrsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); if (getAddrsCount() > 0) { hash = (37 * hash) + ADDRS_FIELD_NUMBER; hash = (53 * hash) + getAddrsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListAddressesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListAddressesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.ListAddressesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains wallet addresses.
     * 
* * Protobuf type {@code pactus.ListAddressesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListAddressesResponse) pactus.WalletOuterClass.ListAddressesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListAddressesResponse.class, pactus.WalletOuterClass.ListAddressesResponse.Builder.class); } // Construct using pactus.WalletOuterClass.ListAddressesResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; if (addrsBuilder_ == null) { addrs_ = java.util.Collections.emptyList(); } else { addrs_ = null; addrsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_ListAddressesResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.ListAddressesResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.ListAddressesResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.ListAddressesResponse build() { pactus.WalletOuterClass.ListAddressesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.ListAddressesResponse buildPartial() { pactus.WalletOuterClass.ListAddressesResponse result = new pactus.WalletOuterClass.ListAddressesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.WalletOuterClass.ListAddressesResponse result) { if (addrsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { addrs_ = java.util.Collections.unmodifiableList(addrs_); bitField0_ = (bitField0_ & ~0x00000002); } result.addrs_ = addrs_; } else { result.addrs_ = addrsBuilder_.build(); } } private void buildPartial0(pactus.WalletOuterClass.ListAddressesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.ListAddressesResponse) { return mergeFrom((pactus.WalletOuterClass.ListAddressesResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.ListAddressesResponse other) { if (other == pactus.WalletOuterClass.ListAddressesResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (addrsBuilder_ == null) { if (!other.addrs_.isEmpty()) { if (addrs_.isEmpty()) { addrs_ = other.addrs_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureAddrsIsMutable(); addrs_.addAll(other.addrs_); } onChanged(); } } else { if (!other.addrs_.isEmpty()) { if (addrsBuilder_.isEmpty()) { addrsBuilder_.dispose(); addrsBuilder_ = null; addrs_ = other.addrs_; bitField0_ = (bitField0_ & ~0x00000002); addrsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetAddrsFieldBuilder() : null; } else { addrsBuilder_.addAllMessages(other.addrs_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { pactus.WalletOuterClass.AddressInfo m = input.readMessage( pactus.WalletOuterClass.AddressInfo.parser(), extensionRegistry); if (addrsBuilder_ == null) { ensureAddrsIsMutable(); addrs_.add(m); } else { addrsBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the queried wallet.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List addrs_ = java.util.Collections.emptyList(); private void ensureAddrsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { addrs_ = new java.util.ArrayList(addrs_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder> addrsBuilder_; /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public java.util.List getAddrsList() { if (addrsBuilder_ == null) { return java.util.Collections.unmodifiableList(addrs_); } else { return addrsBuilder_.getMessageList(); } } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public int getAddrsCount() { if (addrsBuilder_ == null) { return addrs_.size(); } else { return addrsBuilder_.getCount(); } } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public pactus.WalletOuterClass.AddressInfo getAddrs(int index) { if (addrsBuilder_ == null) { return addrs_.get(index); } else { return addrsBuilder_.getMessage(index); } } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder setAddrs( int index, pactus.WalletOuterClass.AddressInfo value) { if (addrsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAddrsIsMutable(); addrs_.set(index, value); onChanged(); } else { addrsBuilder_.setMessage(index, value); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder setAddrs( int index, pactus.WalletOuterClass.AddressInfo.Builder builderForValue) { if (addrsBuilder_ == null) { ensureAddrsIsMutable(); addrs_.set(index, builderForValue.build()); onChanged(); } else { addrsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder addAddrs(pactus.WalletOuterClass.AddressInfo value) { if (addrsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAddrsIsMutable(); addrs_.add(value); onChanged(); } else { addrsBuilder_.addMessage(value); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder addAddrs( int index, pactus.WalletOuterClass.AddressInfo value) { if (addrsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAddrsIsMutable(); addrs_.add(index, value); onChanged(); } else { addrsBuilder_.addMessage(index, value); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder addAddrs( pactus.WalletOuterClass.AddressInfo.Builder builderForValue) { if (addrsBuilder_ == null) { ensureAddrsIsMutable(); addrs_.add(builderForValue.build()); onChanged(); } else { addrsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder addAddrs( int index, pactus.WalletOuterClass.AddressInfo.Builder builderForValue) { if (addrsBuilder_ == null) { ensureAddrsIsMutable(); addrs_.add(index, builderForValue.build()); onChanged(); } else { addrsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder addAllAddrs( java.lang.Iterable values) { if (addrsBuilder_ == null) { ensureAddrsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, addrs_); onChanged(); } else { addrsBuilder_.addAllMessages(values); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder clearAddrs() { if (addrsBuilder_ == null) { addrs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { addrsBuilder_.clear(); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public Builder removeAddrs(int index) { if (addrsBuilder_ == null) { ensureAddrsIsMutable(); addrs_.remove(index); onChanged(); } else { addrsBuilder_.remove(index); } return this; } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public pactus.WalletOuterClass.AddressInfo.Builder getAddrsBuilder( int index) { return internalGetAddrsFieldBuilder().getBuilder(index); } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public pactus.WalletOuterClass.AddressInfoOrBuilder getAddrsOrBuilder( int index) { if (addrsBuilder_ == null) { return addrs_.get(index); } else { return addrsBuilder_.getMessageOrBuilder(index); } } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public java.util.List getAddrsOrBuilderList() { if (addrsBuilder_ != null) { return addrsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(addrs_); } } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public pactus.WalletOuterClass.AddressInfo.Builder addAddrsBuilder() { return internalGetAddrsFieldBuilder().addBuilder( pactus.WalletOuterClass.AddressInfo.getDefaultInstance()); } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public pactus.WalletOuterClass.AddressInfo.Builder addAddrsBuilder( int index) { return internalGetAddrsFieldBuilder().addBuilder( index, pactus.WalletOuterClass.AddressInfo.getDefaultInstance()); } /** *
       * List of all addresses in the wallet with their details.
       * 
* * repeated .pactus.AddressInfo addrs = 2 [json_name = "addrs"]; */ public java.util.List getAddrsBuilderList() { return internalGetAddrsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder> internalGetAddrsFieldBuilder() { if (addrsBuilder_ == null) { addrsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.WalletOuterClass.AddressInfo, pactus.WalletOuterClass.AddressInfo.Builder, pactus.WalletOuterClass.AddressInfoOrBuilder>( addrs_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); addrs_ = null; } return addrsBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.ListAddressesResponse) } // @@protoc_insertion_point(class_scope:pactus.ListAddressesResponse) private static final pactus.WalletOuterClass.ListAddressesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.ListAddressesResponse(); } public static pactus.WalletOuterClass.ListAddressesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListAddressesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.ListAddressesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface UpdatePasswordRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.UpdatePasswordRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet whose password will be updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet whose password will be updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The current wallet password.
     * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return The oldPassword. */ java.lang.String getOldPassword(); /** *
     * The current wallet password.
     * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return The bytes for oldPassword. */ com.google.protobuf.ByteString getOldPasswordBytes(); /** *
     * The new wallet password.
     * 
* * string new_password = 3 [json_name = "newPassword"]; * @return The newPassword. */ java.lang.String getNewPassword(); /** *
     * The new wallet password.
     * 
* * string new_password = 3 [json_name = "newPassword"]; * @return The bytes for newPassword. */ com.google.protobuf.ByteString getNewPasswordBytes(); } /** *
   * Request message for updating wallet password.
   * 
* * Protobuf type {@code pactus.UpdatePasswordRequest} */ public static final class UpdatePasswordRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.UpdatePasswordRequest) UpdatePasswordRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "UpdatePasswordRequest"); } // Use UpdatePasswordRequest.newBuilder() to construct. private UpdatePasswordRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private UpdatePasswordRequest() { walletName_ = ""; oldPassword_ = ""; newPassword_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UpdatePasswordRequest.class, pactus.WalletOuterClass.UpdatePasswordRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet whose password will be updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet whose password will be updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OLD_PASSWORD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object oldPassword_ = ""; /** *
     * The current wallet password.
     * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return The oldPassword. */ @java.lang.Override public java.lang.String getOldPassword() { java.lang.Object ref = oldPassword_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); oldPassword_ = s; return s; } } /** *
     * The current wallet password.
     * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return The bytes for oldPassword. */ @java.lang.Override public com.google.protobuf.ByteString getOldPasswordBytes() { java.lang.Object ref = oldPassword_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); oldPassword_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NEW_PASSWORD_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object newPassword_ = ""; /** *
     * The new wallet password.
     * 
* * string new_password = 3 [json_name = "newPassword"]; * @return The newPassword. */ @java.lang.Override public java.lang.String getNewPassword() { java.lang.Object ref = newPassword_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newPassword_ = s; return s; } } /** *
     * The new wallet password.
     * 
* * string new_password = 3 [json_name = "newPassword"]; * @return The bytes for newPassword. */ @java.lang.Override public com.google.protobuf.ByteString getNewPasswordBytes() { java.lang.Object ref = newPassword_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newPassword_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(oldPassword_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, oldPassword_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(newPassword_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, newPassword_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(oldPassword_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, oldPassword_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(newPassword_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, newPassword_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.UpdatePasswordRequest)) { return super.equals(obj); } pactus.WalletOuterClass.UpdatePasswordRequest other = (pactus.WalletOuterClass.UpdatePasswordRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getOldPassword() .equals(other.getOldPassword())) return false; if (!getNewPassword() .equals(other.getNewPassword())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + OLD_PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getOldPassword().hashCode(); hash = (37 * hash) + NEW_PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getNewPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UpdatePasswordRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.UpdatePasswordRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for updating wallet password.
     * 
* * Protobuf type {@code pactus.UpdatePasswordRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.UpdatePasswordRequest) pactus.WalletOuterClass.UpdatePasswordRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UpdatePasswordRequest.class, pactus.WalletOuterClass.UpdatePasswordRequest.Builder.class); } // Construct using pactus.WalletOuterClass.UpdatePasswordRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; oldPassword_ = ""; newPassword_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.UpdatePasswordRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordRequest build() { pactus.WalletOuterClass.UpdatePasswordRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordRequest buildPartial() { pactus.WalletOuterClass.UpdatePasswordRequest result = new pactus.WalletOuterClass.UpdatePasswordRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.UpdatePasswordRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.oldPassword_ = oldPassword_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.newPassword_ = newPassword_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.UpdatePasswordRequest) { return mergeFrom((pactus.WalletOuterClass.UpdatePasswordRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.UpdatePasswordRequest other) { if (other == pactus.WalletOuterClass.UpdatePasswordRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getOldPassword().isEmpty()) { oldPassword_ = other.oldPassword_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getNewPassword().isEmpty()) { newPassword_ = other.newPassword_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { oldPassword_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { newPassword_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet whose password will be updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet whose password will be updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet whose password will be updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet whose password will be updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet whose password will be updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object oldPassword_ = ""; /** *
       * The current wallet password.
       * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return The oldPassword. */ public java.lang.String getOldPassword() { java.lang.Object ref = oldPassword_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); oldPassword_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The current wallet password.
       * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return The bytes for oldPassword. */ public com.google.protobuf.ByteString getOldPasswordBytes() { java.lang.Object ref = oldPassword_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); oldPassword_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The current wallet password.
       * 
* * string old_password = 2 [json_name = "oldPassword"]; * @param value The oldPassword to set. * @return This builder for chaining. */ public Builder setOldPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } oldPassword_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The current wallet password.
       * 
* * string old_password = 2 [json_name = "oldPassword"]; * @return This builder for chaining. */ public Builder clearOldPassword() { oldPassword_ = getDefaultInstance().getOldPassword(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The current wallet password.
       * 
* * string old_password = 2 [json_name = "oldPassword"]; * @param value The bytes for oldPassword to set. * @return This builder for chaining. */ public Builder setOldPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); oldPassword_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object newPassword_ = ""; /** *
       * The new wallet password.
       * 
* * string new_password = 3 [json_name = "newPassword"]; * @return The newPassword. */ public java.lang.String getNewPassword() { java.lang.Object ref = newPassword_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newPassword_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The new wallet password.
       * 
* * string new_password = 3 [json_name = "newPassword"]; * @return The bytes for newPassword. */ public com.google.protobuf.ByteString getNewPasswordBytes() { java.lang.Object ref = newPassword_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newPassword_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The new wallet password.
       * 
* * string new_password = 3 [json_name = "newPassword"]; * @param value The newPassword to set. * @return This builder for chaining. */ public Builder setNewPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } newPassword_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The new wallet password.
       * 
* * string new_password = 3 [json_name = "newPassword"]; * @return This builder for chaining. */ public Builder clearNewPassword() { newPassword_ = getDefaultInstance().getNewPassword(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The new wallet password.
       * 
* * string new_password = 3 [json_name = "newPassword"]; * @param value The bytes for newPassword to set. * @return This builder for chaining. */ public Builder setNewPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); newPassword_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.UpdatePasswordRequest) } // @@protoc_insertion_point(class_scope:pactus.UpdatePasswordRequest) private static final pactus.WalletOuterClass.UpdatePasswordRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.UpdatePasswordRequest(); } public static pactus.WalletOuterClass.UpdatePasswordRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public UpdatePasswordRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface UpdatePasswordResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.UpdatePasswordResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet whose password was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet whose password was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Response message confirming wallet password update.
   * 
* * Protobuf type {@code pactus.UpdatePasswordResponse} */ public static final class UpdatePasswordResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.UpdatePasswordResponse) UpdatePasswordResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "UpdatePasswordResponse"); } // Use UpdatePasswordResponse.newBuilder() to construct. private UpdatePasswordResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private UpdatePasswordResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UpdatePasswordResponse.class, pactus.WalletOuterClass.UpdatePasswordResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet whose password was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet whose password was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.UpdatePasswordResponse)) { return super.equals(obj); } pactus.WalletOuterClass.UpdatePasswordResponse other = (pactus.WalletOuterClass.UpdatePasswordResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.UpdatePasswordResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.UpdatePasswordResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message confirming wallet password update.
     * 
* * Protobuf type {@code pactus.UpdatePasswordResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.UpdatePasswordResponse) pactus.WalletOuterClass.UpdatePasswordResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.UpdatePasswordResponse.class, pactus.WalletOuterClass.UpdatePasswordResponse.Builder.class); } // Construct using pactus.WalletOuterClass.UpdatePasswordResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_UpdatePasswordResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.UpdatePasswordResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordResponse build() { pactus.WalletOuterClass.UpdatePasswordResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordResponse buildPartial() { pactus.WalletOuterClass.UpdatePasswordResponse result = new pactus.WalletOuterClass.UpdatePasswordResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.UpdatePasswordResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.UpdatePasswordResponse) { return mergeFrom((pactus.WalletOuterClass.UpdatePasswordResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.UpdatePasswordResponse other) { if (other == pactus.WalletOuterClass.UpdatePasswordResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet whose password was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet whose password was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet whose password was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet whose password was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet whose password was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.UpdatePasswordResponse) } // @@protoc_insertion_point(class_scope:pactus.UpdatePasswordResponse) private static final pactus.WalletOuterClass.UpdatePasswordResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.UpdatePasswordResponse(); } public static pactus.WalletOuterClass.UpdatePasswordResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public UpdatePasswordResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.UpdatePasswordResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface WalletTransactionInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.WalletTransactionInfo) com.google.protobuf.MessageOrBuilder { /** *
     * A sequence number for the transaction in the wallet.
     * 
* * int64 no = 1 [json_name = "no"]; * @return The no. */ long getNo(); /** *
     * The unique ID of the transaction.
     * 
* * string tx_id = 2 [json_name = "txId"]; * @return The txId. */ java.lang.String getTxId(); /** *
     * The unique ID of the transaction.
     * 
* * string tx_id = 2 [json_name = "txId"]; * @return The bytes for txId. */ com.google.protobuf.ByteString getTxIdBytes(); /** *
     * The sender's address.
     * 
* * string sender = 3 [json_name = "sender"]; * @return The sender. */ java.lang.String getSender(); /** *
     * The sender's address.
     * 
* * string sender = 3 [json_name = "sender"]; * @return The bytes for sender. */ com.google.protobuf.ByteString getSenderBytes(); /** *
     * The receiver's address.
     * 
* * string receiver = 4 [json_name = "receiver"]; * @return The receiver. */ java.lang.String getReceiver(); /** *
     * The receiver's address.
     * 
* * string receiver = 4 [json_name = "receiver"]; * @return The bytes for receiver. */ com.google.protobuf.ByteString getReceiverBytes(); /** *
     * The direction of the transaction relative to the wallet.
     * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ int getDirectionValue(); /** *
     * The direction of the transaction relative to the wallet.
     * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return The direction. */ pactus.WalletOuterClass.TxDirection getDirection(); /** *
     * The amount involved in the transaction in NanoPAC.
     * 
* * int64 amount = 6 [json_name = "amount"]; * @return The amount. */ long getAmount(); /** *
     * The transaction fee in NanoPAC.
     * 
* * int64 fee = 7 [json_name = "fee"]; * @return The fee. */ long getFee(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The memo. */ java.lang.String getMemo(); /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); /** *
     * The current status of the transaction.
     * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return The enum numeric value on the wire for status. */ int getStatusValue(); /** *
     * The current status of the transaction.
     * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return The status. */ pactus.WalletOuterClass.TransactionStatus getStatus(); /** *
     * The block height containing the transaction.
     * 
* * uint32 block_height = 10 [json_name = "blockHeight"]; * @return The blockHeight. */ int getBlockHeight(); /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ int getPayloadTypeValue(); /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return The payloadType. */ pactus.TransactionOuterClass.PayloadType getPayloadType(); /** *
     * The raw transaction data.
     * 
* * bytes data = 12 [json_name = "data"]; * @return The data. */ com.google.protobuf.ByteString getData(); /** *
     * A comment associated with the transaction in the wallet.
     * 
* * string comment = 13 [json_name = "comment"]; * @return The comment. */ java.lang.String getComment(); /** *
     * A comment associated with the transaction in the wallet.
     * 
* * string comment = 13 [json_name = "comment"]; * @return The bytes for comment. */ com.google.protobuf.ByteString getCommentBytes(); /** *
     * Unix timestamp of when the transaction was created.
     * 
* * int64 created_at = 14 [json_name = "createdAt"]; * @return The createdAt. */ long getCreatedAt(); /** *
     * Unix timestamp of when the transaction was last updated.
     * 
* * int64 updated_at = 15 [json_name = "updatedAt"]; * @return The updatedAt. */ long getUpdatedAt(); } /** *
   * WalletTransactionInfo contains information about a transaction in a wallet.
   * 
* * Protobuf type {@code pactus.WalletTransactionInfo} */ public static final class WalletTransactionInfo extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.WalletTransactionInfo) WalletTransactionInfoOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "WalletTransactionInfo"); } // Use WalletTransactionInfo.newBuilder() to construct. private WalletTransactionInfo(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private WalletTransactionInfo() { txId_ = ""; sender_ = ""; receiver_ = ""; direction_ = 0; memo_ = ""; status_ = 0; payloadType_ = 0; data_ = com.google.protobuf.ByteString.EMPTY; comment_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_WalletTransactionInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_WalletTransactionInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.WalletTransactionInfo.class, pactus.WalletOuterClass.WalletTransactionInfo.Builder.class); } public static final int NO_FIELD_NUMBER = 1; private long no_ = 0L; /** *
     * A sequence number for the transaction in the wallet.
     * 
* * int64 no = 1 [json_name = "no"]; * @return The no. */ @java.lang.Override public long getNo() { return no_; } public static final int TX_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object txId_ = ""; /** *
     * The unique ID of the transaction.
     * 
* * string tx_id = 2 [json_name = "txId"]; * @return The txId. */ @java.lang.Override public java.lang.String getTxId() { java.lang.Object ref = txId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); txId_ = s; return s; } } /** *
     * The unique ID of the transaction.
     * 
* * string tx_id = 2 [json_name = "txId"]; * @return The bytes for txId. */ @java.lang.Override public com.google.protobuf.ByteString getTxIdBytes() { java.lang.Object ref = txId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); txId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SENDER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object sender_ = ""; /** *
     * The sender's address.
     * 
* * string sender = 3 [json_name = "sender"]; * @return The sender. */ @java.lang.Override public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** *
     * The sender's address.
     * 
* * string sender = 3 [json_name = "sender"]; * @return The bytes for sender. */ @java.lang.Override public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RECEIVER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object receiver_ = ""; /** *
     * The receiver's address.
     * 
* * string receiver = 4 [json_name = "receiver"]; * @return The receiver. */ @java.lang.Override public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } } /** *
     * The receiver's address.
     * 
* * string receiver = 4 [json_name = "receiver"]; * @return The bytes for receiver. */ @java.lang.Override public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DIRECTION_FIELD_NUMBER = 5; private int direction_ = 0; /** *
     * The direction of the transaction relative to the wallet.
     * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ @java.lang.Override public int getDirectionValue() { return direction_; } /** *
     * The direction of the transaction relative to the wallet.
     * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return The direction. */ @java.lang.Override public pactus.WalletOuterClass.TxDirection getDirection() { pactus.WalletOuterClass.TxDirection result = pactus.WalletOuterClass.TxDirection.forNumber(direction_); return result == null ? pactus.WalletOuterClass.TxDirection.UNRECOGNIZED : result; } public static final int AMOUNT_FIELD_NUMBER = 6; private long amount_ = 0L; /** *
     * The amount involved in the transaction in NanoPAC.
     * 
* * int64 amount = 6 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } public static final int FEE_FIELD_NUMBER = 7; private long fee_ = 0L; /** *
     * The transaction fee in NanoPAC.
     * 
* * int64 fee = 7 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } public static final int MEMO_FIELD_NUMBER = 8; @SuppressWarnings("serial") private volatile java.lang.Object memo_ = ""; /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } } /** *
     * A memo string for the transaction.
     * 
* * string memo = 8 [json_name = "memo"]; * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 9; private int status_ = 0; /** *
     * The current status of the transaction.
     * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** *
     * The current status of the transaction.
     * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return The status. */ @java.lang.Override public pactus.WalletOuterClass.TransactionStatus getStatus() { pactus.WalletOuterClass.TransactionStatus result = pactus.WalletOuterClass.TransactionStatus.forNumber(status_); return result == null ? pactus.WalletOuterClass.TransactionStatus.UNRECOGNIZED : result; } public static final int BLOCK_HEIGHT_FIELD_NUMBER = 10; private int blockHeight_ = 0; /** *
     * The block height containing the transaction.
     * 
* * uint32 block_height = 10 [json_name = "blockHeight"]; * @return The blockHeight. */ @java.lang.Override public int getBlockHeight() { return blockHeight_; } public static final int PAYLOAD_TYPE_FIELD_NUMBER = 11; private int payloadType_ = 0; /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
     * The type of transaction payload.
     * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } public static final int DATA_FIELD_NUMBER = 12; private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; /** *
     * The raw transaction data.
     * 
* * bytes data = 12 [json_name = "data"]; * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return data_; } public static final int COMMENT_FIELD_NUMBER = 13; @SuppressWarnings("serial") private volatile java.lang.Object comment_ = ""; /** *
     * A comment associated with the transaction in the wallet.
     * 
* * string comment = 13 [json_name = "comment"]; * @return The comment. */ @java.lang.Override public java.lang.String getComment() { java.lang.Object ref = comment_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); comment_ = s; return s; } } /** *
     * A comment associated with the transaction in the wallet.
     * 
* * string comment = 13 [json_name = "comment"]; * @return The bytes for comment. */ @java.lang.Override public com.google.protobuf.ByteString getCommentBytes() { java.lang.Object ref = comment_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); comment_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATED_AT_FIELD_NUMBER = 14; private long createdAt_ = 0L; /** *
     * Unix timestamp of when the transaction was created.
     * 
* * int64 created_at = 14 [json_name = "createdAt"]; * @return The createdAt. */ @java.lang.Override public long getCreatedAt() { return createdAt_; } public static final int UPDATED_AT_FIELD_NUMBER = 15; private long updatedAt_ = 0L; /** *
     * Unix timestamp of when the transaction was last updated.
     * 
* * int64 updated_at = 15 [json_name = "updatedAt"]; * @return The updatedAt. */ @java.lang.Override public long getUpdatedAt() { return updatedAt_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (no_ != 0L) { output.writeInt64(1, no_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(txId_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, txId_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { com.google.protobuf.GeneratedMessage.writeString(output, 4, receiver_); } if (direction_ != pactus.WalletOuterClass.TxDirection.TX_DIRECTION_ANY.getNumber()) { output.writeEnum(5, direction_); } if (amount_ != 0L) { output.writeInt64(6, amount_); } if (fee_ != 0L) { output.writeInt64(7, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { com.google.protobuf.GeneratedMessage.writeString(output, 8, memo_); } if (status_ != pactus.WalletOuterClass.TransactionStatus.TRANSACTION_STATUS_PENDING.getNumber()) { output.writeEnum(9, status_); } if (blockHeight_ != 0) { output.writeUInt32(10, blockHeight_); } if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(11, payloadType_); } if (!data_.isEmpty()) { output.writeBytes(12, data_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(comment_)) { com.google.protobuf.GeneratedMessage.writeString(output, 13, comment_); } if (createdAt_ != 0L) { output.writeInt64(14, createdAt_); } if (updatedAt_ != 0L) { output.writeInt64(15, updatedAt_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (no_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, no_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(txId_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, txId_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(sender_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, sender_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(receiver_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(4, receiver_); } if (direction_ != pactus.WalletOuterClass.TxDirection.TX_DIRECTION_ANY.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, direction_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, amount_); } if (fee_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, fee_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(memo_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(8, memo_); } if (status_ != pactus.WalletOuterClass.TransactionStatus.TRANSACTION_STATUS_PENDING.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(9, status_); } if (blockHeight_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(10, blockHeight_); } if (payloadType_ != pactus.TransactionOuterClass.PayloadType.PAYLOAD_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(11, payloadType_); } if (!data_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(12, data_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(comment_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(13, comment_); } if (createdAt_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(14, createdAt_); } if (updatedAt_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(15, updatedAt_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.WalletTransactionInfo)) { return super.equals(obj); } pactus.WalletOuterClass.WalletTransactionInfo other = (pactus.WalletOuterClass.WalletTransactionInfo) obj; if (getNo() != other.getNo()) return false; if (!getTxId() .equals(other.getTxId())) return false; if (!getSender() .equals(other.getSender())) return false; if (!getReceiver() .equals(other.getReceiver())) return false; if (direction_ != other.direction_) return false; if (getAmount() != other.getAmount()) return false; if (getFee() != other.getFee()) return false; if (!getMemo() .equals(other.getMemo())) return false; if (status_ != other.status_) return false; if (getBlockHeight() != other.getBlockHeight()) return false; if (payloadType_ != other.payloadType_) return false; if (!getData() .equals(other.getData())) return false; if (!getComment() .equals(other.getComment())) return false; if (getCreatedAt() != other.getCreatedAt()) return false; if (getUpdatedAt() != other.getUpdatedAt()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NO_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getNo()); hash = (37 * hash) + TX_ID_FIELD_NUMBER; hash = (53 * hash) + getTxId().hashCode(); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); hash = (37 * hash) + RECEIVER_FIELD_NUMBER; hash = (53 * hash) + getReceiver().hashCode(); hash = (37 * hash) + DIRECTION_FIELD_NUMBER; hash = (53 * hash) + direction_; hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (37 * hash) + FEE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFee()); hash = (37 * hash) + MEMO_FIELD_NUMBER; hash = (53 * hash) + getMemo().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (37 * hash) + BLOCK_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + getBlockHeight(); hash = (37 * hash) + PAYLOAD_TYPE_FIELD_NUMBER; hash = (53 * hash) + payloadType_; hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); hash = (37 * hash) + COMMENT_FIELD_NUMBER; hash = (53 * hash) + getComment().hashCode(); hash = (37 * hash) + CREATED_AT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCreatedAt()); hash = (37 * hash) + UPDATED_AT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getUpdatedAt()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.WalletTransactionInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.WalletTransactionInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.WalletTransactionInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.WalletTransactionInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * WalletTransactionInfo contains information about a transaction in a wallet.
     * 
* * Protobuf type {@code pactus.WalletTransactionInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.WalletTransactionInfo) pactus.WalletOuterClass.WalletTransactionInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_WalletTransactionInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_WalletTransactionInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.WalletTransactionInfo.class, pactus.WalletOuterClass.WalletTransactionInfo.Builder.class); } // Construct using pactus.WalletOuterClass.WalletTransactionInfo.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; no_ = 0L; txId_ = ""; sender_ = ""; receiver_ = ""; direction_ = 0; amount_ = 0L; fee_ = 0L; memo_ = ""; status_ = 0; blockHeight_ = 0; payloadType_ = 0; data_ = com.google.protobuf.ByteString.EMPTY; comment_ = ""; createdAt_ = 0L; updatedAt_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_WalletTransactionInfo_descriptor; } @java.lang.Override public pactus.WalletOuterClass.WalletTransactionInfo getDefaultInstanceForType() { return pactus.WalletOuterClass.WalletTransactionInfo.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.WalletTransactionInfo build() { pactus.WalletOuterClass.WalletTransactionInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.WalletTransactionInfo buildPartial() { pactus.WalletOuterClass.WalletTransactionInfo result = new pactus.WalletOuterClass.WalletTransactionInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.WalletTransactionInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.no_ = no_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.txId_ = txId_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.sender_ = sender_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.receiver_ = receiver_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.direction_ = direction_; } if (((from_bitField0_ & 0x00000020) != 0)) { result.amount_ = amount_; } if (((from_bitField0_ & 0x00000040) != 0)) { result.fee_ = fee_; } if (((from_bitField0_ & 0x00000080) != 0)) { result.memo_ = memo_; } if (((from_bitField0_ & 0x00000100) != 0)) { result.status_ = status_; } if (((from_bitField0_ & 0x00000200) != 0)) { result.blockHeight_ = blockHeight_; } if (((from_bitField0_ & 0x00000400) != 0)) { result.payloadType_ = payloadType_; } if (((from_bitField0_ & 0x00000800) != 0)) { result.data_ = data_; } if (((from_bitField0_ & 0x00001000) != 0)) { result.comment_ = comment_; } if (((from_bitField0_ & 0x00002000) != 0)) { result.createdAt_ = createdAt_; } if (((from_bitField0_ & 0x00004000) != 0)) { result.updatedAt_ = updatedAt_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.WalletTransactionInfo) { return mergeFrom((pactus.WalletOuterClass.WalletTransactionInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.WalletTransactionInfo other) { if (other == pactus.WalletOuterClass.WalletTransactionInfo.getDefaultInstance()) return this; if (other.getNo() != 0L) { setNo(other.getNo()); } if (!other.getTxId().isEmpty()) { txId_ = other.txId_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getSender().isEmpty()) { sender_ = other.sender_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getReceiver().isEmpty()) { receiver_ = other.receiver_; bitField0_ |= 0x00000008; onChanged(); } if (other.direction_ != 0) { setDirectionValue(other.getDirectionValue()); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } if (other.getFee() != 0L) { setFee(other.getFee()); } if (!other.getMemo().isEmpty()) { memo_ = other.memo_; bitField0_ |= 0x00000080; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } if (other.getBlockHeight() != 0) { setBlockHeight(other.getBlockHeight()); } if (other.payloadType_ != 0) { setPayloadTypeValue(other.getPayloadTypeValue()); } if (!other.getData().isEmpty()) { setData(other.getData()); } if (!other.getComment().isEmpty()) { comment_ = other.comment_; bitField0_ |= 0x00001000; onChanged(); } if (other.getCreatedAt() != 0L) { setCreatedAt(other.getCreatedAt()); } if (other.getUpdatedAt() != 0L) { setUpdatedAt(other.getUpdatedAt()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { no_ = input.readInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { txId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { sender_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { receiver_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 40: { direction_ = input.readEnum(); bitField0_ |= 0x00000010; break; } // case 40 case 48: { amount_ = input.readInt64(); bitField0_ |= 0x00000020; break; } // case 48 case 56: { fee_ = input.readInt64(); bitField0_ |= 0x00000040; break; } // case 56 case 66: { memo_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000080; break; } // case 66 case 72: { status_ = input.readEnum(); bitField0_ |= 0x00000100; break; } // case 72 case 80: { blockHeight_ = input.readUInt32(); bitField0_ |= 0x00000200; break; } // case 80 case 88: { payloadType_ = input.readEnum(); bitField0_ |= 0x00000400; break; } // case 88 case 98: { data_ = input.readBytes(); bitField0_ |= 0x00000800; break; } // case 98 case 106: { comment_ = input.readStringRequireUtf8(); bitField0_ |= 0x00001000; break; } // case 106 case 112: { createdAt_ = input.readInt64(); bitField0_ |= 0x00002000; break; } // case 112 case 120: { updatedAt_ = input.readInt64(); bitField0_ |= 0x00004000; break; } // case 120 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private long no_ ; /** *
       * A sequence number for the transaction in the wallet.
       * 
* * int64 no = 1 [json_name = "no"]; * @return The no. */ @java.lang.Override public long getNo() { return no_; } /** *
       * A sequence number for the transaction in the wallet.
       * 
* * int64 no = 1 [json_name = "no"]; * @param value The no to set. * @return This builder for chaining. */ public Builder setNo(long value) { no_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * A sequence number for the transaction in the wallet.
       * 
* * int64 no = 1 [json_name = "no"]; * @return This builder for chaining. */ public Builder clearNo() { bitField0_ = (bitField0_ & ~0x00000001); no_ = 0L; onChanged(); return this; } private java.lang.Object txId_ = ""; /** *
       * The unique ID of the transaction.
       * 
* * string tx_id = 2 [json_name = "txId"]; * @return The txId. */ public java.lang.String getTxId() { java.lang.Object ref = txId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); txId_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The unique ID of the transaction.
       * 
* * string tx_id = 2 [json_name = "txId"]; * @return The bytes for txId. */ public com.google.protobuf.ByteString getTxIdBytes() { java.lang.Object ref = txId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); txId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The unique ID of the transaction.
       * 
* * string tx_id = 2 [json_name = "txId"]; * @param value The txId to set. * @return This builder for chaining. */ public Builder setTxId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } txId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The unique ID of the transaction.
       * 
* * string tx_id = 2 [json_name = "txId"]; * @return This builder for chaining. */ public Builder clearTxId() { txId_ = getDefaultInstance().getTxId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * The unique ID of the transaction.
       * 
* * string tx_id = 2 [json_name = "txId"]; * @param value The bytes for txId to set. * @return This builder for chaining. */ public Builder setTxIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); txId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object sender_ = ""; /** *
       * The sender's address.
       * 
* * string sender = 3 [json_name = "sender"]; * @return The sender. */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 3 [json_name = "sender"]; * @return The bytes for sender. */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The sender's address.
       * 
* * string sender = 3 [json_name = "sender"]; * @param value The sender to set. * @return This builder for chaining. */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 3 [json_name = "sender"]; * @return This builder for chaining. */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The sender's address.
       * 
* * string sender = 3 [json_name = "sender"]; * @param value The bytes for sender to set. * @return This builder for chaining. */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object receiver_ = ""; /** *
       * The receiver's address.
       * 
* * string receiver = 4 [json_name = "receiver"]; * @return The receiver. */ public java.lang.String getReceiver() { java.lang.Object ref = receiver_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); receiver_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 4 [json_name = "receiver"]; * @return The bytes for receiver. */ public com.google.protobuf.ByteString getReceiverBytes() { java.lang.Object ref = receiver_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); receiver_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The receiver's address.
       * 
* * string receiver = 4 [json_name = "receiver"]; * @param value The receiver to set. * @return This builder for chaining. */ public Builder setReceiver( java.lang.String value) { if (value == null) { throw new NullPointerException(); } receiver_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 4 [json_name = "receiver"]; * @return This builder for chaining. */ public Builder clearReceiver() { receiver_ = getDefaultInstance().getReceiver(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** *
       * The receiver's address.
       * 
* * string receiver = 4 [json_name = "receiver"]; * @param value The bytes for receiver to set. * @return This builder for chaining. */ public Builder setReceiverBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); receiver_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private int direction_ = 0; /** *
       * The direction of the transaction relative to the wallet.
       * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ @java.lang.Override public int getDirectionValue() { return direction_; } /** *
       * The direction of the transaction relative to the wallet.
       * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @param value The enum numeric value on the wire for direction to set. * @return This builder for chaining. */ public Builder setDirectionValue(int value) { direction_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * The direction of the transaction relative to the wallet.
       * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return The direction. */ @java.lang.Override public pactus.WalletOuterClass.TxDirection getDirection() { pactus.WalletOuterClass.TxDirection result = pactus.WalletOuterClass.TxDirection.forNumber(direction_); return result == null ? pactus.WalletOuterClass.TxDirection.UNRECOGNIZED : result; } /** *
       * The direction of the transaction relative to the wallet.
       * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @param value The direction to set. * @return This builder for chaining. */ public Builder setDirection(pactus.WalletOuterClass.TxDirection value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000010; direction_ = value.getNumber(); onChanged(); return this; } /** *
       * The direction of the transaction relative to the wallet.
       * 
* * .pactus.TxDirection direction = 5 [json_name = "direction"]; * @return This builder for chaining. */ public Builder clearDirection() { bitField0_ = (bitField0_ & ~0x00000010); direction_ = 0; onChanged(); return this; } private long amount_ ; /** *
       * The amount involved in the transaction in NanoPAC.
       * 
* * int64 amount = 6 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The amount involved in the transaction in NanoPAC.
       * 
* * int64 amount = 6 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000020; onChanged(); return this; } /** *
       * The amount involved in the transaction in NanoPAC.
       * 
* * int64 amount = 6 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000020); amount_ = 0L; onChanged(); return this; } private long fee_ ; /** *
       * The transaction fee in NanoPAC.
       * 
* * int64 fee = 7 [json_name = "fee"]; * @return The fee. */ @java.lang.Override public long getFee() { return fee_; } /** *
       * The transaction fee in NanoPAC.
       * 
* * int64 fee = 7 [json_name = "fee"]; * @param value The fee to set. * @return This builder for chaining. */ public Builder setFee(long value) { fee_ = value; bitField0_ |= 0x00000040; onChanged(); return this; } /** *
       * The transaction fee in NanoPAC.
       * 
* * int64 fee = 7 [json_name = "fee"]; * @return This builder for chaining. */ public Builder clearFee() { bitField0_ = (bitField0_ & ~0x00000040); fee_ = 0L; onChanged(); return this; } private java.lang.Object memo_ = ""; /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @return The memo. */ public java.lang.String getMemo() { java.lang.Object ref = memo_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); memo_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @return The bytes for memo. */ public com.google.protobuf.ByteString getMemoBytes() { java.lang.Object ref = memo_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); memo_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } memo_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @return This builder for chaining. */ public Builder clearMemo() { memo_ = getDefaultInstance().getMemo(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); return this; } /** *
       * A memo string for the transaction.
       * 
* * string memo = 8 [json_name = "memo"]; * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); memo_ = value; bitField0_ |= 0x00000080; onChanged(); return this; } private int status_ = 0; /** *
       * The current status of the transaction.
       * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** *
       * The current status of the transaction.
       * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000100; onChanged(); return this; } /** *
       * The current status of the transaction.
       * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return The status. */ @java.lang.Override public pactus.WalletOuterClass.TransactionStatus getStatus() { pactus.WalletOuterClass.TransactionStatus result = pactus.WalletOuterClass.TransactionStatus.forNumber(status_); return result == null ? pactus.WalletOuterClass.TransactionStatus.UNRECOGNIZED : result; } /** *
       * The current status of the transaction.
       * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(pactus.WalletOuterClass.TransactionStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000100; status_ = value.getNumber(); onChanged(); return this; } /** *
       * The current status of the transaction.
       * 
* * .pactus.TransactionStatus status = 9 [json_name = "status"]; * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000100); status_ = 0; onChanged(); return this; } private int blockHeight_ ; /** *
       * The block height containing the transaction.
       * 
* * uint32 block_height = 10 [json_name = "blockHeight"]; * @return The blockHeight. */ @java.lang.Override public int getBlockHeight() { return blockHeight_; } /** *
       * The block height containing the transaction.
       * 
* * uint32 block_height = 10 [json_name = "blockHeight"]; * @param value The blockHeight to set. * @return This builder for chaining. */ public Builder setBlockHeight(int value) { blockHeight_ = value; bitField0_ |= 0x00000200; onChanged(); return this; } /** *
       * The block height containing the transaction.
       * 
* * uint32 block_height = 10 [json_name = "blockHeight"]; * @return This builder for chaining. */ public Builder clearBlockHeight() { bitField0_ = (bitField0_ & ~0x00000200); blockHeight_ = 0; onChanged(); return this; } private int payloadType_ = 0; /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return The enum numeric value on the wire for payloadType. */ @java.lang.Override public int getPayloadTypeValue() { return payloadType_; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @param value The enum numeric value on the wire for payloadType to set. * @return This builder for chaining. */ public Builder setPayloadTypeValue(int value) { payloadType_ = value; bitField0_ |= 0x00000400; onChanged(); return this; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return The payloadType. */ @java.lang.Override public pactus.TransactionOuterClass.PayloadType getPayloadType() { pactus.TransactionOuterClass.PayloadType result = pactus.TransactionOuterClass.PayloadType.forNumber(payloadType_); return result == null ? pactus.TransactionOuterClass.PayloadType.UNRECOGNIZED : result; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @param value The payloadType to set. * @return This builder for chaining. */ public Builder setPayloadType(pactus.TransactionOuterClass.PayloadType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000400; payloadType_ = value.getNumber(); onChanged(); return this; } /** *
       * The type of transaction payload.
       * 
* * .pactus.PayloadType payload_type = 11 [json_name = "payloadType"]; * @return This builder for chaining. */ public Builder clearPayloadType() { bitField0_ = (bitField0_ & ~0x00000400); payloadType_ = 0; onChanged(); return this; } private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; /** *
       * The raw transaction data.
       * 
* * bytes data = 12 [json_name = "data"]; * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return data_; } /** *
       * The raw transaction data.
       * 
* * bytes data = 12 [json_name = "data"]; * @param value The data to set. * @return This builder for chaining. */ public Builder setData(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } data_ = value; bitField0_ |= 0x00000800; onChanged(); return this; } /** *
       * The raw transaction data.
       * 
* * bytes data = 12 [json_name = "data"]; * @return This builder for chaining. */ public Builder clearData() { bitField0_ = (bitField0_ & ~0x00000800); data_ = getDefaultInstance().getData(); onChanged(); return this; } private java.lang.Object comment_ = ""; /** *
       * A comment associated with the transaction in the wallet.
       * 
* * string comment = 13 [json_name = "comment"]; * @return The comment. */ public java.lang.String getComment() { java.lang.Object ref = comment_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); comment_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * A comment associated with the transaction in the wallet.
       * 
* * string comment = 13 [json_name = "comment"]; * @return The bytes for comment. */ public com.google.protobuf.ByteString getCommentBytes() { java.lang.Object ref = comment_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); comment_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * A comment associated with the transaction in the wallet.
       * 
* * string comment = 13 [json_name = "comment"]; * @param value The comment to set. * @return This builder for chaining. */ public Builder setComment( java.lang.String value) { if (value == null) { throw new NullPointerException(); } comment_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } /** *
       * A comment associated with the transaction in the wallet.
       * 
* * string comment = 13 [json_name = "comment"]; * @return This builder for chaining. */ public Builder clearComment() { comment_ = getDefaultInstance().getComment(); bitField0_ = (bitField0_ & ~0x00001000); onChanged(); return this; } /** *
       * A comment associated with the transaction in the wallet.
       * 
* * string comment = 13 [json_name = "comment"]; * @param value The bytes for comment to set. * @return This builder for chaining. */ public Builder setCommentBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); comment_ = value; bitField0_ |= 0x00001000; onChanged(); return this; } private long createdAt_ ; /** *
       * Unix timestamp of when the transaction was created.
       * 
* * int64 created_at = 14 [json_name = "createdAt"]; * @return The createdAt. */ @java.lang.Override public long getCreatedAt() { return createdAt_; } /** *
       * Unix timestamp of when the transaction was created.
       * 
* * int64 created_at = 14 [json_name = "createdAt"]; * @param value The createdAt to set. * @return This builder for chaining. */ public Builder setCreatedAt(long value) { createdAt_ = value; bitField0_ |= 0x00002000; onChanged(); return this; } /** *
       * Unix timestamp of when the transaction was created.
       * 
* * int64 created_at = 14 [json_name = "createdAt"]; * @return This builder for chaining. */ public Builder clearCreatedAt() { bitField0_ = (bitField0_ & ~0x00002000); createdAt_ = 0L; onChanged(); return this; } private long updatedAt_ ; /** *
       * Unix timestamp of when the transaction was last updated.
       * 
* * int64 updated_at = 15 [json_name = "updatedAt"]; * @return The updatedAt. */ @java.lang.Override public long getUpdatedAt() { return updatedAt_; } /** *
       * Unix timestamp of when the transaction was last updated.
       * 
* * int64 updated_at = 15 [json_name = "updatedAt"]; * @param value The updatedAt to set. * @return This builder for chaining. */ public Builder setUpdatedAt(long value) { updatedAt_ = value; bitField0_ |= 0x00004000; onChanged(); return this; } /** *
       * Unix timestamp of when the transaction was last updated.
       * 
* * int64 updated_at = 15 [json_name = "updatedAt"]; * @return This builder for chaining. */ public Builder clearUpdatedAt() { bitField0_ = (bitField0_ & ~0x00004000); updatedAt_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.WalletTransactionInfo) } // @@protoc_insertion_point(class_scope:pactus.WalletTransactionInfo) private static final pactus.WalletOuterClass.WalletTransactionInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.WalletTransactionInfo(); } public static pactus.WalletOuterClass.WalletTransactionInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public WalletTransactionInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.WalletTransactionInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListTransactionsRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListTransactionsRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to query transactions for.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to query transactions for.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Optional: The address to filter transactions.
     * If empty or set to '*', transactions for all addresses in the wallet are included.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * Optional: The address to filter transactions.
     * If empty or set to '*', transactions for all addresses in the wallet are included.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); /** *
     * Filter transactions by direction relative to the wallet.
     * Defaults to any direction if not set.
     * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ int getDirectionValue(); /** *
     * Filter transactions by direction relative to the wallet.
     * Defaults to any direction if not set.
     * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return The direction. */ pactus.WalletOuterClass.TxDirection getDirection(); /** *
     * Optional: The maximum number of transactions to return.
     * Defaults to 10 if not set.
     * 
* * int32 count = 4 [json_name = "count"]; * @return The count. */ int getCount(); /** *
     * Optional: The number of transactions to skip (for pagination).
     * Defaults to 0 if not set.
     * 
* * int32 skip = 5 [json_name = "skip"]; * @return The skip. */ int getSkip(); } /** *
   * Request message for listing transactions of a wallet, optionally filtered by a specific address.
   * 
* * Protobuf type {@code pactus.ListTransactionsRequest} */ public static final class ListTransactionsRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListTransactionsRequest) ListTransactionsRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListTransactionsRequest"); } // Use ListTransactionsRequest.newBuilder() to construct. private ListTransactionsRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListTransactionsRequest() { walletName_ = ""; address_ = ""; direction_ = 0; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListTransactionsRequest.class, pactus.WalletOuterClass.ListTransactionsRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to query transactions for.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to query transactions for.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * Optional: The address to filter transactions.
     * If empty or set to '*', transactions for all addresses in the wallet are included.
     * 
* * string address = 2 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * Optional: The address to filter transactions.
     * If empty or set to '*', transactions for all addresses in the wallet are included.
     * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DIRECTION_FIELD_NUMBER = 3; private int direction_ = 0; /** *
     * Filter transactions by direction relative to the wallet.
     * Defaults to any direction if not set.
     * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ @java.lang.Override public int getDirectionValue() { return direction_; } /** *
     * Filter transactions by direction relative to the wallet.
     * Defaults to any direction if not set.
     * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return The direction. */ @java.lang.Override public pactus.WalletOuterClass.TxDirection getDirection() { pactus.WalletOuterClass.TxDirection result = pactus.WalletOuterClass.TxDirection.forNumber(direction_); return result == null ? pactus.WalletOuterClass.TxDirection.UNRECOGNIZED : result; } public static final int COUNT_FIELD_NUMBER = 4; private int count_ = 0; /** *
     * Optional: The maximum number of transactions to return.
     * Defaults to 10 if not set.
     * 
* * int32 count = 4 [json_name = "count"]; * @return The count. */ @java.lang.Override public int getCount() { return count_; } public static final int SKIP_FIELD_NUMBER = 5; private int skip_ = 0; /** *
     * Optional: The number of transactions to skip (for pagination).
     * Defaults to 0 if not set.
     * 
* * int32 skip = 5 [json_name = "skip"]; * @return The skip. */ @java.lang.Override public int getSkip() { return skip_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, address_); } if (direction_ != pactus.WalletOuterClass.TxDirection.TX_DIRECTION_ANY.getNumber()) { output.writeEnum(3, direction_); } if (count_ != 0) { output.writeInt32(4, count_); } if (skip_ != 0) { output.writeInt32(5, skip_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, address_); } if (direction_ != pactus.WalletOuterClass.TxDirection.TX_DIRECTION_ANY.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(3, direction_); } if (count_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, count_); } if (skip_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(5, skip_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.ListTransactionsRequest)) { return super.equals(obj); } pactus.WalletOuterClass.ListTransactionsRequest other = (pactus.WalletOuterClass.ListTransactionsRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (direction_ != other.direction_) return false; if (getCount() != other.getCount()) return false; if (getSkip() != other.getSkip()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (37 * hash) + DIRECTION_FIELD_NUMBER; hash = (53 * hash) + direction_; hash = (37 * hash) + COUNT_FIELD_NUMBER; hash = (53 * hash) + getCount(); hash = (37 * hash) + SKIP_FIELD_NUMBER; hash = (53 * hash) + getSkip(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListTransactionsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListTransactionsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.ListTransactionsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for listing transactions of a wallet, optionally filtered by a specific address.
     * 
* * Protobuf type {@code pactus.ListTransactionsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListTransactionsRequest) pactus.WalletOuterClass.ListTransactionsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListTransactionsRequest.class, pactus.WalletOuterClass.ListTransactionsRequest.Builder.class); } // Construct using pactus.WalletOuterClass.ListTransactionsRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; address_ = ""; direction_ = 0; count_ = 0; skip_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.ListTransactionsRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsRequest build() { pactus.WalletOuterClass.ListTransactionsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsRequest buildPartial() { pactus.WalletOuterClass.ListTransactionsRequest result = new pactus.WalletOuterClass.ListTransactionsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.ListTransactionsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.address_ = address_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.direction_ = direction_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.count_ = count_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.skip_ = skip_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.ListTransactionsRequest) { return mergeFrom((pactus.WalletOuterClass.ListTransactionsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.ListTransactionsRequest other) { if (other == pactus.WalletOuterClass.ListTransactionsRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000002; onChanged(); } if (other.direction_ != 0) { setDirectionValue(other.getDirectionValue()); } if (other.getCount() != 0) { setCount(other.getCount()); } if (other.getSkip() != 0) { setSkip(other.getSkip()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { direction_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { count_ = input.readInt32(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { skip_ = input.readInt32(); bitField0_ |= 0x00000010; break; } // case 40 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to query transactions for.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to query transactions for.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to query transactions for.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to query transactions for.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to query transactions for.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * Optional: The address to filter transactions.
       * If empty or set to '*', transactions for all addresses in the wallet are included.
       * 
* * string address = 2 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Optional: The address to filter transactions.
       * If empty or set to '*', transactions for all addresses in the wallet are included.
       * 
* * string address = 2 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Optional: The address to filter transactions.
       * If empty or set to '*', transactions for all addresses in the wallet are included.
       * 
* * string address = 2 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Optional: The address to filter transactions.
       * If empty or set to '*', transactions for all addresses in the wallet are included.
       * 
* * string address = 2 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Optional: The address to filter transactions.
       * If empty or set to '*', transactions for all addresses in the wallet are included.
       * 
* * string address = 2 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int direction_ = 0; /** *
       * Filter transactions by direction relative to the wallet.
       * Defaults to any direction if not set.
       * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return The enum numeric value on the wire for direction. */ @java.lang.Override public int getDirectionValue() { return direction_; } /** *
       * Filter transactions by direction relative to the wallet.
       * Defaults to any direction if not set.
       * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @param value The enum numeric value on the wire for direction to set. * @return This builder for chaining. */ public Builder setDirectionValue(int value) { direction_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * Filter transactions by direction relative to the wallet.
       * Defaults to any direction if not set.
       * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return The direction. */ @java.lang.Override public pactus.WalletOuterClass.TxDirection getDirection() { pactus.WalletOuterClass.TxDirection result = pactus.WalletOuterClass.TxDirection.forNumber(direction_); return result == null ? pactus.WalletOuterClass.TxDirection.UNRECOGNIZED : result; } /** *
       * Filter transactions by direction relative to the wallet.
       * Defaults to any direction if not set.
       * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @param value The direction to set. * @return This builder for chaining. */ public Builder setDirection(pactus.WalletOuterClass.TxDirection value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; direction_ = value.getNumber(); onChanged(); return this; } /** *
       * Filter transactions by direction relative to the wallet.
       * Defaults to any direction if not set.
       * 
* * .pactus.TxDirection direction = 3 [json_name = "direction"]; * @return This builder for chaining. */ public Builder clearDirection() { bitField0_ = (bitField0_ & ~0x00000004); direction_ = 0; onChanged(); return this; } private int count_ ; /** *
       * Optional: The maximum number of transactions to return.
       * Defaults to 10 if not set.
       * 
* * int32 count = 4 [json_name = "count"]; * @return The count. */ @java.lang.Override public int getCount() { return count_; } /** *
       * Optional: The maximum number of transactions to return.
       * Defaults to 10 if not set.
       * 
* * int32 count = 4 [json_name = "count"]; * @param value The count to set. * @return This builder for chaining. */ public Builder setCount(int value) { count_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** *
       * Optional: The maximum number of transactions to return.
       * Defaults to 10 if not set.
       * 
* * int32 count = 4 [json_name = "count"]; * @return This builder for chaining. */ public Builder clearCount() { bitField0_ = (bitField0_ & ~0x00000008); count_ = 0; onChanged(); return this; } private int skip_ ; /** *
       * Optional: The number of transactions to skip (for pagination).
       * Defaults to 0 if not set.
       * 
* * int32 skip = 5 [json_name = "skip"]; * @return The skip. */ @java.lang.Override public int getSkip() { return skip_; } /** *
       * Optional: The number of transactions to skip (for pagination).
       * Defaults to 0 if not set.
       * 
* * int32 skip = 5 [json_name = "skip"]; * @param value The skip to set. * @return This builder for chaining. */ public Builder setSkip(int value) { skip_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** *
       * Optional: The number of transactions to skip (for pagination).
       * Defaults to 0 if not set.
       * 
* * int32 skip = 5 [json_name = "skip"]; * @return This builder for chaining. */ public Builder clearSkip() { bitField0_ = (bitField0_ & ~0x00000010); skip_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.ListTransactionsRequest) } // @@protoc_insertion_point(class_scope:pactus.ListTransactionsRequest) private static final pactus.WalletOuterClass.ListTransactionsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.ListTransactionsRequest(); } public static pactus.WalletOuterClass.ListTransactionsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListTransactionsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ListTransactionsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.ListTransactionsResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet queried.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet queried.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ java.util.List getTxsList(); /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ pactus.WalletOuterClass.WalletTransactionInfo getTxs(int index); /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ int getTxsCount(); /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ java.util.List getTxsOrBuilderList(); /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ pactus.WalletOuterClass.WalletTransactionInfoOrBuilder getTxsOrBuilder( int index); } /** *
   * Response message containing a list of transactions.
   * 
* * Protobuf type {@code pactus.ListTransactionsResponse} */ public static final class ListTransactionsResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.ListTransactionsResponse) ListTransactionsResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "ListTransactionsResponse"); } // Use ListTransactionsResponse.newBuilder() to construct. private ListTransactionsResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private ListTransactionsResponse() { walletName_ = ""; txs_ = java.util.Collections.emptyList(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListTransactionsResponse.class, pactus.WalletOuterClass.ListTransactionsResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet queried.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet queried.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TXS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List txs_; /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ @java.lang.Override public java.util.List getTxsList() { return txs_; } /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ @java.lang.Override public java.util.List getTxsOrBuilderList() { return txs_; } /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ @java.lang.Override public int getTxsCount() { return txs_.size(); } /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ @java.lang.Override public pactus.WalletOuterClass.WalletTransactionInfo getTxs(int index) { return txs_.get(index); } /** *
     * List of transactions for the wallet, filtered by the specified address if provided.
     * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ @java.lang.Override public pactus.WalletOuterClass.WalletTransactionInfoOrBuilder getTxsOrBuilder( int index) { return txs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } for (int i = 0; i < txs_.size(); i++) { output.writeMessage(2, txs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } for (int i = 0; i < txs_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, txs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.ListTransactionsResponse)) { return super.equals(obj); } pactus.WalletOuterClass.ListTransactionsResponse other = (pactus.WalletOuterClass.ListTransactionsResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getTxsList() .equals(other.getTxsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); if (getTxsCount() > 0) { hash = (37 * hash) + TXS_FIELD_NUMBER; hash = (53 * hash) + getTxsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListTransactionsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.ListTransactionsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.ListTransactionsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message containing a list of transactions.
     * 
* * Protobuf type {@code pactus.ListTransactionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.ListTransactionsResponse) pactus.WalletOuterClass.ListTransactionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.ListTransactionsResponse.class, pactus.WalletOuterClass.ListTransactionsResponse.Builder.class); } // Construct using pactus.WalletOuterClass.ListTransactionsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; if (txsBuilder_ == null) { txs_ = java.util.Collections.emptyList(); } else { txs_ = null; txsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_ListTransactionsResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.ListTransactionsResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsResponse build() { pactus.WalletOuterClass.ListTransactionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsResponse buildPartial() { pactus.WalletOuterClass.ListTransactionsResponse result = new pactus.WalletOuterClass.ListTransactionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(pactus.WalletOuterClass.ListTransactionsResponse result) { if (txsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { txs_ = java.util.Collections.unmodifiableList(txs_); bitField0_ = (bitField0_ & ~0x00000002); } result.txs_ = txs_; } else { result.txs_ = txsBuilder_.build(); } } private void buildPartial0(pactus.WalletOuterClass.ListTransactionsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.ListTransactionsResponse) { return mergeFrom((pactus.WalletOuterClass.ListTransactionsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.ListTransactionsResponse other) { if (other == pactus.WalletOuterClass.ListTransactionsResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (txsBuilder_ == null) { if (!other.txs_.isEmpty()) { if (txs_.isEmpty()) { txs_ = other.txs_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureTxsIsMutable(); txs_.addAll(other.txs_); } onChanged(); } } else { if (!other.txs_.isEmpty()) { if (txsBuilder_.isEmpty()) { txsBuilder_.dispose(); txsBuilder_ = null; txs_ = other.txs_; bitField0_ = (bitField0_ & ~0x00000002); txsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? internalGetTxsFieldBuilder() : null; } else { txsBuilder_.addAllMessages(other.txs_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { pactus.WalletOuterClass.WalletTransactionInfo m = input.readMessage( pactus.WalletOuterClass.WalletTransactionInfo.parser(), extensionRegistry); if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(m); } else { txsBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet queried.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet queried.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet queried.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet queried.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet queried.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List txs_ = java.util.Collections.emptyList(); private void ensureTxsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { txs_ = new java.util.ArrayList(txs_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilder< pactus.WalletOuterClass.WalletTransactionInfo, pactus.WalletOuterClass.WalletTransactionInfo.Builder, pactus.WalletOuterClass.WalletTransactionInfoOrBuilder> txsBuilder_; /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public java.util.List getTxsList() { if (txsBuilder_ == null) { return java.util.Collections.unmodifiableList(txs_); } else { return txsBuilder_.getMessageList(); } } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public int getTxsCount() { if (txsBuilder_ == null) { return txs_.size(); } else { return txsBuilder_.getCount(); } } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public pactus.WalletOuterClass.WalletTransactionInfo getTxs(int index) { if (txsBuilder_ == null) { return txs_.get(index); } else { return txsBuilder_.getMessage(index); } } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder setTxs( int index, pactus.WalletOuterClass.WalletTransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.set(index, value); onChanged(); } else { txsBuilder_.setMessage(index, value); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder setTxs( int index, pactus.WalletOuterClass.WalletTransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.set(index, builderForValue.build()); onChanged(); } else { txsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder addTxs(pactus.WalletOuterClass.WalletTransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.add(value); onChanged(); } else { txsBuilder_.addMessage(value); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder addTxs( int index, pactus.WalletOuterClass.WalletTransactionInfo value) { if (txsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTxsIsMutable(); txs_.add(index, value); onChanged(); } else { txsBuilder_.addMessage(index, value); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder addTxs( pactus.WalletOuterClass.WalletTransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(builderForValue.build()); onChanged(); } else { txsBuilder_.addMessage(builderForValue.build()); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder addTxs( int index, pactus.WalletOuterClass.WalletTransactionInfo.Builder builderForValue) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.add(index, builderForValue.build()); onChanged(); } else { txsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder addAllTxs( java.lang.Iterable values) { if (txsBuilder_ == null) { ensureTxsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, txs_); onChanged(); } else { txsBuilder_.addAllMessages(values); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder clearTxs() { if (txsBuilder_ == null) { txs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { txsBuilder_.clear(); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public Builder removeTxs(int index) { if (txsBuilder_ == null) { ensureTxsIsMutable(); txs_.remove(index); onChanged(); } else { txsBuilder_.remove(index); } return this; } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public pactus.WalletOuterClass.WalletTransactionInfo.Builder getTxsBuilder( int index) { return internalGetTxsFieldBuilder().getBuilder(index); } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public pactus.WalletOuterClass.WalletTransactionInfoOrBuilder getTxsOrBuilder( int index) { if (txsBuilder_ == null) { return txs_.get(index); } else { return txsBuilder_.getMessageOrBuilder(index); } } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public java.util.List getTxsOrBuilderList() { if (txsBuilder_ != null) { return txsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(txs_); } } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public pactus.WalletOuterClass.WalletTransactionInfo.Builder addTxsBuilder() { return internalGetTxsFieldBuilder().addBuilder( pactus.WalletOuterClass.WalletTransactionInfo.getDefaultInstance()); } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public pactus.WalletOuterClass.WalletTransactionInfo.Builder addTxsBuilder( int index) { return internalGetTxsFieldBuilder().addBuilder( index, pactus.WalletOuterClass.WalletTransactionInfo.getDefaultInstance()); } /** *
       * List of transactions for the wallet, filtered by the specified address if provided.
       * 
* * repeated .pactus.WalletTransactionInfo txs = 2 [json_name = "txs"]; */ public java.util.List getTxsBuilderList() { return internalGetTxsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< pactus.WalletOuterClass.WalletTransactionInfo, pactus.WalletOuterClass.WalletTransactionInfo.Builder, pactus.WalletOuterClass.WalletTransactionInfoOrBuilder> internalGetTxsFieldBuilder() { if (txsBuilder_ == null) { txsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< pactus.WalletOuterClass.WalletTransactionInfo, pactus.WalletOuterClass.WalletTransactionInfo.Builder, pactus.WalletOuterClass.WalletTransactionInfoOrBuilder>( txs_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); txs_ = null; } return txsBuilder_; } // @@protoc_insertion_point(builder_scope:pactus.ListTransactionsResponse) } // @@protoc_insertion_point(class_scope:pactus.ListTransactionsResponse) private static final pactus.WalletOuterClass.ListTransactionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.ListTransactionsResponse(); } public static pactus.WalletOuterClass.ListTransactionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public ListTransactionsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.ListTransactionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SetDefaultFeeRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SetDefaultFeeRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to set the default fee.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to set the default fee.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * The default fee amount in NanoPAC.
     * 
* * int64 amount = 2 [json_name = "amount"]; * @return The amount. */ long getAmount(); } /** *
   * Request message for setting default fee.
   * 
* * Protobuf type {@code pactus.SetDefaultFeeRequest} */ public static final class SetDefaultFeeRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SetDefaultFeeRequest) SetDefaultFeeRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SetDefaultFeeRequest"); } // Use SetDefaultFeeRequest.newBuilder() to construct. private SetDefaultFeeRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SetDefaultFeeRequest() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetDefaultFeeRequest.class, pactus.WalletOuterClass.SetDefaultFeeRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to set the default fee.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to set the default fee.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AMOUNT_FIELD_NUMBER = 2; private long amount_ = 0L; /** *
     * The default fee amount in NanoPAC.
     * 
* * int64 amount = 2 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (amount_ != 0L) { output.writeInt64(2, amount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (amount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, amount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SetDefaultFeeRequest)) { return super.equals(obj); } pactus.WalletOuterClass.SetDefaultFeeRequest other = (pactus.WalletOuterClass.SetDefaultFeeRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (getAmount() != other.getAmount()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + AMOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getAmount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetDefaultFeeRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SetDefaultFeeRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for setting default fee.
     * 
* * Protobuf type {@code pactus.SetDefaultFeeRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SetDefaultFeeRequest) pactus.WalletOuterClass.SetDefaultFeeRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetDefaultFeeRequest.class, pactus.WalletOuterClass.SetDefaultFeeRequest.Builder.class); } // Construct using pactus.WalletOuterClass.SetDefaultFeeRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; amount_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.SetDefaultFeeRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeRequest build() { pactus.WalletOuterClass.SetDefaultFeeRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeRequest buildPartial() { pactus.WalletOuterClass.SetDefaultFeeRequest result = new pactus.WalletOuterClass.SetDefaultFeeRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SetDefaultFeeRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.amount_ = amount_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SetDefaultFeeRequest) { return mergeFrom((pactus.WalletOuterClass.SetDefaultFeeRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SetDefaultFeeRequest other) { if (other == pactus.WalletOuterClass.SetDefaultFeeRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (other.getAmount() != 0L) { setAmount(other.getAmount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { amount_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to set the default fee.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to set the default fee.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to set the default fee.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to set the default fee.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to set the default fee.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private long amount_ ; /** *
       * The default fee amount in NanoPAC.
       * 
* * int64 amount = 2 [json_name = "amount"]; * @return The amount. */ @java.lang.Override public long getAmount() { return amount_; } /** *
       * The default fee amount in NanoPAC.
       * 
* * int64 amount = 2 [json_name = "amount"]; * @param value The amount to set. * @return This builder for chaining. */ public Builder setAmount(long value) { amount_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * The default fee amount in NanoPAC.
       * 
* * int64 amount = 2 [json_name = "amount"]; * @return This builder for chaining. */ public Builder clearAmount() { bitField0_ = (bitField0_ & ~0x00000002); amount_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SetDefaultFeeRequest) } // @@protoc_insertion_point(class_scope:pactus.SetDefaultFeeRequest) private static final pactus.WalletOuterClass.SetDefaultFeeRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SetDefaultFeeRequest(); } public static pactus.WalletOuterClass.SetDefaultFeeRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SetDefaultFeeRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SetDefaultFeeResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.SetDefaultFeeResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet where the default fee was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet where the default fee was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); } /** *
   * Response message for updated default fee.
   * 
* * Protobuf type {@code pactus.SetDefaultFeeResponse} */ public static final class SetDefaultFeeResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.SetDefaultFeeResponse) SetDefaultFeeResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "SetDefaultFeeResponse"); } // Use SetDefaultFeeResponse.newBuilder() to construct. private SetDefaultFeeResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private SetDefaultFeeResponse() { walletName_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetDefaultFeeResponse.class, pactus.WalletOuterClass.SetDefaultFeeResponse.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet where the default fee was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet where the default fee was updated.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.SetDefaultFeeResponse)) { return super.equals(obj); } pactus.WalletOuterClass.SetDefaultFeeResponse other = (pactus.WalletOuterClass.SetDefaultFeeResponse) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.SetDefaultFeeResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.SetDefaultFeeResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message for updated default fee.
     * 
* * Protobuf type {@code pactus.SetDefaultFeeResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.SetDefaultFeeResponse) pactus.WalletOuterClass.SetDefaultFeeResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.SetDefaultFeeResponse.class, pactus.WalletOuterClass.SetDefaultFeeResponse.Builder.class); } // Construct using pactus.WalletOuterClass.SetDefaultFeeResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_SetDefaultFeeResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.SetDefaultFeeResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeResponse build() { pactus.WalletOuterClass.SetDefaultFeeResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeResponse buildPartial() { pactus.WalletOuterClass.SetDefaultFeeResponse result = new pactus.WalletOuterClass.SetDefaultFeeResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.SetDefaultFeeResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.SetDefaultFeeResponse) { return mergeFrom((pactus.WalletOuterClass.SetDefaultFeeResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.SetDefaultFeeResponse other) { if (other == pactus.WalletOuterClass.SetDefaultFeeResponse.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet where the default fee was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet where the default fee was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet where the default fee was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet where the default fee was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet where the default fee was updated.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.SetDefaultFeeResponse) } // @@protoc_insertion_point(class_scope:pactus.SetDefaultFeeResponse) private static final pactus.WalletOuterClass.SetDefaultFeeResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.SetDefaultFeeResponse(); } public static pactus.WalletOuterClass.SetDefaultFeeResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public SetDefaultFeeResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.SetDefaultFeeResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetMnemonicRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetMnemonicRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet to get the mnemonic.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet to get the mnemonic.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); } /** *
   * Request message for getting mnemonic.
   * 
* * Protobuf type {@code pactus.GetMnemonicRequest} */ public static final class GetMnemonicRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetMnemonicRequest) GetMnemonicRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetMnemonicRequest"); } // Use GetMnemonicRequest.newBuilder() to construct. private GetMnemonicRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetMnemonicRequest() { walletName_ = ""; password_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetMnemonicRequest.class, pactus.WalletOuterClass.GetMnemonicRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet to get the mnemonic.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet to get the mnemonic.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, password_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, password_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetMnemonicRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetMnemonicRequest other = (pactus.WalletOuterClass.GetMnemonicRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetMnemonicRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetMnemonicRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetMnemonicRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for getting mnemonic.
     * 
* * Protobuf type {@code pactus.GetMnemonicRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetMnemonicRequest) pactus.WalletOuterClass.GetMnemonicRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetMnemonicRequest.class, pactus.WalletOuterClass.GetMnemonicRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetMnemonicRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; password_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetMnemonicRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicRequest build() { pactus.WalletOuterClass.GetMnemonicRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicRequest buildPartial() { pactus.WalletOuterClass.GetMnemonicRequest result = new pactus.WalletOuterClass.GetMnemonicRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetMnemonicRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.password_ = password_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetMnemonicRequest) { return mergeFrom((pactus.WalletOuterClass.GetMnemonicRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetMnemonicRequest other) { if (other == pactus.WalletOuterClass.GetMnemonicRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet to get the mnemonic.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet to get the mnemonic.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet to get the mnemonic.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet to get the mnemonic.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet to get the mnemonic.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetMnemonicRequest) } // @@protoc_insertion_point(class_scope:pactus.GetMnemonicRequest) private static final pactus.WalletOuterClass.GetMnemonicRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetMnemonicRequest(); } public static pactus.WalletOuterClass.GetMnemonicRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetMnemonicRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetMnemonicResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetMnemonicResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The mnemonic (seed phrase).
     * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return The mnemonic. */ java.lang.String getMnemonic(); /** *
     * The mnemonic (seed phrase).
     * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ com.google.protobuf.ByteString getMnemonicBytes(); } /** *
   * Response message contains mnemonic.
   * 
* * Protobuf type {@code pactus.GetMnemonicResponse} */ public static final class GetMnemonicResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetMnemonicResponse) GetMnemonicResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetMnemonicResponse"); } // Use GetMnemonicResponse.newBuilder() to construct. private GetMnemonicResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetMnemonicResponse() { mnemonic_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetMnemonicResponse.class, pactus.WalletOuterClass.GetMnemonicResponse.Builder.class); } public static final int MNEMONIC_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object mnemonic_ = ""; /** *
     * The mnemonic (seed phrase).
     * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return The mnemonic. */ @java.lang.Override public java.lang.String getMnemonic() { java.lang.Object ref = mnemonic_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mnemonic_ = s; return s; } } /** *
     * The mnemonic (seed phrase).
     * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ @java.lang.Override public com.google.protobuf.ByteString getMnemonicBytes() { java.lang.Object ref = mnemonic_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); mnemonic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(mnemonic_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, mnemonic_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(mnemonic_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, mnemonic_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetMnemonicResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetMnemonicResponse other = (pactus.WalletOuterClass.GetMnemonicResponse) obj; if (!getMnemonic() .equals(other.getMnemonic())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + MNEMONIC_FIELD_NUMBER; hash = (53 * hash) + getMnemonic().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetMnemonicResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetMnemonicResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetMnemonicResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains mnemonic.
     * 
* * Protobuf type {@code pactus.GetMnemonicResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetMnemonicResponse) pactus.WalletOuterClass.GetMnemonicResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetMnemonicResponse.class, pactus.WalletOuterClass.GetMnemonicResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetMnemonicResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; mnemonic_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetMnemonicResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetMnemonicResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicResponse build() { pactus.WalletOuterClass.GetMnemonicResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicResponse buildPartial() { pactus.WalletOuterClass.GetMnemonicResponse result = new pactus.WalletOuterClass.GetMnemonicResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetMnemonicResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.mnemonic_ = mnemonic_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetMnemonicResponse) { return mergeFrom((pactus.WalletOuterClass.GetMnemonicResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetMnemonicResponse other) { if (other == pactus.WalletOuterClass.GetMnemonicResponse.getDefaultInstance()) return this; if (!other.getMnemonic().isEmpty()) { mnemonic_ = other.mnemonic_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { mnemonic_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object mnemonic_ = ""; /** *
       * The mnemonic (seed phrase).
       * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return The mnemonic. */ public java.lang.String getMnemonic() { java.lang.Object ref = mnemonic_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mnemonic_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The mnemonic (seed phrase).
       * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return The bytes for mnemonic. */ public com.google.protobuf.ByteString getMnemonicBytes() { java.lang.Object ref = mnemonic_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); mnemonic_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The mnemonic (seed phrase).
       * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @param value The mnemonic to set. * @return This builder for chaining. */ public Builder setMnemonic( java.lang.String value) { if (value == null) { throw new NullPointerException(); } mnemonic_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The mnemonic (seed phrase).
       * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @return This builder for chaining. */ public Builder clearMnemonic() { mnemonic_ = getDefaultInstance().getMnemonic(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The mnemonic (seed phrase).
       * 
* * string mnemonic = 1 [json_name = "mnemonic"]; * @param value The bytes for mnemonic to set. * @return This builder for chaining. */ public Builder setMnemonicBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); mnemonic_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetMnemonicResponse) } // @@protoc_insertion_point(class_scope:pactus.GetMnemonicResponse) private static final pactus.WalletOuterClass.GetMnemonicResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetMnemonicResponse(); } public static pactus.WalletOuterClass.GetMnemonicResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetMnemonicResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetMnemonicResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetPrivateKeyRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetPrivateKeyRequest) com.google.protobuf.MessageOrBuilder { /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ java.lang.String getWalletName(); /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ com.google.protobuf.ByteString getWalletNameBytes(); /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ java.lang.String getPassword(); /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ com.google.protobuf.ByteString getPasswordBytes(); /** *
     * The address to get the private key.
     * 
* * string address = 3 [json_name = "address"]; * @return The address. */ java.lang.String getAddress(); /** *
     * The address to get the private key.
     * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ com.google.protobuf.ByteString getAddressBytes(); } /** *
   * Request message for getting private key.
   * 
* * Protobuf type {@code pactus.GetPrivateKeyRequest} */ public static final class GetPrivateKeyRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetPrivateKeyRequest) GetPrivateKeyRequestOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetPrivateKeyRequest"); } // Use GetPrivateKeyRequest.newBuilder() to construct. private GetPrivateKeyRequest(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetPrivateKeyRequest() { walletName_ = ""; password_ = ""; address_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetPrivateKeyRequest.class, pactus.WalletOuterClass.GetPrivateKeyRequest.Builder.class); } public static final int WALLET_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object walletName_ = ""; /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ @java.lang.Override public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } } /** *
     * The name of the wallet containing the address.
     * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ @java.lang.Override public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PASSWORD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** *
     * Wallet password.
     * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ADDRESS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object address_ = ""; /** *
     * The address to get the private key.
     * 
* * string address = 3 [json_name = "address"]; * @return The address. */ @java.lang.Override public java.lang.String getAddress() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } } /** *
     * The address to get the private key.
     * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ @java.lang.Override public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessage.writeString(output, 2, password_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { com.google.protobuf.GeneratedMessage.writeString(output, 3, address_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(walletName_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, walletName_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(2, password_); } if (!com.google.protobuf.GeneratedMessage.isStringEmpty(address_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(3, address_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetPrivateKeyRequest)) { return super.equals(obj); } pactus.WalletOuterClass.GetPrivateKeyRequest other = (pactus.WalletOuterClass.GetPrivateKeyRequest) obj; if (!getWalletName() .equals(other.getWalletName())) return false; if (!getPassword() .equals(other.getPassword())) return false; if (!getAddress() .equals(other.getAddress())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + WALLET_NAME_FIELD_NUMBER; hash = (53 * hash) + getWalletName().hashCode(); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetPrivateKeyRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetPrivateKeyRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Request message for getting private key.
     * 
* * Protobuf type {@code pactus.GetPrivateKeyRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetPrivateKeyRequest) pactus.WalletOuterClass.GetPrivateKeyRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetPrivateKeyRequest.class, pactus.WalletOuterClass.GetPrivateKeyRequest.Builder.class); } // Construct using pactus.WalletOuterClass.GetPrivateKeyRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; walletName_ = ""; password_ = ""; address_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyRequest_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyRequest getDefaultInstanceForType() { return pactus.WalletOuterClass.GetPrivateKeyRequest.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyRequest build() { pactus.WalletOuterClass.GetPrivateKeyRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyRequest buildPartial() { pactus.WalletOuterClass.GetPrivateKeyRequest result = new pactus.WalletOuterClass.GetPrivateKeyRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetPrivateKeyRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.walletName_ = walletName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.password_ = password_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.address_ = address_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetPrivateKeyRequest) { return mergeFrom((pactus.WalletOuterClass.GetPrivateKeyRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetPrivateKeyRequest other) { if (other == pactus.WalletOuterClass.GetPrivateKeyRequest.getDefaultInstance()) return this; if (!other.getWalletName().isEmpty()) { walletName_ = other.walletName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAddress().isEmpty()) { address_ = other.address_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { walletName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { address_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object walletName_ = ""; /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The walletName. */ public java.lang.String getWalletName() { java.lang.Object ref = walletName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); walletName_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return The bytes for walletName. */ public com.google.protobuf.ByteString getWalletNameBytes() { java.lang.Object ref = walletName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); walletName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The walletName to set. * @return This builder for chaining. */ public Builder setWalletName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @return This builder for chaining. */ public Builder clearWalletName() { walletName_ = getDefaultInstance().getWalletName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The name of the wallet containing the address.
       * 
* * string wallet_name = 1 [json_name = "walletName"]; * @param value The bytes for walletName to set. * @return This builder for chaining. */ public Builder setWalletNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); walletName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object password_ = ""; /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword( java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** *
       * Wallet password.
       * 
* * string password = 2 [json_name = "password"]; * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object address_ = ""; /** *
       * The address to get the private key.
       * 
* * string address = 3 [json_name = "address"]; * @return The address. */ public java.lang.String getAddress() { java.lang.Object ref = address_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); address_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The address to get the private key.
       * 
* * string address = 3 [json_name = "address"]; * @return The bytes for address. */ public com.google.protobuf.ByteString getAddressBytes() { java.lang.Object ref = address_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); address_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The address to get the private key.
       * 
* * string address = 3 [json_name = "address"]; * @param value The address to set. * @return This builder for chaining. */ public Builder setAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } address_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** *
       * The address to get the private key.
       * 
* * string address = 3 [json_name = "address"]; * @return This builder for chaining. */ public Builder clearAddress() { address_ = getDefaultInstance().getAddress(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** *
       * The address to get the private key.
       * 
* * string address = 3 [json_name = "address"]; * @param value The bytes for address to set. * @return This builder for chaining. */ public Builder setAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); address_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetPrivateKeyRequest) } // @@protoc_insertion_point(class_scope:pactus.GetPrivateKeyRequest) private static final pactus.WalletOuterClass.GetPrivateKeyRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetPrivateKeyRequest(); } public static pactus.WalletOuterClass.GetPrivateKeyRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetPrivateKeyRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface GetPrivateKeyResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:pactus.GetPrivateKeyResponse) com.google.protobuf.MessageOrBuilder { /** *
     * The private key in hexadecimal format.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The privateKey. */ java.lang.String getPrivateKey(); /** *
     * The private key in hexadecimal format.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The bytes for privateKey. */ com.google.protobuf.ByteString getPrivateKeyBytes(); } /** *
   * Response message contains private key.
   * 
* * Protobuf type {@code pactus.GetPrivateKeyResponse} */ public static final class GetPrivateKeyResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:pactus.GetPrivateKeyResponse) GetPrivateKeyResponseOrBuilder { private static final long serialVersionUID = 0L; static { com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion( com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 33, /* patch= */ 2, /* suffix= */ "", "GetPrivateKeyResponse"); } // Use GetPrivateKeyResponse.newBuilder() to construct. private GetPrivateKeyResponse(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } private GetPrivateKeyResponse() { privateKey_ = ""; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetPrivateKeyResponse.class, pactus.WalletOuterClass.GetPrivateKeyResponse.Builder.class); } public static final int PRIVATE_KEY_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object privateKey_ = ""; /** *
     * The private key in hexadecimal format.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The privateKey. */ @java.lang.Override public java.lang.String getPrivateKey() { java.lang.Object ref = privateKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); privateKey_ = s; return s; } } /** *
     * The private key in hexadecimal format.
     * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The bytes for privateKey. */ @java.lang.Override public com.google.protobuf.ByteString getPrivateKeyBytes() { java.lang.Object ref = privateKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); privateKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessage.isStringEmpty(privateKey_)) { com.google.protobuf.GeneratedMessage.writeString(output, 1, privateKey_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessage.isStringEmpty(privateKey_)) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, privateKey_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pactus.WalletOuterClass.GetPrivateKeyResponse)) { return super.equals(obj); } pactus.WalletOuterClass.GetPrivateKeyResponse other = (pactus.WalletOuterClass.GetPrivateKeyResponse) obj; if (!getPrivateKey() .equals(other.getPrivateKey())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PRIVATE_KEY_FIELD_NUMBER; hash = (53 * hash) + getPrivateKey().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static pactus.WalletOuterClass.GetPrivateKeyResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pactus.WalletOuterClass.GetPrivateKeyResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * Response message contains private key.
     * 
* * Protobuf type {@code pactus.GetPrivateKeyResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:pactus.GetPrivateKeyResponse) pactus.WalletOuterClass.GetPrivateKeyResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( pactus.WalletOuterClass.GetPrivateKeyResponse.class, pactus.WalletOuterClass.GetPrivateKeyResponse.Builder.class); } // Construct using pactus.WalletOuterClass.GetPrivateKeyResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; privateKey_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pactus.WalletOuterClass.internal_static_pactus_GetPrivateKeyResponse_descriptor; } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyResponse getDefaultInstanceForType() { return pactus.WalletOuterClass.GetPrivateKeyResponse.getDefaultInstance(); } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyResponse build() { pactus.WalletOuterClass.GetPrivateKeyResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyResponse buildPartial() { pactus.WalletOuterClass.GetPrivateKeyResponse result = new pactus.WalletOuterClass.GetPrivateKeyResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(pactus.WalletOuterClass.GetPrivateKeyResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.privateKey_ = privateKey_; } } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pactus.WalletOuterClass.GetPrivateKeyResponse) { return mergeFrom((pactus.WalletOuterClass.GetPrivateKeyResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pactus.WalletOuterClass.GetPrivateKeyResponse other) { if (other == pactus.WalletOuterClass.GetPrivateKeyResponse.getDefaultInstance()) return this; if (!other.getPrivateKey().isEmpty()) { privateKey_ = other.privateKey_; bitField0_ |= 0x00000001; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { privateKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object privateKey_ = ""; /** *
       * The private key in hexadecimal format.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The privateKey. */ public java.lang.String getPrivateKey() { java.lang.Object ref = privateKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); privateKey_ = s; return s; } else { return (java.lang.String) ref; } } /** *
       * The private key in hexadecimal format.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @return The bytes for privateKey. */ public com.google.protobuf.ByteString getPrivateKeyBytes() { java.lang.Object ref = privateKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); privateKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** *
       * The private key in hexadecimal format.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @param value The privateKey to set. * @return This builder for chaining. */ public Builder setPrivateKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } privateKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** *
       * The private key in hexadecimal format.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @return This builder for chaining. */ public Builder clearPrivateKey() { privateKey_ = getDefaultInstance().getPrivateKey(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** *
       * The private key in hexadecimal format.
       * 
* * string private_key = 1 [json_name = "privateKey"]; * @param value The bytes for privateKey to set. * @return This builder for chaining. */ public Builder setPrivateKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); privateKey_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:pactus.GetPrivateKeyResponse) } // @@protoc_insertion_point(class_scope:pactus.GetPrivateKeyResponse) private static final pactus.WalletOuterClass.GetPrivateKeyResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pactus.WalletOuterClass.GetPrivateKeyResponse(); } public static pactus.WalletOuterClass.GetPrivateKeyResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public GetPrivateKeyResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public pactus.WalletOuterClass.GetPrivateKeyResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_AddressInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_AddressInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetNewAddressRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetNewAddressRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetNewAddressResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetNewAddressResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_RestoreWalletRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_RestoreWalletRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_RestoreWalletResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_RestoreWalletResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CreateWalletRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CreateWalletRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_CreateWalletResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_CreateWalletResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_LoadWalletRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_LoadWalletRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_LoadWalletResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_LoadWalletResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_UnloadWalletRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_UnloadWalletRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_UnloadWalletResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_UnloadWalletResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorAddressRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorAddressRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetValidatorAddressResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetValidatorAddressResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignRawTransactionRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignRawTransactionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignRawTransactionResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignRawTransactionResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTotalBalanceRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTotalBalanceRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTotalBalanceResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTotalBalanceResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignMessageRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignMessageRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SignMessageResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SignMessageResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTotalStakeRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTotalStakeRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetTotalStakeResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetTotalStakeResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetAddressInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetAddressInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetAddressInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetAddressInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SetAddressLabelRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SetAddressLabelRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SetAddressLabelResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SetAddressLabelResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListWalletsRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListWalletsRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListWalletsResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListWalletsResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetWalletInfoRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetWalletInfoRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetWalletInfoResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetWalletInfoResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListAddressesRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListAddressesRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListAddressesResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListAddressesResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_UpdatePasswordRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_UpdatePasswordRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_UpdatePasswordResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_UpdatePasswordResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_WalletTransactionInfo_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_WalletTransactionInfo_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListTransactionsRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListTransactionsRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_ListTransactionsResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_ListTransactionsResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SetDefaultFeeRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SetDefaultFeeRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_SetDefaultFeeResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_SetDefaultFeeResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetMnemonicRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetMnemonicRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetMnemonicResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetMnemonicResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetPrivateKeyRequest_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetPrivateKeyRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_pactus_GetPrivateKeyResponse_descriptor; private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_pactus_GetPrivateKeyResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\014wallet.proto\022\006pactus\032\021transaction.prot" + "o\"p\n\013AddressInfo\022\030\n\007address\030\001 \001(\tR\007addre" + "ss\022\035\n\npublic_key\030\002 \001(\tR\tpublicKey\022\024\n\005lab" + "el\030\003 \001(\tR\005label\022\022\n\004path\030\004 \001(\tR\004path\"\241\001\n\024" + "GetNewAddressRequest\022\037\n\013wallet_name\030\001 \001(" + "\tR\nwalletName\0226\n\014address_type\030\002 \001(\0162\023.pa" + "ctus.AddressTypeR\013addressType\022\024\n\005label\030\003" + " \001(\tR\005label\022\032\n\010password\030\004 \001(\tR\010password\"" + "a\n\025GetNewAddressResponse\022\037\n\013wallet_name\030" + "\001 \001(\tR\nwalletName\022\'\n\004addr\030\002 \001(\0132\023.pactus" + ".AddressInfoR\004addr\"o\n\024RestoreWalletReque" + "st\022\037\n\013wallet_name\030\001 \001(\tR\nwalletName\022\032\n\010m" + "nemonic\030\002 \001(\tR\010mnemonic\022\032\n\010password\030\003 \001(" + "\tR\010password\"8\n\025RestoreWalletResponse\022\037\n\013" + "wallet_name\030\001 \001(\tR\nwalletName\"R\n\023CreateW" + "alletRequest\022\037\n\013wallet_name\030\001 \001(\tR\nwalle" + "tName\022\032\n\010password\030\002 \001(\tR\010password\"S\n\024Cre" + "ateWalletResponse\022\037\n\013wallet_name\030\001 \001(\tR\n" + "walletName\022\032\n\010mnemonic\030\002 \001(\tR\010mnemonic\"4" + "\n\021LoadWalletRequest\022\037\n\013wallet_name\030\001 \001(\t" + "R\nwalletName\"5\n\022LoadWalletResponse\022\037\n\013wa" + "llet_name\030\001 \001(\tR\nwalletName\"6\n\023UnloadWal" + "letRequest\022\037\n\013wallet_name\030\001 \001(\tR\nwalletN" + "ame\"7\n\024UnloadWalletResponse\022\037\n\013wallet_na" + "me\030\001 \001(\tR\nwalletName\";\n\032GetValidatorAddr" + "essRequest\022\035\n\npublic_key\030\001 \001(\tR\tpublicKe" + "y\"7\n\033GetValidatorAddressResponse\022\030\n\007addr" + "ess\030\001 \001(\tR\007address\"\201\001\n\031SignRawTransactio" + "nRequest\022\037\n\013wallet_name\030\001 \001(\tR\nwalletNam" + "e\022\'\n\017raw_transaction\030\002 \001(\tR\016rawTransacti" + "on\022\032\n\010password\030\003 \001(\tR\010password\"y\n\032SignRa" + "wTransactionResponse\022%\n\016transaction_id\030\001" + " \001(\tR\rtransactionId\0224\n\026signed_raw_transa" + "ction\030\002 \001(\tR\024signedRawTransaction\"9\n\026Get" + "TotalBalanceRequest\022\037\n\013wallet_name\030\001 \001(\t" + "R\nwalletName\"_\n\027GetTotalBalanceResponse\022" + "\037\n\013wallet_name\030\001 \001(\tR\nwalletName\022#\n\rtota" + "l_balance\030\002 \001(\003R\014totalBalance\"\205\001\n\022SignMe" + "ssageRequest\022\037\n\013wallet_name\030\001 \001(\tR\nwalle" + "tName\022\032\n\010password\030\002 \001(\tR\010password\022\030\n\007add" + "ress\030\003 \001(\tR\007address\022\030\n\007message\030\004 \001(\tR\007me" + "ssage\"3\n\023SignMessageResponse\022\034\n\tsignatur" + "e\030\001 \001(\tR\tsignature\"7\n\024GetTotalStakeReque" + "st\022\037\n\013wallet_name\030\001 \001(\tR\nwalletName\"Y\n\025G" + "etTotalStakeResponse\022\037\n\013wallet_name\030\001 \001(" + "\tR\nwalletName\022\037\n\013total_stake\030\002 \001(\003R\ntota" + "lStake\"R\n\025GetAddressInfoRequest\022\037\n\013walle" + "t_name\030\001 \001(\tR\nwalletName\022\030\n\007address\030\002 \001(" + "\tR\007address\"b\n\026GetAddressInfoResponse\022\037\n\013" + "wallet_name\030\001 \001(\tR\nwalletName\022\'\n\004addr\030\002 " + "\001(\0132\023.pactus.AddressInfoR\004addr\"\205\001\n\026SetAd" + "dressLabelRequest\022\037\n\013wallet_name\030\001 \001(\tR\n" + "walletName\022\032\n\010password\030\002 \001(\tR\010password\022\030" + "\n\007address\030\003 \001(\tR\007address\022\024\n\005label\030\004 \001(\tR" + "\005label\"j\n\027SetAddressLabelResponse\022\037\n\013wal" + "let_name\030\001 \001(\tR\nwalletName\022\030\n\007address\030\002 " + "\001(\tR\007address\022\024\n\005label\030\003 \001(\tR\005label\"\024\n\022Li" + "stWalletsRequest\"/\n\023ListWalletsResponse\022" + "\030\n\007wallets\030\001 \003(\tR\007wallets\"7\n\024GetWalletIn" + "foRequest\022\037\n\013wallet_name\030\001 \001(\tR\nwalletNa" + "me\"\212\002\n\025GetWalletInfoResponse\022\037\n\013wallet_n" + "ame\030\001 \001(\tR\nwalletName\022\030\n\007version\030\002 \001(\005R\007" + "version\022\030\n\007network\030\003 \001(\tR\007network\022\034\n\tenc" + "rypted\030\004 \001(\010R\tencrypted\022\022\n\004uuid\030\005 \001(\tR\004u" + "uid\022\035\n\ncreated_at\030\006 \001(\003R\tcreatedAt\022\037\n\013de" + "fault_fee\030\007 \001(\003R\ndefaultFee\022\026\n\006driver\030\010 " + "\001(\tR\006driver\022\022\n\004path\030\t \001(\tR\004path\"q\n\024ListA" + "ddressesRequest\022\037\n\013wallet_name\030\001 \001(\tR\nwa" + "lletName\0228\n\raddress_types\030\002 \003(\0162\023.pactus" + ".AddressTypeR\014addressTypes\"c\n\025ListAddres" + "sesResponse\022\037\n\013wallet_name\030\001 \001(\tR\nwallet" + "Name\022)\n\005addrs\030\002 \003(\0132\023.pactus.AddressInfo" + "R\005addrs\"~\n\025UpdatePasswordRequest\022\037\n\013wall" + "et_name\030\001 \001(\tR\nwalletName\022!\n\014old_passwor" + "d\030\002 \001(\tR\013oldPassword\022!\n\014new_password\030\003 \001" + "(\tR\013newPassword\"9\n\026UpdatePasswordRespons" + "e\022\037\n\013wallet_name\030\001 \001(\tR\nwalletName\"\333\003\n\025W" + "alletTransactionInfo\022\016\n\002no\030\001 \001(\003R\002no\022\023\n\005" + "tx_id\030\002 \001(\tR\004txId\022\026\n\006sender\030\003 \001(\tR\006sende" + "r\022\032\n\010receiver\030\004 \001(\tR\010receiver\0221\n\tdirecti" + "on\030\005 \001(\0162\023.pactus.TxDirectionR\tdirection" + "\022\026\n\006amount\030\006 \001(\003R\006amount\022\020\n\003fee\030\007 \001(\003R\003f" + "ee\022\022\n\004memo\030\010 \001(\tR\004memo\0221\n\006status\030\t \001(\0162\031" + ".pactus.TransactionStatusR\006status\022!\n\014blo" + "ck_height\030\n \001(\rR\013blockHeight\0226\n\014payload_" + "type\030\013 \001(\0162\023.pactus.PayloadTypeR\013payload" + "Type\022\022\n\004data\030\014 \001(\014R\004data\022\030\n\007comment\030\r \001(" + "\tR\007comment\022\035\n\ncreated_at\030\016 \001(\003R\tcreatedA" + "t\022\035\n\nupdated_at\030\017 \001(\003R\tupdatedAt\"\261\001\n\027Lis" + "tTransactionsRequest\022\037\n\013wallet_name\030\001 \001(" + "\tR\nwalletName\022\030\n\007address\030\002 \001(\tR\007address\022" + "1\n\tdirection\030\003 \001(\0162\023.pactus.TxDirectionR" + "\tdirection\022\024\n\005count\030\004 \001(\005R\005count\022\022\n\004skip" + "\030\005 \001(\005R\004skip\"l\n\030ListTransactionsResponse" + "\022\037\n\013wallet_name\030\001 \001(\tR\nwalletName\022/\n\003txs" + "\030\002 \003(\0132\035.pactus.WalletTransactionInfoR\003t" + "xs\"O\n\024SetDefaultFeeRequest\022\037\n\013wallet_nam" + "e\030\001 \001(\tR\nwalletName\022\026\n\006amount\030\002 \001(\003R\006amo" + "unt\"8\n\025SetDefaultFeeResponse\022\037\n\013wallet_n" + "ame\030\001 \001(\tR\nwalletName\"Q\n\022GetMnemonicRequ" + "est\022\037\n\013wallet_name\030\001 \001(\tR\nwalletName\022\032\n\010" + "password\030\002 \001(\tR\010password\"1\n\023GetMnemonicR" + "esponse\022\032\n\010mnemonic\030\001 \001(\tR\010mnemonic\"m\n\024G" + "etPrivateKeyRequest\022\037\n\013wallet_name\030\001 \001(\t" + "R\nwalletName\022\032\n\010password\030\002 \001(\tR\010password" + "\022\030\n\007address\030\003 \001(\tR\007address\"8\n\025GetPrivate" + "KeyResponse\022\037\n\013private_key\030\001 \001(\tR\nprivat" + "eKey*\204\001\n\013AddressType\022\031\n\025ADDRESS_TYPE_TRE" + "ASURY\020\000\022\032\n\026ADDRESS_TYPE_VALIDATOR\020\001\022\034\n\030A" + "DDRESS_TYPE_BLS_ACCOUNT\020\002\022 \n\034ADDRESS_TYP" + "E_ED25519_ACCOUNT\020\003*Y\n\013TxDirection\022\024\n\020TX" + "_DIRECTION_ANY\020\000\022\031\n\025TX_DIRECTION_INCOMIN" + "G\020\001\022\031\n\025TX_DIRECTION_OUTGOING\020\002*}\n\021Transa" + "ctionStatus\022\036\n\032TRANSACTION_STATUS_PENDIN" + "G\020\000\022 \n\034TRANSACTION_STATUS_CONFIRMED\020\001\022&\n" + "\031TRANSACTION_STATUS_FAILED\020\377\377\377\377\377\377\377\377\377\0012\273\014" + "\n\006Wallet\022I\n\014CreateWallet\022\033.pactus.Create" + "WalletRequest\032\034.pactus.CreateWalletRespo" + "nse\022L\n\rRestoreWallet\022\034.pactus.RestoreWal" + "letRequest\032\035.pactus.RestoreWalletRespons" + "e\022C\n\nLoadWallet\022\031.pactus.LoadWalletReque" + "st\032\032.pactus.LoadWalletResponse\022I\n\014Unload" + "Wallet\022\033.pactus.UnloadWalletRequest\032\034.pa" + "ctus.UnloadWalletResponse\022F\n\013ListWallets" + "\022\032.pactus.ListWalletsRequest\032\033.pactus.Li" + "stWalletsResponse\022L\n\rGetWalletInfo\022\034.pac" + "tus.GetWalletInfoRequest\032\035.pactus.GetWal" + "letInfoResponse\022O\n\016UpdatePassword\022\035.pact" + "us.UpdatePasswordRequest\032\036.pactus.Update" + "PasswordResponse\022R\n\017GetTotalBalance\022\036.pa" + "ctus.GetTotalBalanceRequest\032\037.pactus.Get" + "TotalBalanceResponse\022L\n\rGetTotalStake\022\034." + "pactus.GetTotalStakeRequest\032\035.pactus.Get" + "TotalStakeResponse\022^\n\023GetValidatorAddres" + "s\022\".pactus.GetValidatorAddressRequest\032#." + "pactus.GetValidatorAddressResponse\022O\n\016Ge" + "tAddressInfo\022\035.pactus.GetAddressInfoRequ" + "est\032\036.pactus.GetAddressInfoResponse\022R\n\017S" + "etAddressLabel\022\036.pactus.SetAddressLabelR" + "equest\032\037.pactus.SetAddressLabelResponse\022" + "L\n\rGetNewAddress\022\034.pactus.GetNewAddressR" + "equest\032\035.pactus.GetNewAddressResponse\022L\n" + "\rListAddresses\022\034.pactus.ListAddressesReq" + "uest\032\035.pactus.ListAddressesResponse\022F\n\013S" + "ignMessage\022\032.pactus.SignMessageRequest\032\033" + ".pactus.SignMessageResponse\022[\n\022SignRawTr" + "ansaction\022!.pactus.SignRawTransactionReq" + "uest\032\".pactus.SignRawTransactionResponse" + "\022U\n\020ListTransactions\022\037.pactus.ListTransa" + "ctionsRequest\032 .pactus.ListTransactionsR" + "esponse\022L\n\rSetDefaultFee\022\034.pactus.SetDef" + "aultFeeRequest\032\035.pactus.SetDefaultFeeRes" + "ponse\022F\n\013GetMnemonic\022\032.pactus.GetMnemoni" + "cRequest\032\033.pactus.GetMnemonicResponse\022L\n" + "\rGetPrivateKey\022\034.pactus.GetPrivateKeyReq" + "uest\032\035.pactus.GetPrivateKeyResponseB:\n\006p" + "actusZ0github.com/pactus-project/pactus/" + "www/grpc/pactusb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { pactus.TransactionOuterClass.getDescriptor(), }); internal_static_pactus_AddressInfo_descriptor = getDescriptor().getMessageType(0); internal_static_pactus_AddressInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_AddressInfo_descriptor, new java.lang.String[] { "Address", "PublicKey", "Label", "Path", }); internal_static_pactus_GetNewAddressRequest_descriptor = getDescriptor().getMessageType(1); internal_static_pactus_GetNewAddressRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetNewAddressRequest_descriptor, new java.lang.String[] { "WalletName", "AddressType", "Label", "Password", }); internal_static_pactus_GetNewAddressResponse_descriptor = getDescriptor().getMessageType(2); internal_static_pactus_GetNewAddressResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetNewAddressResponse_descriptor, new java.lang.String[] { "WalletName", "Addr", }); internal_static_pactus_RestoreWalletRequest_descriptor = getDescriptor().getMessageType(3); internal_static_pactus_RestoreWalletRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_RestoreWalletRequest_descriptor, new java.lang.String[] { "WalletName", "Mnemonic", "Password", }); internal_static_pactus_RestoreWalletResponse_descriptor = getDescriptor().getMessageType(4); internal_static_pactus_RestoreWalletResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_RestoreWalletResponse_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_CreateWalletRequest_descriptor = getDescriptor().getMessageType(5); internal_static_pactus_CreateWalletRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CreateWalletRequest_descriptor, new java.lang.String[] { "WalletName", "Password", }); internal_static_pactus_CreateWalletResponse_descriptor = getDescriptor().getMessageType(6); internal_static_pactus_CreateWalletResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_CreateWalletResponse_descriptor, new java.lang.String[] { "WalletName", "Mnemonic", }); internal_static_pactus_LoadWalletRequest_descriptor = getDescriptor().getMessageType(7); internal_static_pactus_LoadWalletRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_LoadWalletRequest_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_LoadWalletResponse_descriptor = getDescriptor().getMessageType(8); internal_static_pactus_LoadWalletResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_LoadWalletResponse_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_UnloadWalletRequest_descriptor = getDescriptor().getMessageType(9); internal_static_pactus_UnloadWalletRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_UnloadWalletRequest_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_UnloadWalletResponse_descriptor = getDescriptor().getMessageType(10); internal_static_pactus_UnloadWalletResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_UnloadWalletResponse_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_GetValidatorAddressRequest_descriptor = getDescriptor().getMessageType(11); internal_static_pactus_GetValidatorAddressRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorAddressRequest_descriptor, new java.lang.String[] { "PublicKey", }); internal_static_pactus_GetValidatorAddressResponse_descriptor = getDescriptor().getMessageType(12); internal_static_pactus_GetValidatorAddressResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetValidatorAddressResponse_descriptor, new java.lang.String[] { "Address", }); internal_static_pactus_SignRawTransactionRequest_descriptor = getDescriptor().getMessageType(13); internal_static_pactus_SignRawTransactionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignRawTransactionRequest_descriptor, new java.lang.String[] { "WalletName", "RawTransaction", "Password", }); internal_static_pactus_SignRawTransactionResponse_descriptor = getDescriptor().getMessageType(14); internal_static_pactus_SignRawTransactionResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignRawTransactionResponse_descriptor, new java.lang.String[] { "TransactionId", "SignedRawTransaction", }); internal_static_pactus_GetTotalBalanceRequest_descriptor = getDescriptor().getMessageType(15); internal_static_pactus_GetTotalBalanceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTotalBalanceRequest_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_GetTotalBalanceResponse_descriptor = getDescriptor().getMessageType(16); internal_static_pactus_GetTotalBalanceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTotalBalanceResponse_descriptor, new java.lang.String[] { "WalletName", "TotalBalance", }); internal_static_pactus_SignMessageRequest_descriptor = getDescriptor().getMessageType(17); internal_static_pactus_SignMessageRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignMessageRequest_descriptor, new java.lang.String[] { "WalletName", "Password", "Address", "Message", }); internal_static_pactus_SignMessageResponse_descriptor = getDescriptor().getMessageType(18); internal_static_pactus_SignMessageResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SignMessageResponse_descriptor, new java.lang.String[] { "Signature", }); internal_static_pactus_GetTotalStakeRequest_descriptor = getDescriptor().getMessageType(19); internal_static_pactus_GetTotalStakeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTotalStakeRequest_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_GetTotalStakeResponse_descriptor = getDescriptor().getMessageType(20); internal_static_pactus_GetTotalStakeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetTotalStakeResponse_descriptor, new java.lang.String[] { "WalletName", "TotalStake", }); internal_static_pactus_GetAddressInfoRequest_descriptor = getDescriptor().getMessageType(21); internal_static_pactus_GetAddressInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetAddressInfoRequest_descriptor, new java.lang.String[] { "WalletName", "Address", }); internal_static_pactus_GetAddressInfoResponse_descriptor = getDescriptor().getMessageType(22); internal_static_pactus_GetAddressInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetAddressInfoResponse_descriptor, new java.lang.String[] { "WalletName", "Addr", }); internal_static_pactus_SetAddressLabelRequest_descriptor = getDescriptor().getMessageType(23); internal_static_pactus_SetAddressLabelRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SetAddressLabelRequest_descriptor, new java.lang.String[] { "WalletName", "Password", "Address", "Label", }); internal_static_pactus_SetAddressLabelResponse_descriptor = getDescriptor().getMessageType(24); internal_static_pactus_SetAddressLabelResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SetAddressLabelResponse_descriptor, new java.lang.String[] { "WalletName", "Address", "Label", }); internal_static_pactus_ListWalletsRequest_descriptor = getDescriptor().getMessageType(25); internal_static_pactus_ListWalletsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListWalletsRequest_descriptor, new java.lang.String[] { }); internal_static_pactus_ListWalletsResponse_descriptor = getDescriptor().getMessageType(26); internal_static_pactus_ListWalletsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListWalletsResponse_descriptor, new java.lang.String[] { "Wallets", }); internal_static_pactus_GetWalletInfoRequest_descriptor = getDescriptor().getMessageType(27); internal_static_pactus_GetWalletInfoRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetWalletInfoRequest_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_GetWalletInfoResponse_descriptor = getDescriptor().getMessageType(28); internal_static_pactus_GetWalletInfoResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetWalletInfoResponse_descriptor, new java.lang.String[] { "WalletName", "Version", "Network", "Encrypted", "Uuid", "CreatedAt", "DefaultFee", "Driver", "Path", }); internal_static_pactus_ListAddressesRequest_descriptor = getDescriptor().getMessageType(29); internal_static_pactus_ListAddressesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListAddressesRequest_descriptor, new java.lang.String[] { "WalletName", "AddressTypes", }); internal_static_pactus_ListAddressesResponse_descriptor = getDescriptor().getMessageType(30); internal_static_pactus_ListAddressesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListAddressesResponse_descriptor, new java.lang.String[] { "WalletName", "Addrs", }); internal_static_pactus_UpdatePasswordRequest_descriptor = getDescriptor().getMessageType(31); internal_static_pactus_UpdatePasswordRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_UpdatePasswordRequest_descriptor, new java.lang.String[] { "WalletName", "OldPassword", "NewPassword", }); internal_static_pactus_UpdatePasswordResponse_descriptor = getDescriptor().getMessageType(32); internal_static_pactus_UpdatePasswordResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_UpdatePasswordResponse_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_WalletTransactionInfo_descriptor = getDescriptor().getMessageType(33); internal_static_pactus_WalletTransactionInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_WalletTransactionInfo_descriptor, new java.lang.String[] { "No", "TxId", "Sender", "Receiver", "Direction", "Amount", "Fee", "Memo", "Status", "BlockHeight", "PayloadType", "Data", "Comment", "CreatedAt", "UpdatedAt", }); internal_static_pactus_ListTransactionsRequest_descriptor = getDescriptor().getMessageType(34); internal_static_pactus_ListTransactionsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListTransactionsRequest_descriptor, new java.lang.String[] { "WalletName", "Address", "Direction", "Count", "Skip", }); internal_static_pactus_ListTransactionsResponse_descriptor = getDescriptor().getMessageType(35); internal_static_pactus_ListTransactionsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_ListTransactionsResponse_descriptor, new java.lang.String[] { "WalletName", "Txs", }); internal_static_pactus_SetDefaultFeeRequest_descriptor = getDescriptor().getMessageType(36); internal_static_pactus_SetDefaultFeeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SetDefaultFeeRequest_descriptor, new java.lang.String[] { "WalletName", "Amount", }); internal_static_pactus_SetDefaultFeeResponse_descriptor = getDescriptor().getMessageType(37); internal_static_pactus_SetDefaultFeeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_SetDefaultFeeResponse_descriptor, new java.lang.String[] { "WalletName", }); internal_static_pactus_GetMnemonicRequest_descriptor = getDescriptor().getMessageType(38); internal_static_pactus_GetMnemonicRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetMnemonicRequest_descriptor, new java.lang.String[] { "WalletName", "Password", }); internal_static_pactus_GetMnemonicResponse_descriptor = getDescriptor().getMessageType(39); internal_static_pactus_GetMnemonicResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetMnemonicResponse_descriptor, new java.lang.String[] { "Mnemonic", }); internal_static_pactus_GetPrivateKeyRequest_descriptor = getDescriptor().getMessageType(40); internal_static_pactus_GetPrivateKeyRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetPrivateKeyRequest_descriptor, new java.lang.String[] { "WalletName", "Password", "Address", }); internal_static_pactus_GetPrivateKeyResponse_descriptor = getDescriptor().getMessageType(41); internal_static_pactus_GetPrivateKeyResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_pactus_GetPrivateKeyResponse_descriptor, new java.lang.String[] { "PrivateKey", }); descriptor.resolveAllFeaturesImmutable(); pactus.TransactionOuterClass.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) } ================================================ FILE: www/grpc/gen/js/blockchain_grpc_pb.js ================================================ // GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('@grpc/grpc-js'); var blockchain_pb = require('./blockchain_pb.js'); var transaction_pb = require('./transaction_pb.js'); function serialize_pactus_GetAccountRequest(arg) { if (!(arg instanceof blockchain_pb.GetAccountRequest)) { throw new Error('Expected argument of type pactus.GetAccountRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetAccountRequest(buffer_arg) { return blockchain_pb.GetAccountRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetAccountResponse(arg) { if (!(arg instanceof blockchain_pb.GetAccountResponse)) { throw new Error('Expected argument of type pactus.GetAccountResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetAccountResponse(buffer_arg) { return blockchain_pb.GetAccountResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockHashRequest(arg) { if (!(arg instanceof blockchain_pb.GetBlockHashRequest)) { throw new Error('Expected argument of type pactus.GetBlockHashRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockHashRequest(buffer_arg) { return blockchain_pb.GetBlockHashRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockHashResponse(arg) { if (!(arg instanceof blockchain_pb.GetBlockHashResponse)) { throw new Error('Expected argument of type pactus.GetBlockHashResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockHashResponse(buffer_arg) { return blockchain_pb.GetBlockHashResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockHeightRequest(arg) { if (!(arg instanceof blockchain_pb.GetBlockHeightRequest)) { throw new Error('Expected argument of type pactus.GetBlockHeightRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockHeightRequest(buffer_arg) { return blockchain_pb.GetBlockHeightRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockHeightResponse(arg) { if (!(arg instanceof blockchain_pb.GetBlockHeightResponse)) { throw new Error('Expected argument of type pactus.GetBlockHeightResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockHeightResponse(buffer_arg) { return blockchain_pb.GetBlockHeightResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockRequest(arg) { if (!(arg instanceof blockchain_pb.GetBlockRequest)) { throw new Error('Expected argument of type pactus.GetBlockRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockRequest(buffer_arg) { return blockchain_pb.GetBlockRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockResponse(arg) { if (!(arg instanceof blockchain_pb.GetBlockResponse)) { throw new Error('Expected argument of type pactus.GetBlockResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockResponse(buffer_arg) { return blockchain_pb.GetBlockResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockchainInfoRequest(arg) { if (!(arg instanceof blockchain_pb.GetBlockchainInfoRequest)) { throw new Error('Expected argument of type pactus.GetBlockchainInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockchainInfoRequest(buffer_arg) { return blockchain_pb.GetBlockchainInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetBlockchainInfoResponse(arg) { if (!(arg instanceof blockchain_pb.GetBlockchainInfoResponse)) { throw new Error('Expected argument of type pactus.GetBlockchainInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetBlockchainInfoResponse(buffer_arg) { return blockchain_pb.GetBlockchainInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetCommitteeInfoRequest(arg) { if (!(arg instanceof blockchain_pb.GetCommitteeInfoRequest)) { throw new Error('Expected argument of type pactus.GetCommitteeInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetCommitteeInfoRequest(buffer_arg) { return blockchain_pb.GetCommitteeInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetCommitteeInfoResponse(arg) { if (!(arg instanceof blockchain_pb.GetCommitteeInfoResponse)) { throw new Error('Expected argument of type pactus.GetCommitteeInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetCommitteeInfoResponse(buffer_arg) { return blockchain_pb.GetCommitteeInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetConsensusInfoRequest(arg) { if (!(arg instanceof blockchain_pb.GetConsensusInfoRequest)) { throw new Error('Expected argument of type pactus.GetConsensusInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetConsensusInfoRequest(buffer_arg) { return blockchain_pb.GetConsensusInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetConsensusInfoResponse(arg) { if (!(arg instanceof blockchain_pb.GetConsensusInfoResponse)) { throw new Error('Expected argument of type pactus.GetConsensusInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetConsensusInfoResponse(buffer_arg) { return blockchain_pb.GetConsensusInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetPublicKeyRequest(arg) { if (!(arg instanceof blockchain_pb.GetPublicKeyRequest)) { throw new Error('Expected argument of type pactus.GetPublicKeyRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetPublicKeyRequest(buffer_arg) { return blockchain_pb.GetPublicKeyRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetPublicKeyResponse(arg) { if (!(arg instanceof blockchain_pb.GetPublicKeyResponse)) { throw new Error('Expected argument of type pactus.GetPublicKeyResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetPublicKeyResponse(buffer_arg) { return blockchain_pb.GetPublicKeyResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTxPoolContentRequest(arg) { if (!(arg instanceof blockchain_pb.GetTxPoolContentRequest)) { throw new Error('Expected argument of type pactus.GetTxPoolContentRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTxPoolContentRequest(buffer_arg) { return blockchain_pb.GetTxPoolContentRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTxPoolContentResponse(arg) { if (!(arg instanceof blockchain_pb.GetTxPoolContentResponse)) { throw new Error('Expected argument of type pactus.GetTxPoolContentResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTxPoolContentResponse(buffer_arg) { return blockchain_pb.GetTxPoolContentResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorAddressesRequest(arg) { if (!(arg instanceof blockchain_pb.GetValidatorAddressesRequest)) { throw new Error('Expected argument of type pactus.GetValidatorAddressesRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorAddressesRequest(buffer_arg) { return blockchain_pb.GetValidatorAddressesRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorAddressesResponse(arg) { if (!(arg instanceof blockchain_pb.GetValidatorAddressesResponse)) { throw new Error('Expected argument of type pactus.GetValidatorAddressesResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorAddressesResponse(buffer_arg) { return blockchain_pb.GetValidatorAddressesResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorByNumberRequest(arg) { if (!(arg instanceof blockchain_pb.GetValidatorByNumberRequest)) { throw new Error('Expected argument of type pactus.GetValidatorByNumberRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorByNumberRequest(buffer_arg) { return blockchain_pb.GetValidatorByNumberRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorRequest(arg) { if (!(arg instanceof blockchain_pb.GetValidatorRequest)) { throw new Error('Expected argument of type pactus.GetValidatorRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorRequest(buffer_arg) { return blockchain_pb.GetValidatorRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorResponse(arg) { if (!(arg instanceof blockchain_pb.GetValidatorResponse)) { throw new Error('Expected argument of type pactus.GetValidatorResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorResponse(buffer_arg) { return blockchain_pb.GetValidatorResponse.deserializeBinary(new Uint8Array(buffer_arg)); } // Blockchain service defines RPC methods for interacting with the blockchain. var BlockchainService = exports.BlockchainService = { // GetBlock retrieves information about a block based on the provided request parameters. getBlock: { path: '/pactus.Blockchain/GetBlock', requestStream: false, responseStream: false, requestType: blockchain_pb.GetBlockRequest, responseType: blockchain_pb.GetBlockResponse, requestSerialize: serialize_pactus_GetBlockRequest, requestDeserialize: deserialize_pactus_GetBlockRequest, responseSerialize: serialize_pactus_GetBlockResponse, responseDeserialize: deserialize_pactus_GetBlockResponse, }, // GetBlockHash retrieves the hash of a block at the specified height. getBlockHash: { path: '/pactus.Blockchain/GetBlockHash', requestStream: false, responseStream: false, requestType: blockchain_pb.GetBlockHashRequest, responseType: blockchain_pb.GetBlockHashResponse, requestSerialize: serialize_pactus_GetBlockHashRequest, requestDeserialize: deserialize_pactus_GetBlockHashRequest, responseSerialize: serialize_pactus_GetBlockHashResponse, responseDeserialize: deserialize_pactus_GetBlockHashResponse, }, // GetBlockHeight retrieves the height of a block with the specified hash. getBlockHeight: { path: '/pactus.Blockchain/GetBlockHeight', requestStream: false, responseStream: false, requestType: blockchain_pb.GetBlockHeightRequest, responseType: blockchain_pb.GetBlockHeightResponse, requestSerialize: serialize_pactus_GetBlockHeightRequest, requestDeserialize: deserialize_pactus_GetBlockHeightRequest, responseSerialize: serialize_pactus_GetBlockHeightResponse, responseDeserialize: deserialize_pactus_GetBlockHeightResponse, }, // GetBlockchainInfo retrieves general information about the blockchain. getBlockchainInfo: { path: '/pactus.Blockchain/GetBlockchainInfo', requestStream: false, responseStream: false, requestType: blockchain_pb.GetBlockchainInfoRequest, responseType: blockchain_pb.GetBlockchainInfoResponse, requestSerialize: serialize_pactus_GetBlockchainInfoRequest, requestDeserialize: deserialize_pactus_GetBlockchainInfoRequest, responseSerialize: serialize_pactus_GetBlockchainInfoResponse, responseDeserialize: deserialize_pactus_GetBlockchainInfoResponse, }, // GetCommitteeInfo retrieves information about the current committee. getCommitteeInfo: { path: '/pactus.Blockchain/GetCommitteeInfo', requestStream: false, responseStream: false, requestType: blockchain_pb.GetCommitteeInfoRequest, responseType: blockchain_pb.GetCommitteeInfoResponse, requestSerialize: serialize_pactus_GetCommitteeInfoRequest, requestDeserialize: deserialize_pactus_GetCommitteeInfoRequest, responseSerialize: serialize_pactus_GetCommitteeInfoResponse, responseDeserialize: deserialize_pactus_GetCommitteeInfoResponse, }, // GetConsensusInfo retrieves information about the consensus instances. getConsensusInfo: { path: '/pactus.Blockchain/GetConsensusInfo', requestStream: false, responseStream: false, requestType: blockchain_pb.GetConsensusInfoRequest, responseType: blockchain_pb.GetConsensusInfoResponse, requestSerialize: serialize_pactus_GetConsensusInfoRequest, requestDeserialize: deserialize_pactus_GetConsensusInfoRequest, responseSerialize: serialize_pactus_GetConsensusInfoResponse, responseDeserialize: deserialize_pactus_GetConsensusInfoResponse, }, // GetAccount retrieves information about an account based on the provided address. getAccount: { path: '/pactus.Blockchain/GetAccount', requestStream: false, responseStream: false, requestType: blockchain_pb.GetAccountRequest, responseType: blockchain_pb.GetAccountResponse, requestSerialize: serialize_pactus_GetAccountRequest, requestDeserialize: deserialize_pactus_GetAccountRequest, responseSerialize: serialize_pactus_GetAccountResponse, responseDeserialize: deserialize_pactus_GetAccountResponse, }, // GetValidator retrieves information about a validator based on the provided address. getValidator: { path: '/pactus.Blockchain/GetValidator', requestStream: false, responseStream: false, requestType: blockchain_pb.GetValidatorRequest, responseType: blockchain_pb.GetValidatorResponse, requestSerialize: serialize_pactus_GetValidatorRequest, requestDeserialize: deserialize_pactus_GetValidatorRequest, responseSerialize: serialize_pactus_GetValidatorResponse, responseDeserialize: deserialize_pactus_GetValidatorResponse, }, // GetValidatorByNumber retrieves information about a validator based on the provided number. getValidatorByNumber: { path: '/pactus.Blockchain/GetValidatorByNumber', requestStream: false, responseStream: false, requestType: blockchain_pb.GetValidatorByNumberRequest, responseType: blockchain_pb.GetValidatorResponse, requestSerialize: serialize_pactus_GetValidatorByNumberRequest, requestDeserialize: deserialize_pactus_GetValidatorByNumberRequest, responseSerialize: serialize_pactus_GetValidatorResponse, responseDeserialize: deserialize_pactus_GetValidatorResponse, }, // GetValidatorAddresses retrieves a list of all validator addresses. getValidatorAddresses: { path: '/pactus.Blockchain/GetValidatorAddresses', requestStream: false, responseStream: false, requestType: blockchain_pb.GetValidatorAddressesRequest, responseType: blockchain_pb.GetValidatorAddressesResponse, requestSerialize: serialize_pactus_GetValidatorAddressesRequest, requestDeserialize: deserialize_pactus_GetValidatorAddressesRequest, responseSerialize: serialize_pactus_GetValidatorAddressesResponse, responseDeserialize: deserialize_pactus_GetValidatorAddressesResponse, }, // GetPublicKey retrieves the public key of an account based on the provided address. getPublicKey: { path: '/pactus.Blockchain/GetPublicKey', requestStream: false, responseStream: false, requestType: blockchain_pb.GetPublicKeyRequest, responseType: blockchain_pb.GetPublicKeyResponse, requestSerialize: serialize_pactus_GetPublicKeyRequest, requestDeserialize: deserialize_pactus_GetPublicKeyRequest, responseSerialize: serialize_pactus_GetPublicKeyResponse, responseDeserialize: deserialize_pactus_GetPublicKeyResponse, }, // GetTxPoolContent retrieves current transactions in the transaction pool. getTxPoolContent: { path: '/pactus.Blockchain/GetTxPoolContent', requestStream: false, responseStream: false, requestType: blockchain_pb.GetTxPoolContentRequest, responseType: blockchain_pb.GetTxPoolContentResponse, requestSerialize: serialize_pactus_GetTxPoolContentRequest, requestDeserialize: deserialize_pactus_GetTxPoolContentRequest, responseSerialize: serialize_pactus_GetTxPoolContentResponse, responseDeserialize: deserialize_pactus_GetTxPoolContentResponse, }, }; exports.BlockchainClient = grpc.makeGenericClientConstructor(BlockchainService, 'Blockchain'); ================================================ FILE: www/grpc/gen/js/blockchain_grpc_web_pb.js ================================================ /** * @fileoverview gRPC-Web generated client stub for pactus * @enhanceable * @public */ // Code generated by protoc-gen-grpc-web. DO NOT EDIT. // versions: // protoc-gen-grpc-web v2.0.2 // protoc v0.0.0 // source: blockchain.proto /* eslint-disable */ // @ts-nocheck const grpc = {}; grpc.web = require('grpc-web'); var transaction_pb = require('./transaction_pb.js') const proto = {}; proto.pactus = require('./blockchain_pb.js'); /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.BlockchainClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.BlockchainPromiseClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetBlockRequest, * !proto.pactus.GetBlockResponse>} */ const methodDescriptor_Blockchain_GetBlock = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetBlock', grpc.web.MethodType.UNARY, proto.pactus.GetBlockRequest, proto.pactus.GetBlockResponse, /** * @param {!proto.pactus.GetBlockRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetBlockResponse.deserializeBinary ); /** * @param {!proto.pactus.GetBlockRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetBlockResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getBlock = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetBlock', request, metadata || {}, methodDescriptor_Blockchain_GetBlock, callback); }; /** * @param {!proto.pactus.GetBlockRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getBlock = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetBlock', request, metadata || {}, methodDescriptor_Blockchain_GetBlock); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetBlockHashRequest, * !proto.pactus.GetBlockHashResponse>} */ const methodDescriptor_Blockchain_GetBlockHash = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetBlockHash', grpc.web.MethodType.UNARY, proto.pactus.GetBlockHashRequest, proto.pactus.GetBlockHashResponse, /** * @param {!proto.pactus.GetBlockHashRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetBlockHashResponse.deserializeBinary ); /** * @param {!proto.pactus.GetBlockHashRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetBlockHashResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getBlockHash = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetBlockHash', request, metadata || {}, methodDescriptor_Blockchain_GetBlockHash, callback); }; /** * @param {!proto.pactus.GetBlockHashRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getBlockHash = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetBlockHash', request, metadata || {}, methodDescriptor_Blockchain_GetBlockHash); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetBlockHeightRequest, * !proto.pactus.GetBlockHeightResponse>} */ const methodDescriptor_Blockchain_GetBlockHeight = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetBlockHeight', grpc.web.MethodType.UNARY, proto.pactus.GetBlockHeightRequest, proto.pactus.GetBlockHeightResponse, /** * @param {!proto.pactus.GetBlockHeightRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetBlockHeightResponse.deserializeBinary ); /** * @param {!proto.pactus.GetBlockHeightRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetBlockHeightResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getBlockHeight = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetBlockHeight', request, metadata || {}, methodDescriptor_Blockchain_GetBlockHeight, callback); }; /** * @param {!proto.pactus.GetBlockHeightRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getBlockHeight = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetBlockHeight', request, metadata || {}, methodDescriptor_Blockchain_GetBlockHeight); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetBlockchainInfoRequest, * !proto.pactus.GetBlockchainInfoResponse>} */ const methodDescriptor_Blockchain_GetBlockchainInfo = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetBlockchainInfo', grpc.web.MethodType.UNARY, proto.pactus.GetBlockchainInfoRequest, proto.pactus.GetBlockchainInfoResponse, /** * @param {!proto.pactus.GetBlockchainInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetBlockchainInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetBlockchainInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetBlockchainInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getBlockchainInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetBlockchainInfo', request, metadata || {}, methodDescriptor_Blockchain_GetBlockchainInfo, callback); }; /** * @param {!proto.pactus.GetBlockchainInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getBlockchainInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetBlockchainInfo', request, metadata || {}, methodDescriptor_Blockchain_GetBlockchainInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetCommitteeInfoRequest, * !proto.pactus.GetCommitteeInfoResponse>} */ const methodDescriptor_Blockchain_GetCommitteeInfo = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetCommitteeInfo', grpc.web.MethodType.UNARY, proto.pactus.GetCommitteeInfoRequest, proto.pactus.GetCommitteeInfoResponse, /** * @param {!proto.pactus.GetCommitteeInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetCommitteeInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetCommitteeInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetCommitteeInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getCommitteeInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetCommitteeInfo', request, metadata || {}, methodDescriptor_Blockchain_GetCommitteeInfo, callback); }; /** * @param {!proto.pactus.GetCommitteeInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getCommitteeInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetCommitteeInfo', request, metadata || {}, methodDescriptor_Blockchain_GetCommitteeInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetConsensusInfoRequest, * !proto.pactus.GetConsensusInfoResponse>} */ const methodDescriptor_Blockchain_GetConsensusInfo = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetConsensusInfo', grpc.web.MethodType.UNARY, proto.pactus.GetConsensusInfoRequest, proto.pactus.GetConsensusInfoResponse, /** * @param {!proto.pactus.GetConsensusInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetConsensusInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetConsensusInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetConsensusInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getConsensusInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetConsensusInfo', request, metadata || {}, methodDescriptor_Blockchain_GetConsensusInfo, callback); }; /** * @param {!proto.pactus.GetConsensusInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getConsensusInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetConsensusInfo', request, metadata || {}, methodDescriptor_Blockchain_GetConsensusInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetAccountRequest, * !proto.pactus.GetAccountResponse>} */ const methodDescriptor_Blockchain_GetAccount = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetAccount', grpc.web.MethodType.UNARY, proto.pactus.GetAccountRequest, proto.pactus.GetAccountResponse, /** * @param {!proto.pactus.GetAccountRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetAccountResponse.deserializeBinary ); /** * @param {!proto.pactus.GetAccountRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetAccountResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getAccount = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetAccount', request, metadata || {}, methodDescriptor_Blockchain_GetAccount, callback); }; /** * @param {!proto.pactus.GetAccountRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getAccount = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetAccount', request, metadata || {}, methodDescriptor_Blockchain_GetAccount); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetValidatorRequest, * !proto.pactus.GetValidatorResponse>} */ const methodDescriptor_Blockchain_GetValidator = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetValidator', grpc.web.MethodType.UNARY, proto.pactus.GetValidatorRequest, proto.pactus.GetValidatorResponse, /** * @param {!proto.pactus.GetValidatorRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetValidatorResponse.deserializeBinary ); /** * @param {!proto.pactus.GetValidatorRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetValidatorResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getValidator = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetValidator', request, metadata || {}, methodDescriptor_Blockchain_GetValidator, callback); }; /** * @param {!proto.pactus.GetValidatorRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getValidator = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetValidator', request, metadata || {}, methodDescriptor_Blockchain_GetValidator); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetValidatorByNumberRequest, * !proto.pactus.GetValidatorResponse>} */ const methodDescriptor_Blockchain_GetValidatorByNumber = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetValidatorByNumber', grpc.web.MethodType.UNARY, proto.pactus.GetValidatorByNumberRequest, proto.pactus.GetValidatorResponse, /** * @param {!proto.pactus.GetValidatorByNumberRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetValidatorResponse.deserializeBinary ); /** * @param {!proto.pactus.GetValidatorByNumberRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetValidatorResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getValidatorByNumber = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetValidatorByNumber', request, metadata || {}, methodDescriptor_Blockchain_GetValidatorByNumber, callback); }; /** * @param {!proto.pactus.GetValidatorByNumberRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getValidatorByNumber = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetValidatorByNumber', request, metadata || {}, methodDescriptor_Blockchain_GetValidatorByNumber); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetValidatorAddressesRequest, * !proto.pactus.GetValidatorAddressesResponse>} */ const methodDescriptor_Blockchain_GetValidatorAddresses = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetValidatorAddresses', grpc.web.MethodType.UNARY, proto.pactus.GetValidatorAddressesRequest, proto.pactus.GetValidatorAddressesResponse, /** * @param {!proto.pactus.GetValidatorAddressesRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetValidatorAddressesResponse.deserializeBinary ); /** * @param {!proto.pactus.GetValidatorAddressesRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetValidatorAddressesResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getValidatorAddresses = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetValidatorAddresses', request, metadata || {}, methodDescriptor_Blockchain_GetValidatorAddresses, callback); }; /** * @param {!proto.pactus.GetValidatorAddressesRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getValidatorAddresses = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetValidatorAddresses', request, metadata || {}, methodDescriptor_Blockchain_GetValidatorAddresses); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetPublicKeyRequest, * !proto.pactus.GetPublicKeyResponse>} */ const methodDescriptor_Blockchain_GetPublicKey = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetPublicKey', grpc.web.MethodType.UNARY, proto.pactus.GetPublicKeyRequest, proto.pactus.GetPublicKeyResponse, /** * @param {!proto.pactus.GetPublicKeyRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetPublicKeyResponse.deserializeBinary ); /** * @param {!proto.pactus.GetPublicKeyRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetPublicKeyResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getPublicKey = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetPublicKey', request, metadata || {}, methodDescriptor_Blockchain_GetPublicKey, callback); }; /** * @param {!proto.pactus.GetPublicKeyRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getPublicKey = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetPublicKey', request, metadata || {}, methodDescriptor_Blockchain_GetPublicKey); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetTxPoolContentRequest, * !proto.pactus.GetTxPoolContentResponse>} */ const methodDescriptor_Blockchain_GetTxPoolContent = new grpc.web.MethodDescriptor( '/pactus.Blockchain/GetTxPoolContent', grpc.web.MethodType.UNARY, proto.pactus.GetTxPoolContentRequest, proto.pactus.GetTxPoolContentResponse, /** * @param {!proto.pactus.GetTxPoolContentRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetTxPoolContentResponse.deserializeBinary ); /** * @param {!proto.pactus.GetTxPoolContentRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetTxPoolContentResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.BlockchainClient.prototype.getTxPoolContent = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Blockchain/GetTxPoolContent', request, metadata || {}, methodDescriptor_Blockchain_GetTxPoolContent, callback); }; /** * @param {!proto.pactus.GetTxPoolContentRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.BlockchainPromiseClient.prototype.getTxPoolContent = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Blockchain/GetTxPoolContent', request, metadata || {}, methodDescriptor_Blockchain_GetTxPoolContent); }; module.exports = proto.pactus; ================================================ FILE: www/grpc/gen/js/blockchain_pb.js ================================================ // source: blockchain.proto /** * @fileoverview * @enhanceable * @suppress {missingRequire} reports error on implicit type usages. * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var global = globalThis; var transaction_pb = require('./transaction_pb.js'); goog.object.extend(proto, transaction_pb); goog.exportSymbol('proto.pactus.AccountInfo', null, global); goog.exportSymbol('proto.pactus.BlockHeaderInfo', null, global); goog.exportSymbol('proto.pactus.BlockVerbosity', null, global); goog.exportSymbol('proto.pactus.CertificateInfo', null, global); goog.exportSymbol('proto.pactus.ConsensusInfo', null, global); goog.exportSymbol('proto.pactus.GetAccountRequest', null, global); goog.exportSymbol('proto.pactus.GetAccountResponse', null, global); goog.exportSymbol('proto.pactus.GetBlockHashRequest', null, global); goog.exportSymbol('proto.pactus.GetBlockHashResponse', null, global); goog.exportSymbol('proto.pactus.GetBlockHeightRequest', null, global); goog.exportSymbol('proto.pactus.GetBlockHeightResponse', null, global); goog.exportSymbol('proto.pactus.GetBlockRequest', null, global); goog.exportSymbol('proto.pactus.GetBlockResponse', null, global); goog.exportSymbol('proto.pactus.GetBlockchainInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetBlockchainInfoResponse', null, global); goog.exportSymbol('proto.pactus.GetCommitteeInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetCommitteeInfoResponse', null, global); goog.exportSymbol('proto.pactus.GetConsensusInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetConsensusInfoResponse', null, global); goog.exportSymbol('proto.pactus.GetPublicKeyRequest', null, global); goog.exportSymbol('proto.pactus.GetPublicKeyResponse', null, global); goog.exportSymbol('proto.pactus.GetTxPoolContentRequest', null, global); goog.exportSymbol('proto.pactus.GetTxPoolContentResponse', null, global); goog.exportSymbol('proto.pactus.GetValidatorAddressesRequest', null, global); goog.exportSymbol('proto.pactus.GetValidatorAddressesResponse', null, global); goog.exportSymbol('proto.pactus.GetValidatorByNumberRequest', null, global); goog.exportSymbol('proto.pactus.GetValidatorRequest', null, global); goog.exportSymbol('proto.pactus.GetValidatorResponse', null, global); goog.exportSymbol('proto.pactus.ProposalInfo', null, global); goog.exportSymbol('proto.pactus.ValidatorInfo', null, global); goog.exportSymbol('proto.pactus.VoteInfo', null, global); goog.exportSymbol('proto.pactus.VoteType', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetAccountRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetAccountRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetAccountRequest.displayName = 'proto.pactus.GetAccountRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetAccountResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetAccountResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetAccountResponse.displayName = 'proto.pactus.GetAccountResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorAddressesRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetValidatorAddressesRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorAddressesRequest.displayName = 'proto.pactus.GetValidatorAddressesRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorAddressesResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetValidatorAddressesResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.GetValidatorAddressesResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorAddressesResponse.displayName = 'proto.pactus.GetValidatorAddressesResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetValidatorRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorRequest.displayName = 'proto.pactus.GetValidatorRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorByNumberRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetValidatorByNumberRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorByNumberRequest.displayName = 'proto.pactus.GetValidatorByNumberRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetValidatorResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorResponse.displayName = 'proto.pactus.GetValidatorResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetPublicKeyRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetPublicKeyRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetPublicKeyRequest.displayName = 'proto.pactus.GetPublicKeyRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetPublicKeyResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetPublicKeyResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetPublicKeyResponse.displayName = 'proto.pactus.GetPublicKeyResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockRequest.displayName = 'proto.pactus.GetBlockRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetBlockResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.GetBlockResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockResponse.displayName = 'proto.pactus.GetBlockResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockHashRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockHashRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockHashRequest.displayName = 'proto.pactus.GetBlockHashRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockHashResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockHashResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockHashResponse.displayName = 'proto.pactus.GetBlockHashResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockHeightRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockHeightRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockHeightRequest.displayName = 'proto.pactus.GetBlockHeightRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockHeightResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockHeightResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockHeightResponse.displayName = 'proto.pactus.GetBlockHeightResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockchainInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockchainInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockchainInfoRequest.displayName = 'proto.pactus.GetBlockchainInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetBlockchainInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetBlockchainInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetBlockchainInfoResponse.displayName = 'proto.pactus.GetBlockchainInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetCommitteeInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetCommitteeInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetCommitteeInfoRequest.displayName = 'proto.pactus.GetCommitteeInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetCommitteeInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetCommitteeInfoResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.GetCommitteeInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetCommitteeInfoResponse.displayName = 'proto.pactus.GetCommitteeInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetConsensusInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetConsensusInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetConsensusInfoRequest.displayName = 'proto.pactus.GetConsensusInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetConsensusInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetConsensusInfoResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.GetConsensusInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetConsensusInfoResponse.displayName = 'proto.pactus.GetConsensusInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTxPoolContentRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTxPoolContentRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTxPoolContentRequest.displayName = 'proto.pactus.GetTxPoolContentRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTxPoolContentResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetTxPoolContentResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.GetTxPoolContentResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTxPoolContentResponse.displayName = 'proto.pactus.GetTxPoolContentResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ValidatorInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ValidatorInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ValidatorInfo.displayName = 'proto.pactus.ValidatorInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.AccountInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.AccountInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.AccountInfo.displayName = 'proto.pactus.AccountInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.BlockHeaderInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.BlockHeaderInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.BlockHeaderInfo.displayName = 'proto.pactus.BlockHeaderInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CertificateInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.CertificateInfo.repeatedFields_, null); }; goog.inherits(proto.pactus.CertificateInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CertificateInfo.displayName = 'proto.pactus.CertificateInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.VoteInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.VoteInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.VoteInfo.displayName = 'proto.pactus.VoteInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ConsensusInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.ConsensusInfo.repeatedFields_, null); }; goog.inherits(proto.pactus.ConsensusInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ConsensusInfo.displayName = 'proto.pactus.ConsensusInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ProposalInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ProposalInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ProposalInfo.displayName = 'proto.pactus.ProposalInfo'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetAccountRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetAccountRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetAccountRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAccountRequest.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetAccountRequest} */ proto.pactus.GetAccountRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetAccountRequest; return proto.pactus.GetAccountRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetAccountRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetAccountRequest} */ proto.pactus.GetAccountRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetAccountRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetAccountRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetAccountRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAccountRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.GetAccountRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetAccountRequest} returns this */ proto.pactus.GetAccountRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetAccountResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetAccountResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetAccountResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAccountResponse.toObject = function(includeInstance, msg) { var f, obj = { account: (f = msg.getAccount()) && proto.pactus.AccountInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetAccountResponse} */ proto.pactus.GetAccountResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetAccountResponse; return proto.pactus.GetAccountResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetAccountResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetAccountResponse} */ proto.pactus.GetAccountResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.pactus.AccountInfo; reader.readMessage(value,proto.pactus.AccountInfo.deserializeBinaryFromReader); msg.setAccount(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetAccountResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetAccountResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetAccountResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAccountResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAccount(); if (f != null) { writer.writeMessage( 1, f, proto.pactus.AccountInfo.serializeBinaryToWriter ); } }; /** * optional AccountInfo account = 1; * @return {?proto.pactus.AccountInfo} */ proto.pactus.GetAccountResponse.prototype.getAccount = function() { return /** @type{?proto.pactus.AccountInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.AccountInfo, 1)); }; /** * @param {?proto.pactus.AccountInfo|undefined} value * @return {!proto.pactus.GetAccountResponse} returns this */ proto.pactus.GetAccountResponse.prototype.setAccount = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetAccountResponse} returns this */ proto.pactus.GetAccountResponse.prototype.clearAccount = function() { return this.setAccount(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetAccountResponse.prototype.hasAccount = function() { return jspb.Message.getField(this, 1) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorAddressesRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorAddressesRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorAddressesRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressesRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorAddressesRequest} */ proto.pactus.GetValidatorAddressesRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorAddressesRequest; return proto.pactus.GetValidatorAddressesRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorAddressesRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorAddressesRequest} */ proto.pactus.GetValidatorAddressesRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorAddressesRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorAddressesRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorAddressesRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressesRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetValidatorAddressesResponse.repeatedFields_ = [1]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorAddressesResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorAddressesResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorAddressesResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressesResponse.toObject = function(includeInstance, msg) { var f, obj = { addressesList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorAddressesResponse} */ proto.pactus.GetValidatorAddressesResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorAddressesResponse; return proto.pactus.GetValidatorAddressesResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorAddressesResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorAddressesResponse} */ proto.pactus.GetValidatorAddressesResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addAddresses(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorAddressesResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorAddressesResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorAddressesResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressesResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddressesList(); if (f.length > 0) { writer.writeRepeatedString( 1, f ); } }; /** * repeated string addresses = 1; * @return {!Array} */ proto.pactus.GetValidatorAddressesResponse.prototype.getAddressesList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1)); }; /** * @param {!Array} value * @return {!proto.pactus.GetValidatorAddressesResponse} returns this */ proto.pactus.GetValidatorAddressesResponse.prototype.setAddressesList = function(value) { return jspb.Message.setField(this, 1, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.GetValidatorAddressesResponse} returns this */ proto.pactus.GetValidatorAddressesResponse.prototype.addAddresses = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 1, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetValidatorAddressesResponse} returns this */ proto.pactus.GetValidatorAddressesResponse.prototype.clearAddressesList = function() { return this.setAddressesList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorRequest.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorRequest} */ proto.pactus.GetValidatorRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorRequest; return proto.pactus.GetValidatorRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorRequest} */ proto.pactus.GetValidatorRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.GetValidatorRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetValidatorRequest} returns this */ proto.pactus.GetValidatorRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorByNumberRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorByNumberRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorByNumberRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorByNumberRequest.toObject = function(includeInstance, msg) { var f, obj = { number: jspb.Message.getFieldWithDefault(msg, 1, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorByNumberRequest} */ proto.pactus.GetValidatorByNumberRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorByNumberRequest; return proto.pactus.GetValidatorByNumberRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorByNumberRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorByNumberRequest} */ proto.pactus.GetValidatorByNumberRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt32()); msg.setNumber(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorByNumberRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorByNumberRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorByNumberRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorByNumberRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getNumber(); if (f !== 0) { writer.writeInt32( 1, f ); } }; /** * optional int32 number = 1; * @return {number} */ proto.pactus.GetValidatorByNumberRequest.prototype.getNumber = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetValidatorByNumberRequest} returns this */ proto.pactus.GetValidatorByNumberRequest.prototype.setNumber = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorResponse.toObject = function(includeInstance, msg) { var f, obj = { validator: (f = msg.getValidator()) && proto.pactus.ValidatorInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorResponse} */ proto.pactus.GetValidatorResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorResponse; return proto.pactus.GetValidatorResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorResponse} */ proto.pactus.GetValidatorResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.pactus.ValidatorInfo; reader.readMessage(value,proto.pactus.ValidatorInfo.deserializeBinaryFromReader); msg.setValidator(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getValidator(); if (f != null) { writer.writeMessage( 1, f, proto.pactus.ValidatorInfo.serializeBinaryToWriter ); } }; /** * optional ValidatorInfo validator = 1; * @return {?proto.pactus.ValidatorInfo} */ proto.pactus.GetValidatorResponse.prototype.getValidator = function() { return /** @type{?proto.pactus.ValidatorInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.ValidatorInfo, 1)); }; /** * @param {?proto.pactus.ValidatorInfo|undefined} value * @return {!proto.pactus.GetValidatorResponse} returns this */ proto.pactus.GetValidatorResponse.prototype.setValidator = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetValidatorResponse} returns this */ proto.pactus.GetValidatorResponse.prototype.clearValidator = function() { return this.setValidator(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetValidatorResponse.prototype.hasValidator = function() { return jspb.Message.getField(this, 1) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetPublicKeyRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetPublicKeyRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetPublicKeyRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPublicKeyRequest.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetPublicKeyRequest} */ proto.pactus.GetPublicKeyRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetPublicKeyRequest; return proto.pactus.GetPublicKeyRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetPublicKeyRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetPublicKeyRequest} */ proto.pactus.GetPublicKeyRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetPublicKeyRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetPublicKeyRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetPublicKeyRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPublicKeyRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.GetPublicKeyRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetPublicKeyRequest} returns this */ proto.pactus.GetPublicKeyRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetPublicKeyResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetPublicKeyResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetPublicKeyResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPublicKeyResponse.toObject = function(includeInstance, msg) { var f, obj = { publicKey: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetPublicKeyResponse} */ proto.pactus.GetPublicKeyResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetPublicKeyResponse; return proto.pactus.GetPublicKeyResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetPublicKeyResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetPublicKeyResponse} */ proto.pactus.GetPublicKeyResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetPublicKeyResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetPublicKeyResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetPublicKeyResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPublicKeyResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string public_key = 1; * @return {string} */ proto.pactus.GetPublicKeyResponse.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetPublicKeyResponse} returns this */ proto.pactus.GetPublicKeyResponse.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockRequest.toObject = function(includeInstance, msg) { var f, obj = { height: jspb.Message.getFieldWithDefault(msg, 1, 0), verbosity: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockRequest} */ proto.pactus.GetBlockRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockRequest; return proto.pactus.GetBlockRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockRequest} */ proto.pactus.GetBlockRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; case 2: var value = /** @type {!proto.pactus.BlockVerbosity} */ (reader.readEnum()); msg.setVerbosity(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getVerbosity(); if (f !== 0.0) { writer.writeEnum( 2, f ); } }; /** * optional uint32 height = 1; * @return {number} */ proto.pactus.GetBlockRequest.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockRequest} returns this */ proto.pactus.GetBlockRequest.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional BlockVerbosity verbosity = 2; * @return {!proto.pactus.BlockVerbosity} */ proto.pactus.GetBlockRequest.prototype.getVerbosity = function() { return /** @type {!proto.pactus.BlockVerbosity} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {!proto.pactus.BlockVerbosity} value * @return {!proto.pactus.GetBlockRequest} returns this */ proto.pactus.GetBlockRequest.prototype.setVerbosity = function(value) { return jspb.Message.setProto3EnumField(this, 2, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetBlockResponse.repeatedFields_ = [7]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockResponse.toObject = function(includeInstance, msg) { var f, obj = { height: jspb.Message.getFieldWithDefault(msg, 1, 0), hash: jspb.Message.getFieldWithDefault(msg, 2, ""), data: jspb.Message.getFieldWithDefault(msg, 3, ""), blockTime: jspb.Message.getFieldWithDefault(msg, 4, 0), header: (f = msg.getHeader()) && proto.pactus.BlockHeaderInfo.toObject(includeInstance, f), prevCert: (f = msg.getPrevCert()) && proto.pactus.CertificateInfo.toObject(includeInstance, f), txsList: jspb.Message.toObjectList(msg.getTxsList(), transaction_pb.TransactionInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockResponse} */ proto.pactus.GetBlockResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockResponse; return proto.pactus.GetBlockResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockResponse} */ proto.pactus.GetBlockResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setHash(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setData(value); break; case 4: var value = /** @type {number} */ (reader.readUint32()); msg.setBlockTime(value); break; case 5: var value = new proto.pactus.BlockHeaderInfo; reader.readMessage(value,proto.pactus.BlockHeaderInfo.deserializeBinaryFromReader); msg.setHeader(value); break; case 6: var value = new proto.pactus.CertificateInfo; reader.readMessage(value,proto.pactus.CertificateInfo.deserializeBinaryFromReader); msg.setPrevCert(value); break; case 7: var value = new transaction_pb.TransactionInfo; reader.readMessage(value,transaction_pb.TransactionInfo.deserializeBinaryFromReader); msg.addTxs(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getHash(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getData(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getBlockTime(); if (f !== 0) { writer.writeUint32( 4, f ); } f = message.getHeader(); if (f != null) { writer.writeMessage( 5, f, proto.pactus.BlockHeaderInfo.serializeBinaryToWriter ); } f = message.getPrevCert(); if (f != null) { writer.writeMessage( 6, f, proto.pactus.CertificateInfo.serializeBinaryToWriter ); } f = message.getTxsList(); if (f.length > 0) { writer.writeRepeatedMessage( 7, f, transaction_pb.TransactionInfo.serializeBinaryToWriter ); } }; /** * optional uint32 height = 1; * @return {number} */ proto.pactus.GetBlockResponse.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string hash = 2; * @return {string} */ proto.pactus.GetBlockResponse.prototype.getHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setHash = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string data = 3; * @return {string} */ proto.pactus.GetBlockResponse.prototype.getData = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setData = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional uint32 block_time = 4; * @return {number} */ proto.pactus.GetBlockResponse.prototype.getBlockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setBlockTime = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional BlockHeaderInfo header = 5; * @return {?proto.pactus.BlockHeaderInfo} */ proto.pactus.GetBlockResponse.prototype.getHeader = function() { return /** @type{?proto.pactus.BlockHeaderInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.BlockHeaderInfo, 5)); }; /** * @param {?proto.pactus.BlockHeaderInfo|undefined} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setHeader = function(value) { return jspb.Message.setWrapperField(this, 5, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.clearHeader = function() { return this.setHeader(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetBlockResponse.prototype.hasHeader = function() { return jspb.Message.getField(this, 5) != null; }; /** * optional CertificateInfo prev_cert = 6; * @return {?proto.pactus.CertificateInfo} */ proto.pactus.GetBlockResponse.prototype.getPrevCert = function() { return /** @type{?proto.pactus.CertificateInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.CertificateInfo, 6)); }; /** * @param {?proto.pactus.CertificateInfo|undefined} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setPrevCert = function(value) { return jspb.Message.setWrapperField(this, 6, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.clearPrevCert = function() { return this.setPrevCert(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetBlockResponse.prototype.hasPrevCert = function() { return jspb.Message.getField(this, 6) != null; }; /** * repeated TransactionInfo txs = 7; * @return {!Array} */ proto.pactus.GetBlockResponse.prototype.getTxsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, transaction_pb.TransactionInfo, 7)); }; /** * @param {!Array} value * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.setTxsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 7, value); }; /** * @param {!proto.pactus.TransactionInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.TransactionInfo} */ proto.pactus.GetBlockResponse.prototype.addTxs = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 7, opt_value, proto.pactus.TransactionInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetBlockResponse} returns this */ proto.pactus.GetBlockResponse.prototype.clearTxsList = function() { return this.setTxsList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockHashRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockHashRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockHashRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHashRequest.toObject = function(includeInstance, msg) { var f, obj = { height: jspb.Message.getFieldWithDefault(msg, 1, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockHashRequest} */ proto.pactus.GetBlockHashRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockHashRequest; return proto.pactus.GetBlockHashRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockHashRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockHashRequest} */ proto.pactus.GetBlockHashRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockHashRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockHashRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockHashRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHashRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } }; /** * optional uint32 height = 1; * @return {number} */ proto.pactus.GetBlockHashRequest.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockHashRequest} returns this */ proto.pactus.GetBlockHashRequest.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockHashResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockHashResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockHashResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHashResponse.toObject = function(includeInstance, msg) { var f, obj = { hash: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockHashResponse} */ proto.pactus.GetBlockHashResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockHashResponse; return proto.pactus.GetBlockHashResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockHashResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockHashResponse} */ proto.pactus.GetBlockHashResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setHash(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockHashResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockHashResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockHashResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHashResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHash(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string hash = 1; * @return {string} */ proto.pactus.GetBlockHashResponse.prototype.getHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetBlockHashResponse} returns this */ proto.pactus.GetBlockHashResponse.prototype.setHash = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockHeightRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockHeightRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockHeightRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHeightRequest.toObject = function(includeInstance, msg) { var f, obj = { hash: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockHeightRequest} */ proto.pactus.GetBlockHeightRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockHeightRequest; return proto.pactus.GetBlockHeightRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockHeightRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockHeightRequest} */ proto.pactus.GetBlockHeightRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setHash(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockHeightRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockHeightRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockHeightRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHeightRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHash(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string hash = 1; * @return {string} */ proto.pactus.GetBlockHeightRequest.prototype.getHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetBlockHeightRequest} returns this */ proto.pactus.GetBlockHeightRequest.prototype.setHash = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockHeightResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockHeightResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockHeightResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHeightResponse.toObject = function(includeInstance, msg) { var f, obj = { height: jspb.Message.getFieldWithDefault(msg, 1, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockHeightResponse} */ proto.pactus.GetBlockHeightResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockHeightResponse; return proto.pactus.GetBlockHeightResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockHeightResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockHeightResponse} */ proto.pactus.GetBlockHeightResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockHeightResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockHeightResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockHeightResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockHeightResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } }; /** * optional uint32 height = 1; * @return {number} */ proto.pactus.GetBlockHeightResponse.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockHeightResponse} returns this */ proto.pactus.GetBlockHeightResponse.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockchainInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockchainInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockchainInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockchainInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockchainInfoRequest} */ proto.pactus.GetBlockchainInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockchainInfoRequest; return proto.pactus.GetBlockchainInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockchainInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockchainInfoRequest} */ proto.pactus.GetBlockchainInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockchainInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockchainInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockchainInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockchainInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetBlockchainInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetBlockchainInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetBlockchainInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockchainInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { lastBlockHeight: jspb.Message.getFieldWithDefault(msg, 1, 0), lastBlockHash: jspb.Message.getFieldWithDefault(msg, 2, ""), lastBlockTime: jspb.Message.getFieldWithDefault(msg, 10, 0), totalAccounts: jspb.Message.getFieldWithDefault(msg, 3, 0), totalValidators: jspb.Message.getFieldWithDefault(msg, 4, 0), activeValidators: jspb.Message.getFieldWithDefault(msg, 12, 0), totalPower: jspb.Message.getFieldWithDefault(msg, 5, 0), committeePower: jspb.Message.getFieldWithDefault(msg, 6, 0), isPruned: jspb.Message.getBooleanFieldWithDefault(msg, 8, false), pruningHeight: jspb.Message.getFieldWithDefault(msg, 9, 0), inCommittee: jspb.Message.getBooleanFieldWithDefault(msg, 13, false), committeeSize: jspb.Message.getFieldWithDefault(msg, 14, 0), averageScore: jspb.Message.getFloatingPointFieldWithDefault(msg, 15, 0.0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetBlockchainInfoResponse} */ proto.pactus.GetBlockchainInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetBlockchainInfoResponse; return proto.pactus.GetBlockchainInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetBlockchainInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetBlockchainInfoResponse} */ proto.pactus.GetBlockchainInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setLastBlockHeight(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setLastBlockHash(value); break; case 10: var value = /** @type {number} */ (reader.readInt64()); msg.setLastBlockTime(value); break; case 3: var value = /** @type {number} */ (reader.readInt32()); msg.setTotalAccounts(value); break; case 4: var value = /** @type {number} */ (reader.readInt32()); msg.setTotalValidators(value); break; case 12: var value = /** @type {number} */ (reader.readInt32()); msg.setActiveValidators(value); break; case 5: var value = /** @type {number} */ (reader.readInt64()); msg.setTotalPower(value); break; case 6: var value = /** @type {number} */ (reader.readInt64()); msg.setCommitteePower(value); break; case 8: var value = /** @type {boolean} */ (reader.readBool()); msg.setIsPruned(value); break; case 9: var value = /** @type {number} */ (reader.readUint32()); msg.setPruningHeight(value); break; case 13: var value = /** @type {boolean} */ (reader.readBool()); msg.setInCommittee(value); break; case 14: var value = /** @type {number} */ (reader.readInt32()); msg.setCommitteeSize(value); break; case 15: var value = /** @type {number} */ (reader.readDouble()); msg.setAverageScore(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetBlockchainInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetBlockchainInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetBlockchainInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetBlockchainInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getLastBlockHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getLastBlockHash(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getLastBlockTime(); if (f !== 0) { writer.writeInt64( 10, f ); } f = message.getTotalAccounts(); if (f !== 0) { writer.writeInt32( 3, f ); } f = message.getTotalValidators(); if (f !== 0) { writer.writeInt32( 4, f ); } f = message.getActiveValidators(); if (f !== 0) { writer.writeInt32( 12, f ); } f = message.getTotalPower(); if (f !== 0) { writer.writeInt64( 5, f ); } f = message.getCommitteePower(); if (f !== 0) { writer.writeInt64( 6, f ); } f = message.getIsPruned(); if (f) { writer.writeBool( 8, f ); } f = message.getPruningHeight(); if (f !== 0) { writer.writeUint32( 9, f ); } f = message.getInCommittee(); if (f) { writer.writeBool( 13, f ); } f = message.getCommitteeSize(); if (f !== 0) { writer.writeInt32( 14, f ); } f = message.getAverageScore(); if (f !== 0.0) { writer.writeDouble( 15, f ); } }; /** * optional uint32 last_block_height = 1; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getLastBlockHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setLastBlockHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string last_block_hash = 2; * @return {string} */ proto.pactus.GetBlockchainInfoResponse.prototype.getLastBlockHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setLastBlockHash = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int64 last_block_time = 10; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getLastBlockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 10, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setLastBlockTime = function(value) { return jspb.Message.setProto3IntField(this, 10, value); }; /** * optional int32 total_accounts = 3; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getTotalAccounts = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setTotalAccounts = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * optional int32 total_validators = 4; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getTotalValidators = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setTotalValidators = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int32 active_validators = 12; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getActiveValidators = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 12, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setActiveValidators = function(value) { return jspb.Message.setProto3IntField(this, 12, value); }; /** * optional int64 total_power = 5; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getTotalPower = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setTotalPower = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * optional int64 committee_power = 6; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getCommitteePower = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setCommitteePower = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional bool is_pruned = 8; * @return {boolean} */ proto.pactus.GetBlockchainInfoResponse.prototype.getIsPruned = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 8, false)); }; /** * @param {boolean} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setIsPruned = function(value) { return jspb.Message.setProto3BooleanField(this, 8, value); }; /** * optional uint32 pruning_height = 9; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getPruningHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 9, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setPruningHeight = function(value) { return jspb.Message.setProto3IntField(this, 9, value); }; /** * optional bool in_committee = 13; * @return {boolean} */ proto.pactus.GetBlockchainInfoResponse.prototype.getInCommittee = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 13, false)); }; /** * @param {boolean} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setInCommittee = function(value) { return jspb.Message.setProto3BooleanField(this, 13, value); }; /** * optional int32 committee_size = 14; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getCommitteeSize = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 14, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setCommitteeSize = function(value) { return jspb.Message.setProto3IntField(this, 14, value); }; /** * optional double average_score = 15; * @return {number} */ proto.pactus.GetBlockchainInfoResponse.prototype.getAverageScore = function() { return /** @type {number} */ (jspb.Message.getFloatingPointFieldWithDefault(this, 15, 0.0)); }; /** * @param {number} value * @return {!proto.pactus.GetBlockchainInfoResponse} returns this */ proto.pactus.GetBlockchainInfoResponse.prototype.setAverageScore = function(value) { return jspb.Message.setProto3FloatField(this, 15, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetCommitteeInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetCommitteeInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetCommitteeInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetCommitteeInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetCommitteeInfoRequest} */ proto.pactus.GetCommitteeInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetCommitteeInfoRequest; return proto.pactus.GetCommitteeInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetCommitteeInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetCommitteeInfoRequest} */ proto.pactus.GetCommitteeInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetCommitteeInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetCommitteeInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetCommitteeInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetCommitteeInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetCommitteeInfoResponse.repeatedFields_ = [4]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetCommitteeInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetCommitteeInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetCommitteeInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetCommitteeInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { committeeSize: jspb.Message.getFieldWithDefault(msg, 1, 0), committeePower: jspb.Message.getFieldWithDefault(msg, 2, 0), totalPower: jspb.Message.getFieldWithDefault(msg, 3, 0), validatorsList: jspb.Message.toObjectList(msg.getValidatorsList(), proto.pactus.ValidatorInfo.toObject, includeInstance), protocolVersionsMap: (f = msg.getProtocolVersionsMap()) ? f.toObject(includeInstance, undefined) : [] }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetCommitteeInfoResponse} */ proto.pactus.GetCommitteeInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetCommitteeInfoResponse; return proto.pactus.GetCommitteeInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetCommitteeInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetCommitteeInfoResponse} */ proto.pactus.GetCommitteeInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt32()); msg.setCommitteeSize(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setCommitteePower(value); break; case 3: var value = /** @type {number} */ (reader.readInt64()); msg.setTotalPower(value); break; case 4: var value = new proto.pactus.ValidatorInfo; reader.readMessage(value,proto.pactus.ValidatorInfo.deserializeBinaryFromReader); msg.addValidators(value); break; case 5: var value = msg.getProtocolVersionsMap(); reader.readMessage(value, function(message, reader) { jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readInt32, jspb.BinaryReader.prototype.readDouble, null, 0, 0.0); }); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetCommitteeInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetCommitteeInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetCommitteeInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetCommitteeInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getCommitteeSize(); if (f !== 0) { writer.writeInt32( 1, f ); } f = message.getCommitteePower(); if (f !== 0) { writer.writeInt64( 2, f ); } f = message.getTotalPower(); if (f !== 0) { writer.writeInt64( 3, f ); } f = message.getValidatorsList(); if (f.length > 0) { writer.writeRepeatedMessage( 4, f, proto.pactus.ValidatorInfo.serializeBinaryToWriter ); } f = message.getProtocolVersionsMap(true); if (f && f.getLength() > 0) { jspb.internal.public_for_gencode.serializeMapToBinary( message.getProtocolVersionsMap(true), 5, writer, jspb.BinaryWriter.prototype.writeInt32, jspb.BinaryWriter.prototype.writeDouble); } }; /** * optional int32 committee_size = 1; * @return {number} */ proto.pactus.GetCommitteeInfoResponse.prototype.getCommitteeSize = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetCommitteeInfoResponse} returns this */ proto.pactus.GetCommitteeInfoResponse.prototype.setCommitteeSize = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional int64 committee_power = 2; * @return {number} */ proto.pactus.GetCommitteeInfoResponse.prototype.getCommitteePower = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetCommitteeInfoResponse} returns this */ proto.pactus.GetCommitteeInfoResponse.prototype.setCommitteePower = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * optional int64 total_power = 3; * @return {number} */ proto.pactus.GetCommitteeInfoResponse.prototype.getTotalPower = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetCommitteeInfoResponse} returns this */ proto.pactus.GetCommitteeInfoResponse.prototype.setTotalPower = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * repeated ValidatorInfo validators = 4; * @return {!Array} */ proto.pactus.GetCommitteeInfoResponse.prototype.getValidatorsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.ValidatorInfo, 4)); }; /** * @param {!Array} value * @return {!proto.pactus.GetCommitteeInfoResponse} returns this */ proto.pactus.GetCommitteeInfoResponse.prototype.setValidatorsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 4, value); }; /** * @param {!proto.pactus.ValidatorInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.ValidatorInfo} */ proto.pactus.GetCommitteeInfoResponse.prototype.addValidators = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 4, opt_value, proto.pactus.ValidatorInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetCommitteeInfoResponse} returns this */ proto.pactus.GetCommitteeInfoResponse.prototype.clearValidatorsList = function() { return this.setValidatorsList([]); }; /** * map protocol_versions = 5; * @param {boolean=} opt_noLazyCreate Do not create the map if * empty, instead returning `undefined` * @return {!jspb.Map} */ proto.pactus.GetCommitteeInfoResponse.prototype.getProtocolVersionsMap = function(opt_noLazyCreate) { return /** @type {!jspb.Map} */ ( jspb.Message.getMapField(this, 5, opt_noLazyCreate, null)); }; /** * Clears values from the map. The map will be non-null. * @return {!proto.pactus.GetCommitteeInfoResponse} returns this */ proto.pactus.GetCommitteeInfoResponse.prototype.clearProtocolVersionsMap = function() { this.getProtocolVersionsMap().clear(); return this; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetConsensusInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetConsensusInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetConsensusInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetConsensusInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetConsensusInfoRequest} */ proto.pactus.GetConsensusInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetConsensusInfoRequest; return proto.pactus.GetConsensusInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetConsensusInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetConsensusInfoRequest} */ proto.pactus.GetConsensusInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetConsensusInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetConsensusInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetConsensusInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetConsensusInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetConsensusInfoResponse.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetConsensusInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetConsensusInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetConsensusInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetConsensusInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { proposal: (f = msg.getProposal()) && proto.pactus.ProposalInfo.toObject(includeInstance, f), instancesList: jspb.Message.toObjectList(msg.getInstancesList(), proto.pactus.ConsensusInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetConsensusInfoResponse} */ proto.pactus.GetConsensusInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetConsensusInfoResponse; return proto.pactus.GetConsensusInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetConsensusInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetConsensusInfoResponse} */ proto.pactus.GetConsensusInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.pactus.ProposalInfo; reader.readMessage(value,proto.pactus.ProposalInfo.deserializeBinaryFromReader); msg.setProposal(value); break; case 2: var value = new proto.pactus.ConsensusInfo; reader.readMessage(value,proto.pactus.ConsensusInfo.deserializeBinaryFromReader); msg.addInstances(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetConsensusInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetConsensusInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetConsensusInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetConsensusInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getProposal(); if (f != null) { writer.writeMessage( 1, f, proto.pactus.ProposalInfo.serializeBinaryToWriter ); } f = message.getInstancesList(); if (f.length > 0) { writer.writeRepeatedMessage( 2, f, proto.pactus.ConsensusInfo.serializeBinaryToWriter ); } }; /** * optional ProposalInfo proposal = 1; * @return {?proto.pactus.ProposalInfo} */ proto.pactus.GetConsensusInfoResponse.prototype.getProposal = function() { return /** @type{?proto.pactus.ProposalInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.ProposalInfo, 1)); }; /** * @param {?proto.pactus.ProposalInfo|undefined} value * @return {!proto.pactus.GetConsensusInfoResponse} returns this */ proto.pactus.GetConsensusInfoResponse.prototype.setProposal = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetConsensusInfoResponse} returns this */ proto.pactus.GetConsensusInfoResponse.prototype.clearProposal = function() { return this.setProposal(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetConsensusInfoResponse.prototype.hasProposal = function() { return jspb.Message.getField(this, 1) != null; }; /** * repeated ConsensusInfo instances = 2; * @return {!Array} */ proto.pactus.GetConsensusInfoResponse.prototype.getInstancesList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.ConsensusInfo, 2)); }; /** * @param {!Array} value * @return {!proto.pactus.GetConsensusInfoResponse} returns this */ proto.pactus.GetConsensusInfoResponse.prototype.setInstancesList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 2, value); }; /** * @param {!proto.pactus.ConsensusInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.ConsensusInfo} */ proto.pactus.GetConsensusInfoResponse.prototype.addInstances = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 2, opt_value, proto.pactus.ConsensusInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetConsensusInfoResponse} returns this */ proto.pactus.GetConsensusInfoResponse.prototype.clearInstancesList = function() { return this.setInstancesList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTxPoolContentRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTxPoolContentRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTxPoolContentRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTxPoolContentRequest.toObject = function(includeInstance, msg) { var f, obj = { payloadType: jspb.Message.getFieldWithDefault(msg, 1, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTxPoolContentRequest} */ proto.pactus.GetTxPoolContentRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTxPoolContentRequest; return proto.pactus.GetTxPoolContentRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTxPoolContentRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTxPoolContentRequest} */ proto.pactus.GetTxPoolContentRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {!proto.pactus.PayloadType} */ (reader.readEnum()); msg.setPayloadType(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTxPoolContentRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTxPoolContentRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTxPoolContentRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTxPoolContentRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPayloadType(); if (f !== 0.0) { writer.writeEnum( 1, f ); } }; /** * optional PayloadType payload_type = 1; * @return {!proto.pactus.PayloadType} */ proto.pactus.GetTxPoolContentRequest.prototype.getPayloadType = function() { return /** @type {!proto.pactus.PayloadType} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {!proto.pactus.PayloadType} value * @return {!proto.pactus.GetTxPoolContentRequest} returns this */ proto.pactus.GetTxPoolContentRequest.prototype.setPayloadType = function(value) { return jspb.Message.setProto3EnumField(this, 1, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetTxPoolContentResponse.repeatedFields_ = [1]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTxPoolContentResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTxPoolContentResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTxPoolContentResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTxPoolContentResponse.toObject = function(includeInstance, msg) { var f, obj = { txsList: jspb.Message.toObjectList(msg.getTxsList(), transaction_pb.TransactionInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTxPoolContentResponse} */ proto.pactus.GetTxPoolContentResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTxPoolContentResponse; return proto.pactus.GetTxPoolContentResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTxPoolContentResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTxPoolContentResponse} */ proto.pactus.GetTxPoolContentResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new transaction_pb.TransactionInfo; reader.readMessage(value,transaction_pb.TransactionInfo.deserializeBinaryFromReader); msg.addTxs(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTxPoolContentResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTxPoolContentResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTxPoolContentResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTxPoolContentResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getTxsList(); if (f.length > 0) { writer.writeRepeatedMessage( 1, f, transaction_pb.TransactionInfo.serializeBinaryToWriter ); } }; /** * repeated TransactionInfo txs = 1; * @return {!Array} */ proto.pactus.GetTxPoolContentResponse.prototype.getTxsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, transaction_pb.TransactionInfo, 1)); }; /** * @param {!Array} value * @return {!proto.pactus.GetTxPoolContentResponse} returns this */ proto.pactus.GetTxPoolContentResponse.prototype.setTxsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 1, value); }; /** * @param {!proto.pactus.TransactionInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.TransactionInfo} */ proto.pactus.GetTxPoolContentResponse.prototype.addTxs = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.pactus.TransactionInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetTxPoolContentResponse} returns this */ proto.pactus.GetTxPoolContentResponse.prototype.clearTxsList = function() { return this.setTxsList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ValidatorInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ValidatorInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ValidatorInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ValidatorInfo.toObject = function(includeInstance, msg) { var f, obj = { hash: jspb.Message.getFieldWithDefault(msg, 1, ""), data: jspb.Message.getFieldWithDefault(msg, 2, ""), publicKey: jspb.Message.getFieldWithDefault(msg, 3, ""), number: jspb.Message.getFieldWithDefault(msg, 4, 0), stake: jspb.Message.getFieldWithDefault(msg, 5, 0), lastBondingHeight: jspb.Message.getFieldWithDefault(msg, 6, 0), lastSortitionHeight: jspb.Message.getFieldWithDefault(msg, 7, 0), unbondingHeight: jspb.Message.getFieldWithDefault(msg, 8, 0), address: jspb.Message.getFieldWithDefault(msg, 9, ""), availabilityScore: jspb.Message.getFloatingPointFieldWithDefault(msg, 10, 0.0), protocolVersion: jspb.Message.getFieldWithDefault(msg, 11, 0), isDelegated: jspb.Message.getBooleanFieldWithDefault(msg, 12, false), delegateOwner: jspb.Message.getFieldWithDefault(msg, 13, ""), delegateShare: jspb.Message.getFieldWithDefault(msg, 14, 0), delegateExpiry: jspb.Message.getFieldWithDefault(msg, 15, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ValidatorInfo} */ proto.pactus.ValidatorInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ValidatorInfo; return proto.pactus.ValidatorInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ValidatorInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ValidatorInfo} */ proto.pactus.ValidatorInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setHash(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setData(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; case 4: var value = /** @type {number} */ (reader.readInt32()); msg.setNumber(value); break; case 5: var value = /** @type {number} */ (reader.readInt64()); msg.setStake(value); break; case 6: var value = /** @type {number} */ (reader.readUint32()); msg.setLastBondingHeight(value); break; case 7: var value = /** @type {number} */ (reader.readUint32()); msg.setLastSortitionHeight(value); break; case 8: var value = /** @type {number} */ (reader.readUint32()); msg.setUnbondingHeight(value); break; case 9: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 10: var value = /** @type {number} */ (reader.readDouble()); msg.setAvailabilityScore(value); break; case 11: var value = /** @type {number} */ (reader.readInt32()); msg.setProtocolVersion(value); break; case 12: var value = /** @type {boolean} */ (reader.readBool()); msg.setIsDelegated(value); break; case 13: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setDelegateOwner(value); break; case 14: var value = /** @type {number} */ (reader.readInt64()); msg.setDelegateShare(value); break; case 15: var value = /** @type {number} */ (reader.readUint32()); msg.setDelegateExpiry(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ValidatorInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ValidatorInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ValidatorInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ValidatorInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHash(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getData(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getNumber(); if (f !== 0) { writer.writeInt32( 4, f ); } f = message.getStake(); if (f !== 0) { writer.writeInt64( 5, f ); } f = message.getLastBondingHeight(); if (f !== 0) { writer.writeUint32( 6, f ); } f = message.getLastSortitionHeight(); if (f !== 0) { writer.writeUint32( 7, f ); } f = message.getUnbondingHeight(); if (f !== 0) { writer.writeUint32( 8, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 9, f ); } f = message.getAvailabilityScore(); if (f !== 0.0) { writer.writeDouble( 10, f ); } f = message.getProtocolVersion(); if (f !== 0) { writer.writeInt32( 11, f ); } f = message.getIsDelegated(); if (f) { writer.writeBool( 12, f ); } f = message.getDelegateOwner(); if (f.length > 0) { writer.writeString( 13, f ); } f = message.getDelegateShare(); if (f !== 0) { writer.writeInt64( 14, f ); } f = message.getDelegateExpiry(); if (f !== 0) { writer.writeUint32( 15, f ); } }; /** * optional string hash = 1; * @return {string} */ proto.pactus.ValidatorInfo.prototype.getHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setHash = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string data = 2; * @return {string} */ proto.pactus.ValidatorInfo.prototype.getData = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setData = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string public_key = 3; * @return {string} */ proto.pactus.ValidatorInfo.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional int32 number = 4; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getNumber = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setNumber = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int64 stake = 5; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getStake = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setStake = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * optional uint32 last_bonding_height = 6; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getLastBondingHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setLastBondingHeight = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional uint32 last_sortition_height = 7; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getLastSortitionHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setLastSortitionHeight = function(value) { return jspb.Message.setProto3IntField(this, 7, value); }; /** * optional uint32 unbonding_height = 8; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getUnbondingHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 8, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setUnbondingHeight = function(value) { return jspb.Message.setProto3IntField(this, 8, value); }; /** * optional string address = 9; * @return {string} */ proto.pactus.ValidatorInfo.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 9, "")); }; /** * @param {string} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 9, value); }; /** * optional double availability_score = 10; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getAvailabilityScore = function() { return /** @type {number} */ (jspb.Message.getFloatingPointFieldWithDefault(this, 10, 0.0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setAvailabilityScore = function(value) { return jspb.Message.setProto3FloatField(this, 10, value); }; /** * optional int32 protocol_version = 11; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getProtocolVersion = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 11, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setProtocolVersion = function(value) { return jspb.Message.setProto3IntField(this, 11, value); }; /** * optional bool is_delegated = 12; * @return {boolean} */ proto.pactus.ValidatorInfo.prototype.getIsDelegated = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 12, false)); }; /** * @param {boolean} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setIsDelegated = function(value) { return jspb.Message.setProto3BooleanField(this, 12, value); }; /** * optional string delegate_owner = 13; * @return {string} */ proto.pactus.ValidatorInfo.prototype.getDelegateOwner = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 13, "")); }; /** * @param {string} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setDelegateOwner = function(value) { return jspb.Message.setProto3StringField(this, 13, value); }; /** * optional int64 delegate_share = 14; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getDelegateShare = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 14, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setDelegateShare = function(value) { return jspb.Message.setProto3IntField(this, 14, value); }; /** * optional uint32 delegate_expiry = 15; * @return {number} */ proto.pactus.ValidatorInfo.prototype.getDelegateExpiry = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 15, 0)); }; /** * @param {number} value * @return {!proto.pactus.ValidatorInfo} returns this */ proto.pactus.ValidatorInfo.prototype.setDelegateExpiry = function(value) { return jspb.Message.setProto3IntField(this, 15, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.AccountInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.AccountInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.AccountInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.AccountInfo.toObject = function(includeInstance, msg) { var f, obj = { hash: jspb.Message.getFieldWithDefault(msg, 1, ""), data: jspb.Message.getFieldWithDefault(msg, 2, ""), number: jspb.Message.getFieldWithDefault(msg, 3, 0), balance: jspb.Message.getFieldWithDefault(msg, 4, 0), address: jspb.Message.getFieldWithDefault(msg, 5, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.AccountInfo} */ proto.pactus.AccountInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.AccountInfo; return proto.pactus.AccountInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.AccountInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.AccountInfo} */ proto.pactus.AccountInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setHash(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setData(value); break; case 3: var value = /** @type {number} */ (reader.readInt32()); msg.setNumber(value); break; case 4: var value = /** @type {number} */ (reader.readInt64()); msg.setBalance(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.AccountInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.AccountInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.AccountInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.AccountInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHash(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getData(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getNumber(); if (f !== 0) { writer.writeInt32( 3, f ); } f = message.getBalance(); if (f !== 0) { writer.writeInt64( 4, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 5, f ); } }; /** * optional string hash = 1; * @return {string} */ proto.pactus.AccountInfo.prototype.getHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.AccountInfo} returns this */ proto.pactus.AccountInfo.prototype.setHash = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string data = 2; * @return {string} */ proto.pactus.AccountInfo.prototype.getData = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.AccountInfo} returns this */ proto.pactus.AccountInfo.prototype.setData = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int32 number = 3; * @return {number} */ proto.pactus.AccountInfo.prototype.getNumber = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.AccountInfo} returns this */ proto.pactus.AccountInfo.prototype.setNumber = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * optional int64 balance = 4; * @return {number} */ proto.pactus.AccountInfo.prototype.getBalance = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.AccountInfo} returns this */ proto.pactus.AccountInfo.prototype.setBalance = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional string address = 5; * @return {string} */ proto.pactus.AccountInfo.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.AccountInfo} returns this */ proto.pactus.AccountInfo.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.BlockHeaderInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.BlockHeaderInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.BlockHeaderInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.BlockHeaderInfo.toObject = function(includeInstance, msg) { var f, obj = { version: jspb.Message.getFieldWithDefault(msg, 1, 0), prevBlockHash: jspb.Message.getFieldWithDefault(msg, 2, ""), stateRoot: jspb.Message.getFieldWithDefault(msg, 3, ""), sortitionSeed: jspb.Message.getFieldWithDefault(msg, 4, ""), proposerAddress: jspb.Message.getFieldWithDefault(msg, 5, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.BlockHeaderInfo} */ proto.pactus.BlockHeaderInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.BlockHeaderInfo; return proto.pactus.BlockHeaderInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.BlockHeaderInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.BlockHeaderInfo} */ proto.pactus.BlockHeaderInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt32()); msg.setVersion(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPrevBlockHash(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setStateRoot(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSortitionSeed(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setProposerAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.BlockHeaderInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.BlockHeaderInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.BlockHeaderInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.BlockHeaderInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getVersion(); if (f !== 0) { writer.writeInt32( 1, f ); } f = message.getPrevBlockHash(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getStateRoot(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getSortitionSeed(); if (f.length > 0) { writer.writeString( 4, f ); } f = message.getProposerAddress(); if (f.length > 0) { writer.writeString( 5, f ); } }; /** * optional int32 version = 1; * @return {number} */ proto.pactus.BlockHeaderInfo.prototype.getVersion = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.BlockHeaderInfo} returns this */ proto.pactus.BlockHeaderInfo.prototype.setVersion = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string prev_block_hash = 2; * @return {string} */ proto.pactus.BlockHeaderInfo.prototype.getPrevBlockHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.BlockHeaderInfo} returns this */ proto.pactus.BlockHeaderInfo.prototype.setPrevBlockHash = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string state_root = 3; * @return {string} */ proto.pactus.BlockHeaderInfo.prototype.getStateRoot = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.BlockHeaderInfo} returns this */ proto.pactus.BlockHeaderInfo.prototype.setStateRoot = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string sortition_seed = 4; * @return {string} */ proto.pactus.BlockHeaderInfo.prototype.getSortitionSeed = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.BlockHeaderInfo} returns this */ proto.pactus.BlockHeaderInfo.prototype.setSortitionSeed = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; /** * optional string proposer_address = 5; * @return {string} */ proto.pactus.BlockHeaderInfo.prototype.getProposerAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.BlockHeaderInfo} returns this */ proto.pactus.BlockHeaderInfo.prototype.setProposerAddress = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.CertificateInfo.repeatedFields_ = [3,4]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CertificateInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CertificateInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CertificateInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CertificateInfo.toObject = function(includeInstance, msg) { var f, obj = { hash: jspb.Message.getFieldWithDefault(msg, 1, ""), round: jspb.Message.getFieldWithDefault(msg, 2, 0), committersList: (f = jspb.Message.getRepeatedField(msg, 3)) == null ? undefined : f, absenteesList: (f = jspb.Message.getRepeatedField(msg, 4)) == null ? undefined : f, signature: jspb.Message.getFieldWithDefault(msg, 5, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CertificateInfo} */ proto.pactus.CertificateInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CertificateInfo; return proto.pactus.CertificateInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CertificateInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CertificateInfo} */ proto.pactus.CertificateInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setHash(value); break; case 2: var value = /** @type {number} */ (reader.readInt32()); msg.setRound(value); break; case 3: reader.readPackableInt32Into(msg.getCommittersList()); break; case 4: reader.readPackableInt32Into(msg.getAbsenteesList()); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CertificateInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CertificateInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CertificateInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CertificateInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHash(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getRound(); if (f !== 0) { writer.writeInt32( 2, f ); } f = message.getCommittersList(); if (f.length > 0) { writer.writePackedInt32( 3, f ); } f = message.getAbsenteesList(); if (f.length > 0) { writer.writePackedInt32( 4, f ); } f = message.getSignature(); if (f.length > 0) { writer.writeString( 5, f ); } }; /** * optional string hash = 1; * @return {string} */ proto.pactus.CertificateInfo.prototype.getHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.setHash = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional int32 round = 2; * @return {number} */ proto.pactus.CertificateInfo.prototype.getRound = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.setRound = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * repeated int32 committers = 3; * @return {!Array} */ proto.pactus.CertificateInfo.prototype.getCommittersList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 3)); }; /** * @param {!Array} value * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.setCommittersList = function(value) { return jspb.Message.setField(this, 3, value || []); }; /** * @param {number} value * @param {number=} opt_index * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.addCommitters = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 3, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.clearCommittersList = function() { return this.setCommittersList([]); }; /** * repeated int32 absentees = 4; * @return {!Array} */ proto.pactus.CertificateInfo.prototype.getAbsenteesList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 4)); }; /** * @param {!Array} value * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.setAbsenteesList = function(value) { return jspb.Message.setField(this, 4, value || []); }; /** * @param {number} value * @param {number=} opt_index * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.addAbsentees = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 4, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.clearAbsenteesList = function() { return this.setAbsenteesList([]); }; /** * optional string signature = 5; * @return {string} */ proto.pactus.CertificateInfo.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.CertificateInfo} returns this */ proto.pactus.CertificateInfo.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.VoteInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.VoteInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.VoteInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.VoteInfo.toObject = function(includeInstance, msg) { var f, obj = { type: jspb.Message.getFieldWithDefault(msg, 1, 0), voter: jspb.Message.getFieldWithDefault(msg, 2, ""), blockHash: jspb.Message.getFieldWithDefault(msg, 3, ""), round: jspb.Message.getFieldWithDefault(msg, 4, 0), cpRound: jspb.Message.getFieldWithDefault(msg, 5, 0), cpValue: jspb.Message.getFieldWithDefault(msg, 6, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.VoteInfo} */ proto.pactus.VoteInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.VoteInfo; return proto.pactus.VoteInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.VoteInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.VoteInfo} */ proto.pactus.VoteInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {!proto.pactus.VoteType} */ (reader.readEnum()); msg.setType(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setVoter(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setBlockHash(value); break; case 4: var value = /** @type {number} */ (reader.readInt32()); msg.setRound(value); break; case 5: var value = /** @type {number} */ (reader.readInt32()); msg.setCpRound(value); break; case 6: var value = /** @type {number} */ (reader.readInt32()); msg.setCpValue(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.VoteInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.VoteInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.VoteInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.VoteInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getType(); if (f !== 0.0) { writer.writeEnum( 1, f ); } f = message.getVoter(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getBlockHash(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getRound(); if (f !== 0) { writer.writeInt32( 4, f ); } f = message.getCpRound(); if (f !== 0) { writer.writeInt32( 5, f ); } f = message.getCpValue(); if (f !== 0) { writer.writeInt32( 6, f ); } }; /** * optional VoteType type = 1; * @return {!proto.pactus.VoteType} */ proto.pactus.VoteInfo.prototype.getType = function() { return /** @type {!proto.pactus.VoteType} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {!proto.pactus.VoteType} value * @return {!proto.pactus.VoteInfo} returns this */ proto.pactus.VoteInfo.prototype.setType = function(value) { return jspb.Message.setProto3EnumField(this, 1, value); }; /** * optional string voter = 2; * @return {string} */ proto.pactus.VoteInfo.prototype.getVoter = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.VoteInfo} returns this */ proto.pactus.VoteInfo.prototype.setVoter = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string block_hash = 3; * @return {string} */ proto.pactus.VoteInfo.prototype.getBlockHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.VoteInfo} returns this */ proto.pactus.VoteInfo.prototype.setBlockHash = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional int32 round = 4; * @return {number} */ proto.pactus.VoteInfo.prototype.getRound = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.VoteInfo} returns this */ proto.pactus.VoteInfo.prototype.setRound = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int32 cp_round = 5; * @return {number} */ proto.pactus.VoteInfo.prototype.getCpRound = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.VoteInfo} returns this */ proto.pactus.VoteInfo.prototype.setCpRound = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * optional int32 cp_value = 6; * @return {number} */ proto.pactus.VoteInfo.prototype.getCpValue = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.VoteInfo} returns this */ proto.pactus.VoteInfo.prototype.setCpValue = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.ConsensusInfo.repeatedFields_ = [5]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ConsensusInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ConsensusInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ConsensusInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ConsensusInfo.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, ""), active: jspb.Message.getBooleanFieldWithDefault(msg, 2, false), height: jspb.Message.getFieldWithDefault(msg, 3, 0), round: jspb.Message.getFieldWithDefault(msg, 4, 0), votesList: jspb.Message.toObjectList(msg.getVotesList(), proto.pactus.VoteInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ConsensusInfo} */ proto.pactus.ConsensusInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ConsensusInfo; return proto.pactus.ConsensusInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ConsensusInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ConsensusInfo} */ proto.pactus.ConsensusInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 2: var value = /** @type {boolean} */ (reader.readBool()); msg.setActive(value); break; case 3: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; case 4: var value = /** @type {number} */ (reader.readInt32()); msg.setRound(value); break; case 5: var value = new proto.pactus.VoteInfo; reader.readMessage(value,proto.pactus.VoteInfo.deserializeBinaryFromReader); msg.addVotes(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ConsensusInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ConsensusInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ConsensusInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ConsensusInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getActive(); if (f) { writer.writeBool( 2, f ); } f = message.getHeight(); if (f !== 0) { writer.writeUint32( 3, f ); } f = message.getRound(); if (f !== 0) { writer.writeInt32( 4, f ); } f = message.getVotesList(); if (f.length > 0) { writer.writeRepeatedMessage( 5, f, proto.pactus.VoteInfo.serializeBinaryToWriter ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.ConsensusInfo.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ConsensusInfo} returns this */ proto.pactus.ConsensusInfo.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional bool active = 2; * @return {boolean} */ proto.pactus.ConsensusInfo.prototype.getActive = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); }; /** * @param {boolean} value * @return {!proto.pactus.ConsensusInfo} returns this */ proto.pactus.ConsensusInfo.prototype.setActive = function(value) { return jspb.Message.setProto3BooleanField(this, 2, value); }; /** * optional uint32 height = 3; * @return {number} */ proto.pactus.ConsensusInfo.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.ConsensusInfo} returns this */ proto.pactus.ConsensusInfo.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * optional int32 round = 4; * @return {number} */ proto.pactus.ConsensusInfo.prototype.getRound = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.ConsensusInfo} returns this */ proto.pactus.ConsensusInfo.prototype.setRound = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * repeated VoteInfo votes = 5; * @return {!Array} */ proto.pactus.ConsensusInfo.prototype.getVotesList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.VoteInfo, 5)); }; /** * @param {!Array} value * @return {!proto.pactus.ConsensusInfo} returns this */ proto.pactus.ConsensusInfo.prototype.setVotesList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 5, value); }; /** * @param {!proto.pactus.VoteInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.VoteInfo} */ proto.pactus.ConsensusInfo.prototype.addVotes = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 5, opt_value, proto.pactus.VoteInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.ConsensusInfo} returns this */ proto.pactus.ConsensusInfo.prototype.clearVotesList = function() { return this.setVotesList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ProposalInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ProposalInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ProposalInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ProposalInfo.toObject = function(includeInstance, msg) { var f, obj = { height: jspb.Message.getFieldWithDefault(msg, 1, 0), round: jspb.Message.getFieldWithDefault(msg, 2, 0), blockData: jspb.Message.getFieldWithDefault(msg, 3, ""), signature: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ProposalInfo} */ proto.pactus.ProposalInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ProposalInfo; return proto.pactus.ProposalInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ProposalInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ProposalInfo} */ proto.pactus.ProposalInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; case 2: var value = /** @type {number} */ (reader.readInt32()); msg.setRound(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setBlockData(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ProposalInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ProposalInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ProposalInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ProposalInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getRound(); if (f !== 0) { writer.writeInt32( 2, f ); } f = message.getBlockData(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getSignature(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional uint32 height = 1; * @return {number} */ proto.pactus.ProposalInfo.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.ProposalInfo} returns this */ proto.pactus.ProposalInfo.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional int32 round = 2; * @return {number} */ proto.pactus.ProposalInfo.prototype.getRound = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.ProposalInfo} returns this */ proto.pactus.ProposalInfo.prototype.setRound = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * optional string block_data = 3; * @return {string} */ proto.pactus.ProposalInfo.prototype.getBlockData = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.ProposalInfo} returns this */ proto.pactus.ProposalInfo.prototype.setBlockData = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string signature = 4; * @return {string} */ proto.pactus.ProposalInfo.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.ProposalInfo} returns this */ proto.pactus.ProposalInfo.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; /** * @enum {number} */ proto.pactus.BlockVerbosity = { BLOCK_VERBOSITY_DATA: 0, BLOCK_VERBOSITY_INFO: 1, BLOCK_VERBOSITY_TRANSACTIONS: 2 }; /** * @enum {number} */ proto.pactus.VoteType = { VOTE_TYPE_UNSPECIFIED: 0, VOTE_TYPE_PREPARE: 1, VOTE_TYPE_PRECOMMIT: 2, VOTE_TYPE_CP_PRE_VOTE: 3, VOTE_TYPE_CP_MAIN_VOTE: 4, VOTE_TYPE_CP_DECIDED: 5 }; goog.object.extend(exports, proto.pactus); ================================================ FILE: www/grpc/gen/js/network_grpc_pb.js ================================================ // GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('@grpc/grpc-js'); var network_pb = require('./network_pb.js'); function serialize_pactus_GetNetworkInfoRequest(arg) { if (!(arg instanceof network_pb.GetNetworkInfoRequest)) { throw new Error('Expected argument of type pactus.GetNetworkInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetNetworkInfoRequest(buffer_arg) { return network_pb.GetNetworkInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetNetworkInfoResponse(arg) { if (!(arg instanceof network_pb.GetNetworkInfoResponse)) { throw new Error('Expected argument of type pactus.GetNetworkInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetNetworkInfoResponse(buffer_arg) { return network_pb.GetNetworkInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetNodeInfoRequest(arg) { if (!(arg instanceof network_pb.GetNodeInfoRequest)) { throw new Error('Expected argument of type pactus.GetNodeInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetNodeInfoRequest(buffer_arg) { return network_pb.GetNodeInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetNodeInfoResponse(arg) { if (!(arg instanceof network_pb.GetNodeInfoResponse)) { throw new Error('Expected argument of type pactus.GetNodeInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetNodeInfoResponse(buffer_arg) { return network_pb.GetNodeInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListPeersRequest(arg) { if (!(arg instanceof network_pb.ListPeersRequest)) { throw new Error('Expected argument of type pactus.ListPeersRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListPeersRequest(buffer_arg) { return network_pb.ListPeersRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListPeersResponse(arg) { if (!(arg instanceof network_pb.ListPeersResponse)) { throw new Error('Expected argument of type pactus.ListPeersResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListPeersResponse(buffer_arg) { return network_pb.ListPeersResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_PingRequest(arg) { if (!(arg instanceof network_pb.PingRequest)) { throw new Error('Expected argument of type pactus.PingRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_PingRequest(buffer_arg) { return network_pb.PingRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_PingResponse(arg) { if (!(arg instanceof network_pb.PingResponse)) { throw new Error('Expected argument of type pactus.PingResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_PingResponse(buffer_arg) { return network_pb.PingResponse.deserializeBinary(new Uint8Array(buffer_arg)); } // Network service provides RPCs for retrieving information about the network. var NetworkService = exports.NetworkService = { // GetNetworkInfo retrieves information about the overall network. getNetworkInfo: { path: '/pactus.Network/GetNetworkInfo', requestStream: false, responseStream: false, requestType: network_pb.GetNetworkInfoRequest, responseType: network_pb.GetNetworkInfoResponse, requestSerialize: serialize_pactus_GetNetworkInfoRequest, requestDeserialize: deserialize_pactus_GetNetworkInfoRequest, responseSerialize: serialize_pactus_GetNetworkInfoResponse, responseDeserialize: deserialize_pactus_GetNetworkInfoResponse, }, // ListPeers lists all peers in the network. listPeers: { path: '/pactus.Network/ListPeers', requestStream: false, responseStream: false, requestType: network_pb.ListPeersRequest, responseType: network_pb.ListPeersResponse, requestSerialize: serialize_pactus_ListPeersRequest, requestDeserialize: deserialize_pactus_ListPeersRequest, responseSerialize: serialize_pactus_ListPeersResponse, responseDeserialize: deserialize_pactus_ListPeersResponse, }, // GetNodeInfo retrieves information about a specific node in the network. getNodeInfo: { path: '/pactus.Network/GetNodeInfo', requestStream: false, responseStream: false, requestType: network_pb.GetNodeInfoRequest, responseType: network_pb.GetNodeInfoResponse, requestSerialize: serialize_pactus_GetNodeInfoRequest, requestDeserialize: deserialize_pactus_GetNodeInfoRequest, responseSerialize: serialize_pactus_GetNodeInfoResponse, responseDeserialize: deserialize_pactus_GetNodeInfoResponse, }, // Ping provides a simple connectivity test and latency measurement. ping: { path: '/pactus.Network/Ping', requestStream: false, responseStream: false, requestType: network_pb.PingRequest, responseType: network_pb.PingResponse, requestSerialize: serialize_pactus_PingRequest, requestDeserialize: deserialize_pactus_PingRequest, responseSerialize: serialize_pactus_PingResponse, responseDeserialize: deserialize_pactus_PingResponse, }, }; exports.NetworkClient = grpc.makeGenericClientConstructor(NetworkService, 'Network'); ================================================ FILE: www/grpc/gen/js/network_grpc_web_pb.js ================================================ /** * @fileoverview gRPC-Web generated client stub for pactus * @enhanceable * @public */ // Code generated by protoc-gen-grpc-web. DO NOT EDIT. // versions: // protoc-gen-grpc-web v2.0.2 // protoc v0.0.0 // source: network.proto /* eslint-disable */ // @ts-nocheck const grpc = {}; grpc.web = require('grpc-web'); const proto = {}; proto.pactus = require('./network_pb.js'); /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.NetworkClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.NetworkPromiseClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetNetworkInfoRequest, * !proto.pactus.GetNetworkInfoResponse>} */ const methodDescriptor_Network_GetNetworkInfo = new grpc.web.MethodDescriptor( '/pactus.Network/GetNetworkInfo', grpc.web.MethodType.UNARY, proto.pactus.GetNetworkInfoRequest, proto.pactus.GetNetworkInfoResponse, /** * @param {!proto.pactus.GetNetworkInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetNetworkInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetNetworkInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetNetworkInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.NetworkClient.prototype.getNetworkInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Network/GetNetworkInfo', request, metadata || {}, methodDescriptor_Network_GetNetworkInfo, callback); }; /** * @param {!proto.pactus.GetNetworkInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.NetworkPromiseClient.prototype.getNetworkInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Network/GetNetworkInfo', request, metadata || {}, methodDescriptor_Network_GetNetworkInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.ListPeersRequest, * !proto.pactus.ListPeersResponse>} */ const methodDescriptor_Network_ListPeers = new grpc.web.MethodDescriptor( '/pactus.Network/ListPeers', grpc.web.MethodType.UNARY, proto.pactus.ListPeersRequest, proto.pactus.ListPeersResponse, /** * @param {!proto.pactus.ListPeersRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.ListPeersResponse.deserializeBinary ); /** * @param {!proto.pactus.ListPeersRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.ListPeersResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.NetworkClient.prototype.listPeers = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Network/ListPeers', request, metadata || {}, methodDescriptor_Network_ListPeers, callback); }; /** * @param {!proto.pactus.ListPeersRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.NetworkPromiseClient.prototype.listPeers = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Network/ListPeers', request, metadata || {}, methodDescriptor_Network_ListPeers); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetNodeInfoRequest, * !proto.pactus.GetNodeInfoResponse>} */ const methodDescriptor_Network_GetNodeInfo = new grpc.web.MethodDescriptor( '/pactus.Network/GetNodeInfo', grpc.web.MethodType.UNARY, proto.pactus.GetNodeInfoRequest, proto.pactus.GetNodeInfoResponse, /** * @param {!proto.pactus.GetNodeInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetNodeInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetNodeInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetNodeInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.NetworkClient.prototype.getNodeInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Network/GetNodeInfo', request, metadata || {}, methodDescriptor_Network_GetNodeInfo, callback); }; /** * @param {!proto.pactus.GetNodeInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.NetworkPromiseClient.prototype.getNodeInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Network/GetNodeInfo', request, metadata || {}, methodDescriptor_Network_GetNodeInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.PingRequest, * !proto.pactus.PingResponse>} */ const methodDescriptor_Network_Ping = new grpc.web.MethodDescriptor( '/pactus.Network/Ping', grpc.web.MethodType.UNARY, proto.pactus.PingRequest, proto.pactus.PingResponse, /** * @param {!proto.pactus.PingRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.PingResponse.deserializeBinary ); /** * @param {!proto.pactus.PingRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.PingResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.NetworkClient.prototype.ping = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Network/Ping', request, metadata || {}, methodDescriptor_Network_Ping, callback); }; /** * @param {!proto.pactus.PingRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.NetworkPromiseClient.prototype.ping = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Network/Ping', request, metadata || {}, methodDescriptor_Network_Ping); }; module.exports = proto.pactus; ================================================ FILE: www/grpc/gen/js/network_pb.js ================================================ // source: network.proto /** * @fileoverview * @enhanceable * @suppress {missingRequire} reports error on implicit type usages. * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var global = globalThis; goog.exportSymbol('proto.pactus.ConnectionInfo', null, global); goog.exportSymbol('proto.pactus.CounterInfo', null, global); goog.exportSymbol('proto.pactus.Direction', null, global); goog.exportSymbol('proto.pactus.GetNetworkInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetNetworkInfoResponse', null, global); goog.exportSymbol('proto.pactus.GetNodeInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetNodeInfoResponse', null, global); goog.exportSymbol('proto.pactus.ListPeersRequest', null, global); goog.exportSymbol('proto.pactus.ListPeersResponse', null, global); goog.exportSymbol('proto.pactus.MetricInfo', null, global); goog.exportSymbol('proto.pactus.PeerInfo', null, global); goog.exportSymbol('proto.pactus.PingRequest', null, global); goog.exportSymbol('proto.pactus.PingResponse', null, global); goog.exportSymbol('proto.pactus.ZMQPublisherInfo', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetNetworkInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetNetworkInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetNetworkInfoRequest.displayName = 'proto.pactus.GetNetworkInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetNetworkInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetNetworkInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetNetworkInfoResponse.displayName = 'proto.pactus.GetNetworkInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListPeersRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ListPeersRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListPeersRequest.displayName = 'proto.pactus.ListPeersRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListPeersResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.ListPeersResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.ListPeersResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListPeersResponse.displayName = 'proto.pactus.ListPeersResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetNodeInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetNodeInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetNodeInfoRequest.displayName = 'proto.pactus.GetNodeInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetNodeInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetNodeInfoResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.GetNodeInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetNodeInfoResponse.displayName = 'proto.pactus.GetNodeInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ZMQPublisherInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ZMQPublisherInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ZMQPublisherInfo.displayName = 'proto.pactus.ZMQPublisherInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PeerInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.PeerInfo.repeatedFields_, null); }; goog.inherits(proto.pactus.PeerInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PeerInfo.displayName = 'proto.pactus.PeerInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ConnectionInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ConnectionInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ConnectionInfo.displayName = 'proto.pactus.ConnectionInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.MetricInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.MetricInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.MetricInfo.displayName = 'proto.pactus.MetricInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CounterInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CounterInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CounterInfo.displayName = 'proto.pactus.CounterInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PingRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PingRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PingRequest.displayName = 'proto.pactus.PingRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PingResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PingResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PingResponse.displayName = 'proto.pactus.PingResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetNetworkInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetNetworkInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetNetworkInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNetworkInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetNetworkInfoRequest} */ proto.pactus.GetNetworkInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetNetworkInfoRequest; return proto.pactus.GetNetworkInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetNetworkInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetNetworkInfoRequest} */ proto.pactus.GetNetworkInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetNetworkInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetNetworkInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetNetworkInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNetworkInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetNetworkInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetNetworkInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetNetworkInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNetworkInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { networkName: jspb.Message.getFieldWithDefault(msg, 1, ""), connectedPeersCount: jspb.Message.getFieldWithDefault(msg, 2, 0), metricInfo: (f = msg.getMetricInfo()) && proto.pactus.MetricInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetNetworkInfoResponse} */ proto.pactus.GetNetworkInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetNetworkInfoResponse; return proto.pactus.GetNetworkInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetNetworkInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetNetworkInfoResponse} */ proto.pactus.GetNetworkInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setNetworkName(value); break; case 2: var value = /** @type {number} */ (reader.readUint32()); msg.setConnectedPeersCount(value); break; case 4: var value = new proto.pactus.MetricInfo; reader.readMessage(value,proto.pactus.MetricInfo.deserializeBinaryFromReader); msg.setMetricInfo(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetNetworkInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetNetworkInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetNetworkInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNetworkInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getNetworkName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getConnectedPeersCount(); if (f !== 0) { writer.writeUint32( 2, f ); } f = message.getMetricInfo(); if (f != null) { writer.writeMessage( 4, f, proto.pactus.MetricInfo.serializeBinaryToWriter ); } }; /** * optional string network_name = 1; * @return {string} */ proto.pactus.GetNetworkInfoResponse.prototype.getNetworkName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNetworkInfoResponse} returns this */ proto.pactus.GetNetworkInfoResponse.prototype.setNetworkName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional uint32 connected_peers_count = 2; * @return {number} */ proto.pactus.GetNetworkInfoResponse.prototype.getConnectedPeersCount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetNetworkInfoResponse} returns this */ proto.pactus.GetNetworkInfoResponse.prototype.setConnectedPeersCount = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * optional MetricInfo metric_info = 4; * @return {?proto.pactus.MetricInfo} */ proto.pactus.GetNetworkInfoResponse.prototype.getMetricInfo = function() { return /** @type{?proto.pactus.MetricInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.MetricInfo, 4)); }; /** * @param {?proto.pactus.MetricInfo|undefined} value * @return {!proto.pactus.GetNetworkInfoResponse} returns this */ proto.pactus.GetNetworkInfoResponse.prototype.setMetricInfo = function(value) { return jspb.Message.setWrapperField(this, 4, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetNetworkInfoResponse} returns this */ proto.pactus.GetNetworkInfoResponse.prototype.clearMetricInfo = function() { return this.setMetricInfo(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetNetworkInfoResponse.prototype.hasMetricInfo = function() { return jspb.Message.getField(this, 4) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListPeersRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListPeersRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListPeersRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListPeersRequest.toObject = function(includeInstance, msg) { var f, obj = { includeDisconnected: jspb.Message.getBooleanFieldWithDefault(msg, 1, false) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListPeersRequest} */ proto.pactus.ListPeersRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListPeersRequest; return proto.pactus.ListPeersRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListPeersRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListPeersRequest} */ proto.pactus.ListPeersRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {boolean} */ (reader.readBool()); msg.setIncludeDisconnected(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListPeersRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListPeersRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListPeersRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListPeersRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getIncludeDisconnected(); if (f) { writer.writeBool( 1, f ); } }; /** * optional bool include_disconnected = 1; * @return {boolean} */ proto.pactus.ListPeersRequest.prototype.getIncludeDisconnected = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); }; /** * @param {boolean} value * @return {!proto.pactus.ListPeersRequest} returns this */ proto.pactus.ListPeersRequest.prototype.setIncludeDisconnected = function(value) { return jspb.Message.setProto3BooleanField(this, 1, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.ListPeersResponse.repeatedFields_ = [1]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListPeersResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListPeersResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListPeersResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListPeersResponse.toObject = function(includeInstance, msg) { var f, obj = { peersList: jspb.Message.toObjectList(msg.getPeersList(), proto.pactus.PeerInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListPeersResponse} */ proto.pactus.ListPeersResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListPeersResponse; return proto.pactus.ListPeersResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListPeersResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListPeersResponse} */ proto.pactus.ListPeersResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.pactus.PeerInfo; reader.readMessage(value,proto.pactus.PeerInfo.deserializeBinaryFromReader); msg.addPeers(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListPeersResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListPeersResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListPeersResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListPeersResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPeersList(); if (f.length > 0) { writer.writeRepeatedMessage( 1, f, proto.pactus.PeerInfo.serializeBinaryToWriter ); } }; /** * repeated PeerInfo peers = 1; * @return {!Array} */ proto.pactus.ListPeersResponse.prototype.getPeersList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.PeerInfo, 1)); }; /** * @param {!Array} value * @return {!proto.pactus.ListPeersResponse} returns this */ proto.pactus.ListPeersResponse.prototype.setPeersList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 1, value); }; /** * @param {!proto.pactus.PeerInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.PeerInfo} */ proto.pactus.ListPeersResponse.prototype.addPeers = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.pactus.PeerInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.ListPeersResponse} returns this */ proto.pactus.ListPeersResponse.prototype.clearPeersList = function() { return this.setPeersList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetNodeInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetNodeInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetNodeInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNodeInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetNodeInfoRequest} */ proto.pactus.GetNodeInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetNodeInfoRequest; return proto.pactus.GetNodeInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetNodeInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetNodeInfoRequest} */ proto.pactus.GetNodeInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetNodeInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetNodeInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetNodeInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNodeInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetNodeInfoResponse.repeatedFields_ = [8,9,15]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetNodeInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetNodeInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetNodeInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNodeInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { moniker: jspb.Message.getFieldWithDefault(msg, 1, ""), agent: jspb.Message.getFieldWithDefault(msg, 2, ""), peerId: jspb.Message.getFieldWithDefault(msg, 3, ""), startedAt: jspb.Message.getFieldWithDefault(msg, 4, 0), reachability: jspb.Message.getFieldWithDefault(msg, 5, ""), services: jspb.Message.getFieldWithDefault(msg, 6, 0), servicesNames: jspb.Message.getFieldWithDefault(msg, 7, ""), localAddrsList: (f = jspb.Message.getRepeatedField(msg, 8)) == null ? undefined : f, protocolsList: (f = jspb.Message.getRepeatedField(msg, 9)) == null ? undefined : f, clockOffset: jspb.Message.getFloatingPointFieldWithDefault(msg, 13, 0.0), connectionInfo: (f = msg.getConnectionInfo()) && proto.pactus.ConnectionInfo.toObject(includeInstance, f), zmqPublishersList: jspb.Message.toObjectList(msg.getZmqPublishersList(), proto.pactus.ZMQPublisherInfo.toObject, includeInstance), currentTime: jspb.Message.getFieldWithDefault(msg, 16, 0), networkName: jspb.Message.getFieldWithDefault(msg, 17, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetNodeInfoResponse} */ proto.pactus.GetNodeInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetNodeInfoResponse; return proto.pactus.GetNodeInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetNodeInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetNodeInfoResponse} */ proto.pactus.GetNodeInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMoniker(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAgent(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPeerId(value); break; case 4: var value = /** @type {number} */ (reader.readUint64()); msg.setStartedAt(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReachability(value); break; case 6: var value = /** @type {number} */ (reader.readInt32()); msg.setServices(value); break; case 7: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setServicesNames(value); break; case 8: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addLocalAddrs(value); break; case 9: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addProtocols(value); break; case 13: var value = /** @type {number} */ (reader.readDouble()); msg.setClockOffset(value); break; case 14: var value = new proto.pactus.ConnectionInfo; reader.readMessage(value,proto.pactus.ConnectionInfo.deserializeBinaryFromReader); msg.setConnectionInfo(value); break; case 15: var value = new proto.pactus.ZMQPublisherInfo; reader.readMessage(value,proto.pactus.ZMQPublisherInfo.deserializeBinaryFromReader); msg.addZmqPublishers(value); break; case 16: var value = /** @type {number} */ (reader.readUint64()); msg.setCurrentTime(value); break; case 17: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setNetworkName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetNodeInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetNodeInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetNodeInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNodeInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getMoniker(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAgent(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getPeerId(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getStartedAt(); if (f !== 0) { writer.writeUint64( 4, f ); } f = message.getReachability(); if (f.length > 0) { writer.writeString( 5, f ); } f = message.getServices(); if (f !== 0) { writer.writeInt32( 6, f ); } f = message.getServicesNames(); if (f.length > 0) { writer.writeString( 7, f ); } f = message.getLocalAddrsList(); if (f.length > 0) { writer.writeRepeatedString( 8, f ); } f = message.getProtocolsList(); if (f.length > 0) { writer.writeRepeatedString( 9, f ); } f = message.getClockOffset(); if (f !== 0.0) { writer.writeDouble( 13, f ); } f = message.getConnectionInfo(); if (f != null) { writer.writeMessage( 14, f, proto.pactus.ConnectionInfo.serializeBinaryToWriter ); } f = message.getZmqPublishersList(); if (f.length > 0) { writer.writeRepeatedMessage( 15, f, proto.pactus.ZMQPublisherInfo.serializeBinaryToWriter ); } f = message.getCurrentTime(); if (f !== 0) { writer.writeUint64( 16, f ); } f = message.getNetworkName(); if (f.length > 0) { writer.writeString( 17, f ); } }; /** * optional string moniker = 1; * @return {string} */ proto.pactus.GetNodeInfoResponse.prototype.getMoniker = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setMoniker = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string agent = 2; * @return {string} */ proto.pactus.GetNodeInfoResponse.prototype.getAgent = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setAgent = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string peer_id = 3; * @return {string} */ proto.pactus.GetNodeInfoResponse.prototype.getPeerId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setPeerId = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional uint64 started_at = 4; * @return {number} */ proto.pactus.GetNodeInfoResponse.prototype.getStartedAt = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setStartedAt = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional string reachability = 5; * @return {string} */ proto.pactus.GetNodeInfoResponse.prototype.getReachability = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setReachability = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; /** * optional int32 services = 6; * @return {number} */ proto.pactus.GetNodeInfoResponse.prototype.getServices = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setServices = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional string services_names = 7; * @return {string} */ proto.pactus.GetNodeInfoResponse.prototype.getServicesNames = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 7, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setServicesNames = function(value) { return jspb.Message.setProto3StringField(this, 7, value); }; /** * repeated string local_addrs = 8; * @return {!Array} */ proto.pactus.GetNodeInfoResponse.prototype.getLocalAddrsList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 8)); }; /** * @param {!Array} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setLocalAddrsList = function(value) { return jspb.Message.setField(this, 8, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.addLocalAddrs = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 8, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.clearLocalAddrsList = function() { return this.setLocalAddrsList([]); }; /** * repeated string protocols = 9; * @return {!Array} */ proto.pactus.GetNodeInfoResponse.prototype.getProtocolsList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 9)); }; /** * @param {!Array} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setProtocolsList = function(value) { return jspb.Message.setField(this, 9, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.addProtocols = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 9, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.clearProtocolsList = function() { return this.setProtocolsList([]); }; /** * optional double clock_offset = 13; * @return {number} */ proto.pactus.GetNodeInfoResponse.prototype.getClockOffset = function() { return /** @type {number} */ (jspb.Message.getFloatingPointFieldWithDefault(this, 13, 0.0)); }; /** * @param {number} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setClockOffset = function(value) { return jspb.Message.setProto3FloatField(this, 13, value); }; /** * optional ConnectionInfo connection_info = 14; * @return {?proto.pactus.ConnectionInfo} */ proto.pactus.GetNodeInfoResponse.prototype.getConnectionInfo = function() { return /** @type{?proto.pactus.ConnectionInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.ConnectionInfo, 14)); }; /** * @param {?proto.pactus.ConnectionInfo|undefined} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setConnectionInfo = function(value) { return jspb.Message.setWrapperField(this, 14, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.clearConnectionInfo = function() { return this.setConnectionInfo(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetNodeInfoResponse.prototype.hasConnectionInfo = function() { return jspb.Message.getField(this, 14) != null; }; /** * repeated ZMQPublisherInfo zmq_publishers = 15; * @return {!Array} */ proto.pactus.GetNodeInfoResponse.prototype.getZmqPublishersList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.ZMQPublisherInfo, 15)); }; /** * @param {!Array} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setZmqPublishersList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 15, value); }; /** * @param {!proto.pactus.ZMQPublisherInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.ZMQPublisherInfo} */ proto.pactus.GetNodeInfoResponse.prototype.addZmqPublishers = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 15, opt_value, proto.pactus.ZMQPublisherInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.clearZmqPublishersList = function() { return this.setZmqPublishersList([]); }; /** * optional uint64 current_time = 16; * @return {number} */ proto.pactus.GetNodeInfoResponse.prototype.getCurrentTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 16, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setCurrentTime = function(value) { return jspb.Message.setProto3IntField(this, 16, value); }; /** * optional string network_name = 17; * @return {string} */ proto.pactus.GetNodeInfoResponse.prototype.getNetworkName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 17, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNodeInfoResponse} returns this */ proto.pactus.GetNodeInfoResponse.prototype.setNetworkName = function(value) { return jspb.Message.setProto3StringField(this, 17, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ZMQPublisherInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ZMQPublisherInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ZMQPublisherInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ZMQPublisherInfo.toObject = function(includeInstance, msg) { var f, obj = { topic: jspb.Message.getFieldWithDefault(msg, 1, ""), address: jspb.Message.getFieldWithDefault(msg, 2, ""), hwm: jspb.Message.getFieldWithDefault(msg, 3, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ZMQPublisherInfo} */ proto.pactus.ZMQPublisherInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ZMQPublisherInfo; return proto.pactus.ZMQPublisherInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ZMQPublisherInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ZMQPublisherInfo} */ proto.pactus.ZMQPublisherInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setTopic(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 3: var value = /** @type {number} */ (reader.readInt32()); msg.setHwm(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ZMQPublisherInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ZMQPublisherInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ZMQPublisherInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ZMQPublisherInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getTopic(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getHwm(); if (f !== 0) { writer.writeInt32( 3, f ); } }; /** * optional string topic = 1; * @return {string} */ proto.pactus.ZMQPublisherInfo.prototype.getTopic = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ZMQPublisherInfo} returns this */ proto.pactus.ZMQPublisherInfo.prototype.setTopic = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string address = 2; * @return {string} */ proto.pactus.ZMQPublisherInfo.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.ZMQPublisherInfo} returns this */ proto.pactus.ZMQPublisherInfo.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int32 hwm = 3; * @return {number} */ proto.pactus.ZMQPublisherInfo.prototype.getHwm = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.ZMQPublisherInfo} returns this */ proto.pactus.ZMQPublisherInfo.prototype.setHwm = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.PeerInfo.repeatedFields_ = [5,6,14]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PeerInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PeerInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PeerInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PeerInfo.toObject = function(includeInstance, msg) { var f, obj = { status: jspb.Message.getFieldWithDefault(msg, 1, 0), moniker: jspb.Message.getFieldWithDefault(msg, 2, ""), agent: jspb.Message.getFieldWithDefault(msg, 3, ""), peerId: jspb.Message.getFieldWithDefault(msg, 4, ""), consensusKeysList: (f = jspb.Message.getRepeatedField(msg, 5)) == null ? undefined : f, consensusAddressesList: (f = jspb.Message.getRepeatedField(msg, 6)) == null ? undefined : f, services: jspb.Message.getFieldWithDefault(msg, 7, 0), lastBlockHash: jspb.Message.getFieldWithDefault(msg, 8, ""), height: jspb.Message.getFieldWithDefault(msg, 9, 0), lastSent: jspb.Message.getFieldWithDefault(msg, 10, 0), lastReceived: jspb.Message.getFieldWithDefault(msg, 11, 0), address: jspb.Message.getFieldWithDefault(msg, 12, ""), direction: jspb.Message.getFieldWithDefault(msg, 13, 0), protocolsList: (f = jspb.Message.getRepeatedField(msg, 14)) == null ? undefined : f, totalSessions: jspb.Message.getFieldWithDefault(msg, 15, 0), completedSessions: jspb.Message.getFieldWithDefault(msg, 16, 0), metricInfo: (f = msg.getMetricInfo()) && proto.pactus.MetricInfo.toObject(includeInstance, f), outboundHelloSent: jspb.Message.getBooleanFieldWithDefault(msg, 18, false) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PeerInfo} */ proto.pactus.PeerInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PeerInfo; return proto.pactus.PeerInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PeerInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PeerInfo} */ proto.pactus.PeerInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt32()); msg.setStatus(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMoniker(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAgent(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPeerId(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addConsensusKeys(value); break; case 6: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addConsensusAddresses(value); break; case 7: var value = /** @type {number} */ (reader.readUint32()); msg.setServices(value); break; case 8: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setLastBlockHash(value); break; case 9: var value = /** @type {number} */ (reader.readUint32()); msg.setHeight(value); break; case 10: var value = /** @type {number} */ (reader.readInt64()); msg.setLastSent(value); break; case 11: var value = /** @type {number} */ (reader.readInt64()); msg.setLastReceived(value); break; case 12: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 13: var value = /** @type {!proto.pactus.Direction} */ (reader.readEnum()); msg.setDirection(value); break; case 14: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addProtocols(value); break; case 15: var value = /** @type {number} */ (reader.readInt32()); msg.setTotalSessions(value); break; case 16: var value = /** @type {number} */ (reader.readInt32()); msg.setCompletedSessions(value); break; case 17: var value = new proto.pactus.MetricInfo; reader.readMessage(value,proto.pactus.MetricInfo.deserializeBinaryFromReader); msg.setMetricInfo(value); break; case 18: var value = /** @type {boolean} */ (reader.readBool()); msg.setOutboundHelloSent(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PeerInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PeerInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PeerInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PeerInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getStatus(); if (f !== 0) { writer.writeInt32( 1, f ); } f = message.getMoniker(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAgent(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getPeerId(); if (f.length > 0) { writer.writeString( 4, f ); } f = message.getConsensusKeysList(); if (f.length > 0) { writer.writeRepeatedString( 5, f ); } f = message.getConsensusAddressesList(); if (f.length > 0) { writer.writeRepeatedString( 6, f ); } f = message.getServices(); if (f !== 0) { writer.writeUint32( 7, f ); } f = message.getLastBlockHash(); if (f.length > 0) { writer.writeString( 8, f ); } f = message.getHeight(); if (f !== 0) { writer.writeUint32( 9, f ); } f = message.getLastSent(); if (f !== 0) { writer.writeInt64( 10, f ); } f = message.getLastReceived(); if (f !== 0) { writer.writeInt64( 11, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 12, f ); } f = message.getDirection(); if (f !== 0.0) { writer.writeEnum( 13, f ); } f = message.getProtocolsList(); if (f.length > 0) { writer.writeRepeatedString( 14, f ); } f = message.getTotalSessions(); if (f !== 0) { writer.writeInt32( 15, f ); } f = message.getCompletedSessions(); if (f !== 0) { writer.writeInt32( 16, f ); } f = message.getMetricInfo(); if (f != null) { writer.writeMessage( 17, f, proto.pactus.MetricInfo.serializeBinaryToWriter ); } f = message.getOutboundHelloSent(); if (f) { writer.writeBool( 18, f ); } }; /** * optional int32 status = 1; * @return {number} */ proto.pactus.PeerInfo.prototype.getStatus = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setStatus = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string moniker = 2; * @return {string} */ proto.pactus.PeerInfo.prototype.getMoniker = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setMoniker = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string agent = 3; * @return {string} */ proto.pactus.PeerInfo.prototype.getAgent = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setAgent = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string peer_id = 4; * @return {string} */ proto.pactus.PeerInfo.prototype.getPeerId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setPeerId = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; /** * repeated string consensus_keys = 5; * @return {!Array} */ proto.pactus.PeerInfo.prototype.getConsensusKeysList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 5)); }; /** * @param {!Array} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setConsensusKeysList = function(value) { return jspb.Message.setField(this, 5, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.addConsensusKeys = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 5, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.clearConsensusKeysList = function() { return this.setConsensusKeysList([]); }; /** * repeated string consensus_addresses = 6; * @return {!Array} */ proto.pactus.PeerInfo.prototype.getConsensusAddressesList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 6)); }; /** * @param {!Array} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setConsensusAddressesList = function(value) { return jspb.Message.setField(this, 6, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.addConsensusAddresses = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 6, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.clearConsensusAddressesList = function() { return this.setConsensusAddressesList([]); }; /** * optional uint32 services = 7; * @return {number} */ proto.pactus.PeerInfo.prototype.getServices = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setServices = function(value) { return jspb.Message.setProto3IntField(this, 7, value); }; /** * optional string last_block_hash = 8; * @return {string} */ proto.pactus.PeerInfo.prototype.getLastBlockHash = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, "")); }; /** * @param {string} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setLastBlockHash = function(value) { return jspb.Message.setProto3StringField(this, 8, value); }; /** * optional uint32 height = 9; * @return {number} */ proto.pactus.PeerInfo.prototype.getHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 9, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setHeight = function(value) { return jspb.Message.setProto3IntField(this, 9, value); }; /** * optional int64 last_sent = 10; * @return {number} */ proto.pactus.PeerInfo.prototype.getLastSent = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 10, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setLastSent = function(value) { return jspb.Message.setProto3IntField(this, 10, value); }; /** * optional int64 last_received = 11; * @return {number} */ proto.pactus.PeerInfo.prototype.getLastReceived = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 11, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setLastReceived = function(value) { return jspb.Message.setProto3IntField(this, 11, value); }; /** * optional string address = 12; * @return {string} */ proto.pactus.PeerInfo.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 12, "")); }; /** * @param {string} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 12, value); }; /** * optional Direction direction = 13; * @return {!proto.pactus.Direction} */ proto.pactus.PeerInfo.prototype.getDirection = function() { return /** @type {!proto.pactus.Direction} */ (jspb.Message.getFieldWithDefault(this, 13, 0)); }; /** * @param {!proto.pactus.Direction} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setDirection = function(value) { return jspb.Message.setProto3EnumField(this, 13, value); }; /** * repeated string protocols = 14; * @return {!Array} */ proto.pactus.PeerInfo.prototype.getProtocolsList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 14)); }; /** * @param {!Array} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setProtocolsList = function(value) { return jspb.Message.setField(this, 14, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.addProtocols = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 14, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.clearProtocolsList = function() { return this.setProtocolsList([]); }; /** * optional int32 total_sessions = 15; * @return {number} */ proto.pactus.PeerInfo.prototype.getTotalSessions = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 15, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setTotalSessions = function(value) { return jspb.Message.setProto3IntField(this, 15, value); }; /** * optional int32 completed_sessions = 16; * @return {number} */ proto.pactus.PeerInfo.prototype.getCompletedSessions = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 16, 0)); }; /** * @param {number} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setCompletedSessions = function(value) { return jspb.Message.setProto3IntField(this, 16, value); }; /** * optional MetricInfo metric_info = 17; * @return {?proto.pactus.MetricInfo} */ proto.pactus.PeerInfo.prototype.getMetricInfo = function() { return /** @type{?proto.pactus.MetricInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.MetricInfo, 17)); }; /** * @param {?proto.pactus.MetricInfo|undefined} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setMetricInfo = function(value) { return jspb.Message.setWrapperField(this, 17, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.clearMetricInfo = function() { return this.setMetricInfo(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.PeerInfo.prototype.hasMetricInfo = function() { return jspb.Message.getField(this, 17) != null; }; /** * optional bool outbound_hello_sent = 18; * @return {boolean} */ proto.pactus.PeerInfo.prototype.getOutboundHelloSent = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 18, false)); }; /** * @param {boolean} value * @return {!proto.pactus.PeerInfo} returns this */ proto.pactus.PeerInfo.prototype.setOutboundHelloSent = function(value) { return jspb.Message.setProto3BooleanField(this, 18, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ConnectionInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ConnectionInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ConnectionInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ConnectionInfo.toObject = function(includeInstance, msg) { var f, obj = { connections: jspb.Message.getFieldWithDefault(msg, 1, 0), inboundConnections: jspb.Message.getFieldWithDefault(msg, 2, 0), outboundConnections: jspb.Message.getFieldWithDefault(msg, 3, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ConnectionInfo} */ proto.pactus.ConnectionInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ConnectionInfo; return proto.pactus.ConnectionInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ConnectionInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ConnectionInfo} */ proto.pactus.ConnectionInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint64()); msg.setConnections(value); break; case 2: var value = /** @type {number} */ (reader.readUint64()); msg.setInboundConnections(value); break; case 3: var value = /** @type {number} */ (reader.readUint64()); msg.setOutboundConnections(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ConnectionInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ConnectionInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ConnectionInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ConnectionInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getConnections(); if (f !== 0) { writer.writeUint64( 1, f ); } f = message.getInboundConnections(); if (f !== 0) { writer.writeUint64( 2, f ); } f = message.getOutboundConnections(); if (f !== 0) { writer.writeUint64( 3, f ); } }; /** * optional uint64 connections = 1; * @return {number} */ proto.pactus.ConnectionInfo.prototype.getConnections = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.ConnectionInfo} returns this */ proto.pactus.ConnectionInfo.prototype.setConnections = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional uint64 inbound_connections = 2; * @return {number} */ proto.pactus.ConnectionInfo.prototype.getInboundConnections = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.ConnectionInfo} returns this */ proto.pactus.ConnectionInfo.prototype.setInboundConnections = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * optional uint64 outbound_connections = 3; * @return {number} */ proto.pactus.ConnectionInfo.prototype.getOutboundConnections = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.ConnectionInfo} returns this */ proto.pactus.ConnectionInfo.prototype.setOutboundConnections = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.MetricInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.MetricInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.MetricInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.MetricInfo.toObject = function(includeInstance, msg) { var f, obj = { totalInvalid: (f = msg.getTotalInvalid()) && proto.pactus.CounterInfo.toObject(includeInstance, f), totalSent: (f = msg.getTotalSent()) && proto.pactus.CounterInfo.toObject(includeInstance, f), totalReceived: (f = msg.getTotalReceived()) && proto.pactus.CounterInfo.toObject(includeInstance, f), messageSentMap: (f = msg.getMessageSentMap()) ? f.toObject(includeInstance, proto.pactus.CounterInfo.toObject) : [], messageReceivedMap: (f = msg.getMessageReceivedMap()) ? f.toObject(includeInstance, proto.pactus.CounterInfo.toObject) : [] }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.MetricInfo} */ proto.pactus.MetricInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.MetricInfo; return proto.pactus.MetricInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.MetricInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.MetricInfo} */ proto.pactus.MetricInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.pactus.CounterInfo; reader.readMessage(value,proto.pactus.CounterInfo.deserializeBinaryFromReader); msg.setTotalInvalid(value); break; case 2: var value = new proto.pactus.CounterInfo; reader.readMessage(value,proto.pactus.CounterInfo.deserializeBinaryFromReader); msg.setTotalSent(value); break; case 3: var value = new proto.pactus.CounterInfo; reader.readMessage(value,proto.pactus.CounterInfo.deserializeBinaryFromReader); msg.setTotalReceived(value); break; case 4: var value = msg.getMessageSentMap(); reader.readMessage(value, function(message, reader) { jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readInt32, jspb.BinaryReader.prototype.readMessage, proto.pactus.CounterInfo.deserializeBinaryFromReader, 0, new proto.pactus.CounterInfo()); }); break; case 5: var value = msg.getMessageReceivedMap(); reader.readMessage(value, function(message, reader) { jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readInt32, jspb.BinaryReader.prototype.readMessage, proto.pactus.CounterInfo.deserializeBinaryFromReader, 0, new proto.pactus.CounterInfo()); }); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.MetricInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.MetricInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.MetricInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.MetricInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getTotalInvalid(); if (f != null) { writer.writeMessage( 1, f, proto.pactus.CounterInfo.serializeBinaryToWriter ); } f = message.getTotalSent(); if (f != null) { writer.writeMessage( 2, f, proto.pactus.CounterInfo.serializeBinaryToWriter ); } f = message.getTotalReceived(); if (f != null) { writer.writeMessage( 3, f, proto.pactus.CounterInfo.serializeBinaryToWriter ); } f = message.getMessageSentMap(true); if (f && f.getLength() > 0) { jspb.internal.public_for_gencode.serializeMapToBinary( message.getMessageSentMap(true), 4, writer, jspb.BinaryWriter.prototype.writeInt32, jspb.BinaryWriter.prototype.writeMessage, proto.pactus.CounterInfo.serializeBinaryToWriter); } f = message.getMessageReceivedMap(true); if (f && f.getLength() > 0) { jspb.internal.public_for_gencode.serializeMapToBinary( message.getMessageReceivedMap(true), 5, writer, jspb.BinaryWriter.prototype.writeInt32, jspb.BinaryWriter.prototype.writeMessage, proto.pactus.CounterInfo.serializeBinaryToWriter); } }; /** * optional CounterInfo total_invalid = 1; * @return {?proto.pactus.CounterInfo} */ proto.pactus.MetricInfo.prototype.getTotalInvalid = function() { return /** @type{?proto.pactus.CounterInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.CounterInfo, 1)); }; /** * @param {?proto.pactus.CounterInfo|undefined} value * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.setTotalInvalid = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.clearTotalInvalid = function() { return this.setTotalInvalid(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.MetricInfo.prototype.hasTotalInvalid = function() { return jspb.Message.getField(this, 1) != null; }; /** * optional CounterInfo total_sent = 2; * @return {?proto.pactus.CounterInfo} */ proto.pactus.MetricInfo.prototype.getTotalSent = function() { return /** @type{?proto.pactus.CounterInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.CounterInfo, 2)); }; /** * @param {?proto.pactus.CounterInfo|undefined} value * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.setTotalSent = function(value) { return jspb.Message.setWrapperField(this, 2, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.clearTotalSent = function() { return this.setTotalSent(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.MetricInfo.prototype.hasTotalSent = function() { return jspb.Message.getField(this, 2) != null; }; /** * optional CounterInfo total_received = 3; * @return {?proto.pactus.CounterInfo} */ proto.pactus.MetricInfo.prototype.getTotalReceived = function() { return /** @type{?proto.pactus.CounterInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.CounterInfo, 3)); }; /** * @param {?proto.pactus.CounterInfo|undefined} value * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.setTotalReceived = function(value) { return jspb.Message.setWrapperField(this, 3, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.clearTotalReceived = function() { return this.setTotalReceived(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.MetricInfo.prototype.hasTotalReceived = function() { return jspb.Message.getField(this, 3) != null; }; /** * map message_sent = 4; * @param {boolean=} opt_noLazyCreate Do not create the map if * empty, instead returning `undefined` * @return {!jspb.Map} */ proto.pactus.MetricInfo.prototype.getMessageSentMap = function(opt_noLazyCreate) { return /** @type {!jspb.Map} */ ( jspb.Message.getMapField(this, 4, opt_noLazyCreate, proto.pactus.CounterInfo)); }; /** * Clears values from the map. The map will be non-null. * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.clearMessageSentMap = function() { this.getMessageSentMap().clear(); return this; }; /** * map message_received = 5; * @param {boolean=} opt_noLazyCreate Do not create the map if * empty, instead returning `undefined` * @return {!jspb.Map} */ proto.pactus.MetricInfo.prototype.getMessageReceivedMap = function(opt_noLazyCreate) { return /** @type {!jspb.Map} */ ( jspb.Message.getMapField(this, 5, opt_noLazyCreate, proto.pactus.CounterInfo)); }; /** * Clears values from the map. The map will be non-null. * @return {!proto.pactus.MetricInfo} returns this */ proto.pactus.MetricInfo.prototype.clearMessageReceivedMap = function() { this.getMessageReceivedMap().clear(); return this; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CounterInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CounterInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CounterInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CounterInfo.toObject = function(includeInstance, msg) { var f, obj = { bytes: jspb.Message.getFieldWithDefault(msg, 1, 0), bundles: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CounterInfo} */ proto.pactus.CounterInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CounterInfo; return proto.pactus.CounterInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CounterInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CounterInfo} */ proto.pactus.CounterInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint64()); msg.setBytes(value); break; case 2: var value = /** @type {number} */ (reader.readUint64()); msg.setBundles(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CounterInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CounterInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CounterInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CounterInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getBytes(); if (f !== 0) { writer.writeUint64( 1, f ); } f = message.getBundles(); if (f !== 0) { writer.writeUint64( 2, f ); } }; /** * optional uint64 bytes = 1; * @return {number} */ proto.pactus.CounterInfo.prototype.getBytes = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.CounterInfo} returns this */ proto.pactus.CounterInfo.prototype.setBytes = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional uint64 bundles = 2; * @return {number} */ proto.pactus.CounterInfo.prototype.getBundles = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.CounterInfo} returns this */ proto.pactus.CounterInfo.prototype.setBundles = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PingRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PingRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PingRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PingRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PingRequest} */ proto.pactus.PingRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PingRequest; return proto.pactus.PingRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PingRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PingRequest} */ proto.pactus.PingRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PingRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PingRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PingRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PingRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PingResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PingResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PingResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PingResponse.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PingResponse} */ proto.pactus.PingResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PingResponse; return proto.pactus.PingResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PingResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PingResponse} */ proto.pactus.PingResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PingResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PingResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PingResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PingResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * @enum {number} */ proto.pactus.Direction = { DIRECTION_UNKNOWN: 0, DIRECTION_INBOUND: 1, DIRECTION_OUTBOUND: 2 }; goog.object.extend(exports, proto.pactus); ================================================ FILE: www/grpc/gen/js/transaction_grpc_pb.js ================================================ // GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('@grpc/grpc-js'); var transaction_pb = require('./transaction_pb.js'); function serialize_pactus_BroadcastTransactionRequest(arg) { if (!(arg instanceof transaction_pb.BroadcastTransactionRequest)) { throw new Error('Expected argument of type pactus.BroadcastTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_BroadcastTransactionRequest(buffer_arg) { return transaction_pb.BroadcastTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_BroadcastTransactionResponse(arg) { if (!(arg instanceof transaction_pb.BroadcastTransactionResponse)) { throw new Error('Expected argument of type pactus.BroadcastTransactionResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_BroadcastTransactionResponse(buffer_arg) { return transaction_pb.BroadcastTransactionResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_CalculateFeeRequest(arg) { if (!(arg instanceof transaction_pb.CalculateFeeRequest)) { throw new Error('Expected argument of type pactus.CalculateFeeRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_CalculateFeeRequest(buffer_arg) { return transaction_pb.CalculateFeeRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_CalculateFeeResponse(arg) { if (!(arg instanceof transaction_pb.CalculateFeeResponse)) { throw new Error('Expected argument of type pactus.CalculateFeeResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_CalculateFeeResponse(buffer_arg) { return transaction_pb.CalculateFeeResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_CheckTransactionRequest(arg) { if (!(arg instanceof transaction_pb.CheckTransactionRequest)) { throw new Error('Expected argument of type pactus.CheckTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_CheckTransactionRequest(buffer_arg) { return transaction_pb.CheckTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_CheckTransactionResponse(arg) { if (!(arg instanceof transaction_pb.CheckTransactionResponse)) { throw new Error('Expected argument of type pactus.CheckTransactionResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_CheckTransactionResponse(buffer_arg) { return transaction_pb.CheckTransactionResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_DecodeRawTransactionRequest(arg) { if (!(arg instanceof transaction_pb.DecodeRawTransactionRequest)) { throw new Error('Expected argument of type pactus.DecodeRawTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_DecodeRawTransactionRequest(buffer_arg) { return transaction_pb.DecodeRawTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_DecodeRawTransactionResponse(arg) { if (!(arg instanceof transaction_pb.DecodeRawTransactionResponse)) { throw new Error('Expected argument of type pactus.DecodeRawTransactionResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_DecodeRawTransactionResponse(buffer_arg) { return transaction_pb.DecodeRawTransactionResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetRawBatchTransferTransactionRequest(arg) { if (!(arg instanceof transaction_pb.GetRawBatchTransferTransactionRequest)) { throw new Error('Expected argument of type pactus.GetRawBatchTransferTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetRawBatchTransferTransactionRequest(buffer_arg) { return transaction_pb.GetRawBatchTransferTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetRawBondTransactionRequest(arg) { if (!(arg instanceof transaction_pb.GetRawBondTransactionRequest)) { throw new Error('Expected argument of type pactus.GetRawBondTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetRawBondTransactionRequest(buffer_arg) { return transaction_pb.GetRawBondTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetRawTransactionResponse(arg) { if (!(arg instanceof transaction_pb.GetRawTransactionResponse)) { throw new Error('Expected argument of type pactus.GetRawTransactionResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetRawTransactionResponse(buffer_arg) { return transaction_pb.GetRawTransactionResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetRawTransferTransactionRequest(arg) { if (!(arg instanceof transaction_pb.GetRawTransferTransactionRequest)) { throw new Error('Expected argument of type pactus.GetRawTransferTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetRawTransferTransactionRequest(buffer_arg) { return transaction_pb.GetRawTransferTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetRawUnbondTransactionRequest(arg) { if (!(arg instanceof transaction_pb.GetRawUnbondTransactionRequest)) { throw new Error('Expected argument of type pactus.GetRawUnbondTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetRawUnbondTransactionRequest(buffer_arg) { return transaction_pb.GetRawUnbondTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetRawWithdrawTransactionRequest(arg) { if (!(arg instanceof transaction_pb.GetRawWithdrawTransactionRequest)) { throw new Error('Expected argument of type pactus.GetRawWithdrawTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetRawWithdrawTransactionRequest(buffer_arg) { return transaction_pb.GetRawWithdrawTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTransactionRequest(arg) { if (!(arg instanceof transaction_pb.GetTransactionRequest)) { throw new Error('Expected argument of type pactus.GetTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTransactionRequest(buffer_arg) { return transaction_pb.GetTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTransactionResponse(arg) { if (!(arg instanceof transaction_pb.GetTransactionResponse)) { throw new Error('Expected argument of type pactus.GetTransactionResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTransactionResponse(buffer_arg) { return transaction_pb.GetTransactionResponse.deserializeBinary(new Uint8Array(buffer_arg)); } // Transaction service defines various RPC methods for interacting with transactions. var TransactionService = exports.TransactionService = { // GetTransaction retrieves transaction details based on the provided request parameters. getTransaction: { path: '/pactus.Transaction/GetTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.GetTransactionRequest, responseType: transaction_pb.GetTransactionResponse, requestSerialize: serialize_pactus_GetTransactionRequest, requestDeserialize: deserialize_pactus_GetTransactionRequest, responseSerialize: serialize_pactus_GetTransactionResponse, responseDeserialize: deserialize_pactus_GetTransactionResponse, }, // CalculateFee calculates the transaction fee based on the specified amount and payload type. calculateFee: { path: '/pactus.Transaction/CalculateFee', requestStream: false, responseStream: false, requestType: transaction_pb.CalculateFeeRequest, responseType: transaction_pb.CalculateFeeResponse, requestSerialize: serialize_pactus_CalculateFeeRequest, requestDeserialize: deserialize_pactus_CalculateFeeRequest, responseSerialize: serialize_pactus_CalculateFeeResponse, responseDeserialize: deserialize_pactus_CalculateFeeResponse, }, // BroadcastTransaction broadcasts a signed transaction to the network. broadcastTransaction: { path: '/pactus.Transaction/BroadcastTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.BroadcastTransactionRequest, responseType: transaction_pb.BroadcastTransactionResponse, requestSerialize: serialize_pactus_BroadcastTransactionRequest, requestDeserialize: deserialize_pactus_BroadcastTransactionRequest, responseSerialize: serialize_pactus_BroadcastTransactionResponse, responseDeserialize: deserialize_pactus_BroadcastTransactionResponse, }, // GetRawTransferTransaction retrieves raw details of a transfer transaction. getRawTransferTransaction: { path: '/pactus.Transaction/GetRawTransferTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.GetRawTransferTransactionRequest, responseType: transaction_pb.GetRawTransactionResponse, requestSerialize: serialize_pactus_GetRawTransferTransactionRequest, requestDeserialize: deserialize_pactus_GetRawTransferTransactionRequest, responseSerialize: serialize_pactus_GetRawTransactionResponse, responseDeserialize: deserialize_pactus_GetRawTransactionResponse, }, // GetRawBondTransaction retrieves raw details of a bond transaction. getRawBondTransaction: { path: '/pactus.Transaction/GetRawBondTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.GetRawBondTransactionRequest, responseType: transaction_pb.GetRawTransactionResponse, requestSerialize: serialize_pactus_GetRawBondTransactionRequest, requestDeserialize: deserialize_pactus_GetRawBondTransactionRequest, responseSerialize: serialize_pactus_GetRawTransactionResponse, responseDeserialize: deserialize_pactus_GetRawTransactionResponse, }, // GetRawUnbondTransaction retrieves raw details of an unbond transaction. getRawUnbondTransaction: { path: '/pactus.Transaction/GetRawUnbondTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.GetRawUnbondTransactionRequest, responseType: transaction_pb.GetRawTransactionResponse, requestSerialize: serialize_pactus_GetRawUnbondTransactionRequest, requestDeserialize: deserialize_pactus_GetRawUnbondTransactionRequest, responseSerialize: serialize_pactus_GetRawTransactionResponse, responseDeserialize: deserialize_pactus_GetRawTransactionResponse, }, // GetRawWithdrawTransaction retrieves raw details of a withdraw transaction. getRawWithdrawTransaction: { path: '/pactus.Transaction/GetRawWithdrawTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.GetRawWithdrawTransactionRequest, responseType: transaction_pb.GetRawTransactionResponse, requestSerialize: serialize_pactus_GetRawWithdrawTransactionRequest, requestDeserialize: deserialize_pactus_GetRawWithdrawTransactionRequest, responseSerialize: serialize_pactus_GetRawTransactionResponse, responseDeserialize: deserialize_pactus_GetRawTransactionResponse, }, // GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction. getRawBatchTransferTransaction: { path: '/pactus.Transaction/GetRawBatchTransferTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.GetRawBatchTransferTransactionRequest, responseType: transaction_pb.GetRawTransactionResponse, requestSerialize: serialize_pactus_GetRawBatchTransferTransactionRequest, requestDeserialize: deserialize_pactus_GetRawBatchTransferTransactionRequest, responseSerialize: serialize_pactus_GetRawTransactionResponse, responseDeserialize: deserialize_pactus_GetRawTransactionResponse, }, // DecodeRawTransaction accepts raw transaction and returns decoded transaction. decodeRawTransaction: { path: '/pactus.Transaction/DecodeRawTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.DecodeRawTransactionRequest, responseType: transaction_pb.DecodeRawTransactionResponse, requestSerialize: serialize_pactus_DecodeRawTransactionRequest, requestDeserialize: deserialize_pactus_DecodeRawTransactionRequest, responseSerialize: serialize_pactus_DecodeRawTransactionResponse, responseDeserialize: deserialize_pactus_DecodeRawTransactionResponse, }, // CheckTransaction checks if the transaction is valid and can be included in the blockchain. checkTransaction: { path: '/pactus.Transaction/CheckTransaction', requestStream: false, responseStream: false, requestType: transaction_pb.CheckTransactionRequest, responseType: transaction_pb.CheckTransactionResponse, requestSerialize: serialize_pactus_CheckTransactionRequest, requestDeserialize: deserialize_pactus_CheckTransactionRequest, responseSerialize: serialize_pactus_CheckTransactionResponse, responseDeserialize: deserialize_pactus_CheckTransactionResponse, }, }; exports.TransactionClient = grpc.makeGenericClientConstructor(TransactionService, 'Transaction'); ================================================ FILE: www/grpc/gen/js/transaction_grpc_web_pb.js ================================================ /** * @fileoverview gRPC-Web generated client stub for pactus * @enhanceable * @public */ // Code generated by protoc-gen-grpc-web. DO NOT EDIT. // versions: // protoc-gen-grpc-web v2.0.2 // protoc v0.0.0 // source: transaction.proto /* eslint-disable */ // @ts-nocheck const grpc = {}; grpc.web = require('grpc-web'); const proto = {}; proto.pactus = require('./transaction_pb.js'); /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.TransactionClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.TransactionPromiseClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetTransactionRequest, * !proto.pactus.GetTransactionResponse>} */ const methodDescriptor_Transaction_GetTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/GetTransaction', grpc.web.MethodType.UNARY, proto.pactus.GetTransactionRequest, proto.pactus.GetTransactionResponse, /** * @param {!proto.pactus.GetTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.GetTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.getTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/GetTransaction', request, metadata || {}, methodDescriptor_Transaction_GetTransaction, callback); }; /** * @param {!proto.pactus.GetTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.getTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/GetTransaction', request, metadata || {}, methodDescriptor_Transaction_GetTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.CalculateFeeRequest, * !proto.pactus.CalculateFeeResponse>} */ const methodDescriptor_Transaction_CalculateFee = new grpc.web.MethodDescriptor( '/pactus.Transaction/CalculateFee', grpc.web.MethodType.UNARY, proto.pactus.CalculateFeeRequest, proto.pactus.CalculateFeeResponse, /** * @param {!proto.pactus.CalculateFeeRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.CalculateFeeResponse.deserializeBinary ); /** * @param {!proto.pactus.CalculateFeeRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.CalculateFeeResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.calculateFee = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/CalculateFee', request, metadata || {}, methodDescriptor_Transaction_CalculateFee, callback); }; /** * @param {!proto.pactus.CalculateFeeRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.calculateFee = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/CalculateFee', request, metadata || {}, methodDescriptor_Transaction_CalculateFee); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.BroadcastTransactionRequest, * !proto.pactus.BroadcastTransactionResponse>} */ const methodDescriptor_Transaction_BroadcastTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/BroadcastTransaction', grpc.web.MethodType.UNARY, proto.pactus.BroadcastTransactionRequest, proto.pactus.BroadcastTransactionResponse, /** * @param {!proto.pactus.BroadcastTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.BroadcastTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.BroadcastTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.BroadcastTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.broadcastTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/BroadcastTransaction', request, metadata || {}, methodDescriptor_Transaction_BroadcastTransaction, callback); }; /** * @param {!proto.pactus.BroadcastTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.broadcastTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/BroadcastTransaction', request, metadata || {}, methodDescriptor_Transaction_BroadcastTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetRawTransferTransactionRequest, * !proto.pactus.GetRawTransactionResponse>} */ const methodDescriptor_Transaction_GetRawTransferTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/GetRawTransferTransaction', grpc.web.MethodType.UNARY, proto.pactus.GetRawTransferTransactionRequest, proto.pactus.GetRawTransactionResponse, /** * @param {!proto.pactus.GetRawTransferTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.GetRawTransferTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.getRawTransferTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/GetRawTransferTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawTransferTransaction, callback); }; /** * @param {!proto.pactus.GetRawTransferTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.getRawTransferTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/GetRawTransferTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawTransferTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetRawBondTransactionRequest, * !proto.pactus.GetRawTransactionResponse>} */ const methodDescriptor_Transaction_GetRawBondTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/GetRawBondTransaction', grpc.web.MethodType.UNARY, proto.pactus.GetRawBondTransactionRequest, proto.pactus.GetRawTransactionResponse, /** * @param {!proto.pactus.GetRawBondTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.GetRawBondTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.getRawBondTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/GetRawBondTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawBondTransaction, callback); }; /** * @param {!proto.pactus.GetRawBondTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.getRawBondTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/GetRawBondTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawBondTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetRawUnbondTransactionRequest, * !proto.pactus.GetRawTransactionResponse>} */ const methodDescriptor_Transaction_GetRawUnbondTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/GetRawUnbondTransaction', grpc.web.MethodType.UNARY, proto.pactus.GetRawUnbondTransactionRequest, proto.pactus.GetRawTransactionResponse, /** * @param {!proto.pactus.GetRawUnbondTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.GetRawUnbondTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.getRawUnbondTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/GetRawUnbondTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawUnbondTransaction, callback); }; /** * @param {!proto.pactus.GetRawUnbondTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.getRawUnbondTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/GetRawUnbondTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawUnbondTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetRawWithdrawTransactionRequest, * !proto.pactus.GetRawTransactionResponse>} */ const methodDescriptor_Transaction_GetRawWithdrawTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/GetRawWithdrawTransaction', grpc.web.MethodType.UNARY, proto.pactus.GetRawWithdrawTransactionRequest, proto.pactus.GetRawTransactionResponse, /** * @param {!proto.pactus.GetRawWithdrawTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.GetRawWithdrawTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.getRawWithdrawTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/GetRawWithdrawTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawWithdrawTransaction, callback); }; /** * @param {!proto.pactus.GetRawWithdrawTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.getRawWithdrawTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/GetRawWithdrawTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawWithdrawTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetRawBatchTransferTransactionRequest, * !proto.pactus.GetRawTransactionResponse>} */ const methodDescriptor_Transaction_GetRawBatchTransferTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/GetRawBatchTransferTransaction', grpc.web.MethodType.UNARY, proto.pactus.GetRawBatchTransferTransactionRequest, proto.pactus.GetRawTransactionResponse, /** * @param {!proto.pactus.GetRawBatchTransferTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.GetRawBatchTransferTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.getRawBatchTransferTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/GetRawBatchTransferTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawBatchTransferTransaction, callback); }; /** * @param {!proto.pactus.GetRawBatchTransferTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.getRawBatchTransferTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/GetRawBatchTransferTransaction', request, metadata || {}, methodDescriptor_Transaction_GetRawBatchTransferTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.DecodeRawTransactionRequest, * !proto.pactus.DecodeRawTransactionResponse>} */ const methodDescriptor_Transaction_DecodeRawTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/DecodeRawTransaction', grpc.web.MethodType.UNARY, proto.pactus.DecodeRawTransactionRequest, proto.pactus.DecodeRawTransactionResponse, /** * @param {!proto.pactus.DecodeRawTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.DecodeRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.DecodeRawTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.DecodeRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.decodeRawTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/DecodeRawTransaction', request, metadata || {}, methodDescriptor_Transaction_DecodeRawTransaction, callback); }; /** * @param {!proto.pactus.DecodeRawTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.decodeRawTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/DecodeRawTransaction', request, metadata || {}, methodDescriptor_Transaction_DecodeRawTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.CheckTransactionRequest, * !proto.pactus.CheckTransactionResponse>} */ const methodDescriptor_Transaction_CheckTransaction = new grpc.web.MethodDescriptor( '/pactus.Transaction/CheckTransaction', grpc.web.MethodType.UNARY, proto.pactus.CheckTransactionRequest, proto.pactus.CheckTransactionResponse, /** * @param {!proto.pactus.CheckTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.CheckTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.CheckTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.CheckTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.TransactionClient.prototype.checkTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Transaction/CheckTransaction', request, metadata || {}, methodDescriptor_Transaction_CheckTransaction, callback); }; /** * @param {!proto.pactus.CheckTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.TransactionPromiseClient.prototype.checkTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Transaction/CheckTransaction', request, metadata || {}, methodDescriptor_Transaction_CheckTransaction); }; module.exports = proto.pactus; ================================================ FILE: www/grpc/gen/js/transaction_pb.js ================================================ // source: transaction.proto /** * @fileoverview * @enhanceable * @suppress {missingRequire} reports error on implicit type usages. * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var global = globalThis; goog.exportSymbol('proto.pactus.BroadcastTransactionRequest', null, global); goog.exportSymbol('proto.pactus.BroadcastTransactionResponse', null, global); goog.exportSymbol('proto.pactus.CalculateFeeRequest', null, global); goog.exportSymbol('proto.pactus.CalculateFeeResponse', null, global); goog.exportSymbol('proto.pactus.CheckTransactionRequest', null, global); goog.exportSymbol('proto.pactus.CheckTransactionResponse', null, global); goog.exportSymbol('proto.pactus.DecodeRawTransactionRequest', null, global); goog.exportSymbol('proto.pactus.DecodeRawTransactionResponse', null, global); goog.exportSymbol('proto.pactus.GetRawBatchTransferTransactionRequest', null, global); goog.exportSymbol('proto.pactus.GetRawBondTransactionRequest', null, global); goog.exportSymbol('proto.pactus.GetRawTransactionResponse', null, global); goog.exportSymbol('proto.pactus.GetRawTransferTransactionRequest', null, global); goog.exportSymbol('proto.pactus.GetRawUnbondTransactionRequest', null, global); goog.exportSymbol('proto.pactus.GetRawWithdrawTransactionRequest', null, global); goog.exportSymbol('proto.pactus.GetTransactionRequest', null, global); goog.exportSymbol('proto.pactus.GetTransactionResponse', null, global); goog.exportSymbol('proto.pactus.PayloadBatchTransfer', null, global); goog.exportSymbol('proto.pactus.PayloadBond', null, global); goog.exportSymbol('proto.pactus.PayloadSortition', null, global); goog.exportSymbol('proto.pactus.PayloadTransfer', null, global); goog.exportSymbol('proto.pactus.PayloadType', null, global); goog.exportSymbol('proto.pactus.PayloadUnbond', null, global); goog.exportSymbol('proto.pactus.PayloadWithdraw', null, global); goog.exportSymbol('proto.pactus.Recipient', null, global); goog.exportSymbol('proto.pactus.TransactionInfo', null, global); goog.exportSymbol('proto.pactus.TransactionInfo.PayloadCase', null, global); goog.exportSymbol('proto.pactus.TransactionVerbosity', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTransactionRequest.displayName = 'proto.pactus.GetTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTransactionResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTransactionResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTransactionResponse.displayName = 'proto.pactus.GetTransactionResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CalculateFeeRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CalculateFeeRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CalculateFeeRequest.displayName = 'proto.pactus.CalculateFeeRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CalculateFeeResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CalculateFeeResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CalculateFeeResponse.displayName = 'proto.pactus.CalculateFeeResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.BroadcastTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.BroadcastTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.BroadcastTransactionRequest.displayName = 'proto.pactus.BroadcastTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.BroadcastTransactionResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.BroadcastTransactionResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.BroadcastTransactionResponse.displayName = 'proto.pactus.BroadcastTransactionResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetRawTransferTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetRawTransferTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetRawTransferTransactionRequest.displayName = 'proto.pactus.GetRawTransferTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetRawBondTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetRawBondTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetRawBondTransactionRequest.displayName = 'proto.pactus.GetRawBondTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetRawUnbondTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetRawUnbondTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetRawUnbondTransactionRequest.displayName = 'proto.pactus.GetRawUnbondTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetRawWithdrawTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetRawWithdrawTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetRawWithdrawTransactionRequest.displayName = 'proto.pactus.GetRawWithdrawTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetRawBatchTransferTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.GetRawBatchTransferTransactionRequest.repeatedFields_, null); }; goog.inherits(proto.pactus.GetRawBatchTransferTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetRawBatchTransferTransactionRequest.displayName = 'proto.pactus.GetRawBatchTransferTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetRawTransactionResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetRawTransactionResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetRawTransactionResponse.displayName = 'proto.pactus.GetRawTransactionResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PayloadTransfer = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PayloadTransfer, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PayloadTransfer.displayName = 'proto.pactus.PayloadTransfer'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PayloadBond = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PayloadBond, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PayloadBond.displayName = 'proto.pactus.PayloadBond'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PayloadSortition = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PayloadSortition, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PayloadSortition.displayName = 'proto.pactus.PayloadSortition'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PayloadUnbond = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PayloadUnbond, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PayloadUnbond.displayName = 'proto.pactus.PayloadUnbond'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PayloadWithdraw = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PayloadWithdraw, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PayloadWithdraw.displayName = 'proto.pactus.PayloadWithdraw'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PayloadBatchTransfer = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.PayloadBatchTransfer.repeatedFields_, null); }; goog.inherits(proto.pactus.PayloadBatchTransfer, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PayloadBatchTransfer.displayName = 'proto.pactus.PayloadBatchTransfer'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.Recipient = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.Recipient, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.Recipient.displayName = 'proto.pactus.Recipient'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.TransactionInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, proto.pactus.TransactionInfo.oneofGroups_); }; goog.inherits(proto.pactus.TransactionInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.TransactionInfo.displayName = 'proto.pactus.TransactionInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.DecodeRawTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.DecodeRawTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.DecodeRawTransactionRequest.displayName = 'proto.pactus.DecodeRawTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.DecodeRawTransactionResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.DecodeRawTransactionResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.DecodeRawTransactionResponse.displayName = 'proto.pactus.DecodeRawTransactionResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CheckTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CheckTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CheckTransactionRequest.displayName = 'proto.pactus.CheckTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CheckTransactionResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CheckTransactionResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CheckTransactionResponse.displayName = 'proto.pactus.CheckTransactionResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { id: jspb.Message.getFieldWithDefault(msg, 1, ""), verbosity: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTransactionRequest} */ proto.pactus.GetTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTransactionRequest; return proto.pactus.GetTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTransactionRequest} */ proto.pactus.GetTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setId(value); break; case 2: var value = /** @type {!proto.pactus.TransactionVerbosity} */ (reader.readEnum()); msg.setVerbosity(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getId(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getVerbosity(); if (f !== 0.0) { writer.writeEnum( 2, f ); } }; /** * optional string id = 1; * @return {string} */ proto.pactus.GetTransactionRequest.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetTransactionRequest} returns this */ proto.pactus.GetTransactionRequest.prototype.setId = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional TransactionVerbosity verbosity = 2; * @return {!proto.pactus.TransactionVerbosity} */ proto.pactus.GetTransactionRequest.prototype.getVerbosity = function() { return /** @type {!proto.pactus.TransactionVerbosity} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {!proto.pactus.TransactionVerbosity} value * @return {!proto.pactus.GetTransactionRequest} returns this */ proto.pactus.GetTransactionRequest.prototype.setVerbosity = function(value) { return jspb.Message.setProto3EnumField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTransactionResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTransactionResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTransactionResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTransactionResponse.toObject = function(includeInstance, msg) { var f, obj = { blockHeight: jspb.Message.getFieldWithDefault(msg, 1, 0), blockTime: jspb.Message.getFieldWithDefault(msg, 2, 0), transaction: (f = msg.getTransaction()) && proto.pactus.TransactionInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTransactionResponse} */ proto.pactus.GetTransactionResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTransactionResponse; return proto.pactus.GetTransactionResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTransactionResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTransactionResponse} */ proto.pactus.GetTransactionResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setBlockHeight(value); break; case 2: var value = /** @type {number} */ (reader.readUint32()); msg.setBlockTime(value); break; case 3: var value = new proto.pactus.TransactionInfo; reader.readMessage(value,proto.pactus.TransactionInfo.deserializeBinaryFromReader); msg.setTransaction(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTransactionResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTransactionResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTransactionResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTransactionResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getBlockHeight(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getBlockTime(); if (f !== 0) { writer.writeUint32( 2, f ); } f = message.getTransaction(); if (f != null) { writer.writeMessage( 3, f, proto.pactus.TransactionInfo.serializeBinaryToWriter ); } }; /** * optional uint32 block_height = 1; * @return {number} */ proto.pactus.GetTransactionResponse.prototype.getBlockHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetTransactionResponse} returns this */ proto.pactus.GetTransactionResponse.prototype.setBlockHeight = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional uint32 block_time = 2; * @return {number} */ proto.pactus.GetTransactionResponse.prototype.getBlockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetTransactionResponse} returns this */ proto.pactus.GetTransactionResponse.prototype.setBlockTime = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * optional TransactionInfo transaction = 3; * @return {?proto.pactus.TransactionInfo} */ proto.pactus.GetTransactionResponse.prototype.getTransaction = function() { return /** @type{?proto.pactus.TransactionInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.TransactionInfo, 3)); }; /** * @param {?proto.pactus.TransactionInfo|undefined} value * @return {!proto.pactus.GetTransactionResponse} returns this */ proto.pactus.GetTransactionResponse.prototype.setTransaction = function(value) { return jspb.Message.setWrapperField(this, 3, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetTransactionResponse} returns this */ proto.pactus.GetTransactionResponse.prototype.clearTransaction = function() { return this.setTransaction(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetTransactionResponse.prototype.hasTransaction = function() { return jspb.Message.getField(this, 3) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CalculateFeeRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CalculateFeeRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CalculateFeeRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CalculateFeeRequest.toObject = function(includeInstance, msg) { var f, obj = { amount: jspb.Message.getFieldWithDefault(msg, 1, 0), payloadType: jspb.Message.getFieldWithDefault(msg, 2, 0), fixedAmount: jspb.Message.getBooleanFieldWithDefault(msg, 3, false) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CalculateFeeRequest} */ proto.pactus.CalculateFeeRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CalculateFeeRequest; return proto.pactus.CalculateFeeRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CalculateFeeRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CalculateFeeRequest} */ proto.pactus.CalculateFeeRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; case 2: var value = /** @type {!proto.pactus.PayloadType} */ (reader.readEnum()); msg.setPayloadType(value); break; case 3: var value = /** @type {boolean} */ (reader.readBool()); msg.setFixedAmount(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CalculateFeeRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CalculateFeeRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CalculateFeeRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CalculateFeeRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAmount(); if (f !== 0) { writer.writeInt64( 1, f ); } f = message.getPayloadType(); if (f !== 0.0) { writer.writeEnum( 2, f ); } f = message.getFixedAmount(); if (f) { writer.writeBool( 3, f ); } }; /** * optional int64 amount = 1; * @return {number} */ proto.pactus.CalculateFeeRequest.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.CalculateFeeRequest} returns this */ proto.pactus.CalculateFeeRequest.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional PayloadType payload_type = 2; * @return {!proto.pactus.PayloadType} */ proto.pactus.CalculateFeeRequest.prototype.getPayloadType = function() { return /** @type {!proto.pactus.PayloadType} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {!proto.pactus.PayloadType} value * @return {!proto.pactus.CalculateFeeRequest} returns this */ proto.pactus.CalculateFeeRequest.prototype.setPayloadType = function(value) { return jspb.Message.setProto3EnumField(this, 2, value); }; /** * optional bool fixed_amount = 3; * @return {boolean} */ proto.pactus.CalculateFeeRequest.prototype.getFixedAmount = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 3, false)); }; /** * @param {boolean} value * @return {!proto.pactus.CalculateFeeRequest} returns this */ proto.pactus.CalculateFeeRequest.prototype.setFixedAmount = function(value) { return jspb.Message.setProto3BooleanField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CalculateFeeResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CalculateFeeResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CalculateFeeResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CalculateFeeResponse.toObject = function(includeInstance, msg) { var f, obj = { amount: jspb.Message.getFieldWithDefault(msg, 1, 0), fee: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CalculateFeeResponse} */ proto.pactus.CalculateFeeResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CalculateFeeResponse; return proto.pactus.CalculateFeeResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CalculateFeeResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CalculateFeeResponse} */ proto.pactus.CalculateFeeResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CalculateFeeResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CalculateFeeResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CalculateFeeResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CalculateFeeResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAmount(); if (f !== 0) { writer.writeInt64( 1, f ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 2, f ); } }; /** * optional int64 amount = 1; * @return {number} */ proto.pactus.CalculateFeeResponse.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.CalculateFeeResponse} returns this */ proto.pactus.CalculateFeeResponse.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional int64 fee = 2; * @return {number} */ proto.pactus.CalculateFeeResponse.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.CalculateFeeResponse} returns this */ proto.pactus.CalculateFeeResponse.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.BroadcastTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.BroadcastTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.BroadcastTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.BroadcastTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { signedRawTransaction: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.BroadcastTransactionRequest} */ proto.pactus.BroadcastTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.BroadcastTransactionRequest; return proto.pactus.BroadcastTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.BroadcastTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.BroadcastTransactionRequest} */ proto.pactus.BroadcastTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignedRawTransaction(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.BroadcastTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.BroadcastTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.BroadcastTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.BroadcastTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSignedRawTransaction(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string signed_raw_transaction = 1; * @return {string} */ proto.pactus.BroadcastTransactionRequest.prototype.getSignedRawTransaction = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.BroadcastTransactionRequest} returns this */ proto.pactus.BroadcastTransactionRequest.prototype.setSignedRawTransaction = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.BroadcastTransactionResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.BroadcastTransactionResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.BroadcastTransactionResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.BroadcastTransactionResponse.toObject = function(includeInstance, msg) { var f, obj = { id: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.BroadcastTransactionResponse} */ proto.pactus.BroadcastTransactionResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.BroadcastTransactionResponse; return proto.pactus.BroadcastTransactionResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.BroadcastTransactionResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.BroadcastTransactionResponse} */ proto.pactus.BroadcastTransactionResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setId(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.BroadcastTransactionResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.BroadcastTransactionResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.BroadcastTransactionResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.BroadcastTransactionResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getId(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string id = 1; * @return {string} */ proto.pactus.BroadcastTransactionResponse.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.BroadcastTransactionResponse} returns this */ proto.pactus.BroadcastTransactionResponse.prototype.setId = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetRawTransferTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetRawTransferTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetRawTransferTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawTransferTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { lockTime: jspb.Message.getFieldWithDefault(msg, 1, 0), sender: jspb.Message.getFieldWithDefault(msg, 2, ""), receiver: jspb.Message.getFieldWithDefault(msg, 3, ""), amount: jspb.Message.getFieldWithDefault(msg, 4, 0), fee: jspb.Message.getFieldWithDefault(msg, 5, 0), memo: jspb.Message.getFieldWithDefault(msg, 6, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetRawTransferTransactionRequest} */ proto.pactus.GetRawTransferTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetRawTransferTransactionRequest; return proto.pactus.GetRawTransferTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetRawTransferTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetRawTransferTransactionRequest} */ proto.pactus.GetRawTransferTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setLockTime(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReceiver(value); break; case 4: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; case 5: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; case 6: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetRawTransferTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetRawTransferTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetRawTransferTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawTransferTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getLockTime(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getSender(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getReceiver(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 4, f ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 5, f ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 6, f ); } }; /** * optional uint32 lock_time = 1; * @return {number} */ proto.pactus.GetRawTransferTransactionRequest.prototype.getLockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawTransferTransactionRequest} returns this */ proto.pactus.GetRawTransferTransactionRequest.prototype.setLockTime = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string sender = 2; * @return {string} */ proto.pactus.GetRawTransferTransactionRequest.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawTransferTransactionRequest} returns this */ proto.pactus.GetRawTransferTransactionRequest.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string receiver = 3; * @return {string} */ proto.pactus.GetRawTransferTransactionRequest.prototype.getReceiver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawTransferTransactionRequest} returns this */ proto.pactus.GetRawTransferTransactionRequest.prototype.setReceiver = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional int64 amount = 4; * @return {number} */ proto.pactus.GetRawTransferTransactionRequest.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawTransferTransactionRequest} returns this */ proto.pactus.GetRawTransferTransactionRequest.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int64 fee = 5; * @return {number} */ proto.pactus.GetRawTransferTransactionRequest.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawTransferTransactionRequest} returns this */ proto.pactus.GetRawTransferTransactionRequest.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * optional string memo = 6; * @return {string} */ proto.pactus.GetRawTransferTransactionRequest.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 6, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawTransferTransactionRequest} returns this */ proto.pactus.GetRawTransferTransactionRequest.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 6, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetRawBondTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetRawBondTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetRawBondTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawBondTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { lockTime: jspb.Message.getFieldWithDefault(msg, 1, 0), sender: jspb.Message.getFieldWithDefault(msg, 2, ""), receiver: jspb.Message.getFieldWithDefault(msg, 3, ""), stake: jspb.Message.getFieldWithDefault(msg, 4, 0), publicKey: jspb.Message.getFieldWithDefault(msg, 5, ""), fee: jspb.Message.getFieldWithDefault(msg, 6, 0), memo: jspb.Message.getFieldWithDefault(msg, 7, ""), delegateOwner: jspb.Message.getFieldWithDefault(msg, 8, ""), delegateShare: jspb.Message.getFieldWithDefault(msg, 9, 0), delegateExpiry: jspb.Message.getFieldWithDefault(msg, 10, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetRawBondTransactionRequest} */ proto.pactus.GetRawBondTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetRawBondTransactionRequest; return proto.pactus.GetRawBondTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetRawBondTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetRawBondTransactionRequest} */ proto.pactus.GetRawBondTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setLockTime(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReceiver(value); break; case 4: var value = /** @type {number} */ (reader.readInt64()); msg.setStake(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; case 6: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; case 7: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; case 8: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setDelegateOwner(value); break; case 9: var value = /** @type {number} */ (reader.readInt64()); msg.setDelegateShare(value); break; case 10: var value = /** @type {number} */ (reader.readUint32()); msg.setDelegateExpiry(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetRawBondTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetRawBondTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetRawBondTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawBondTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getLockTime(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getSender(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getReceiver(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getStake(); if (f !== 0) { writer.writeInt64( 4, f ); } f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 5, f ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 6, f ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 7, f ); } f = message.getDelegateOwner(); if (f.length > 0) { writer.writeString( 8, f ); } f = message.getDelegateShare(); if (f !== 0) { writer.writeInt64( 9, f ); } f = message.getDelegateExpiry(); if (f !== 0) { writer.writeUint32( 10, f ); } }; /** * optional uint32 lock_time = 1; * @return {number} */ proto.pactus.GetRawBondTransactionRequest.prototype.getLockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setLockTime = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string sender = 2; * @return {string} */ proto.pactus.GetRawBondTransactionRequest.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string receiver = 3; * @return {string} */ proto.pactus.GetRawBondTransactionRequest.prototype.getReceiver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setReceiver = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional int64 stake = 4; * @return {number} */ proto.pactus.GetRawBondTransactionRequest.prototype.getStake = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setStake = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional string public_key = 5; * @return {string} */ proto.pactus.GetRawBondTransactionRequest.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; /** * optional int64 fee = 6; * @return {number} */ proto.pactus.GetRawBondTransactionRequest.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional string memo = 7; * @return {string} */ proto.pactus.GetRawBondTransactionRequest.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 7, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 7, value); }; /** * optional string delegate_owner = 8; * @return {string} */ proto.pactus.GetRawBondTransactionRequest.prototype.getDelegateOwner = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setDelegateOwner = function(value) { return jspb.Message.setProto3StringField(this, 8, value); }; /** * optional int64 delegate_share = 9; * @return {number} */ proto.pactus.GetRawBondTransactionRequest.prototype.getDelegateShare = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 9, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setDelegateShare = function(value) { return jspb.Message.setProto3IntField(this, 9, value); }; /** * optional uint32 delegate_expiry = 10; * @return {number} */ proto.pactus.GetRawBondTransactionRequest.prototype.getDelegateExpiry = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 10, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBondTransactionRequest} returns this */ proto.pactus.GetRawBondTransactionRequest.prototype.setDelegateExpiry = function(value) { return jspb.Message.setProto3IntField(this, 10, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetRawUnbondTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetRawUnbondTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetRawUnbondTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawUnbondTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { lockTime: jspb.Message.getFieldWithDefault(msg, 1, 0), validatorAddress: jspb.Message.getFieldWithDefault(msg, 2, ""), memo: jspb.Message.getFieldWithDefault(msg, 3, ""), delegateOwner: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetRawUnbondTransactionRequest} */ proto.pactus.GetRawUnbondTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetRawUnbondTransactionRequest; return proto.pactus.GetRawUnbondTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetRawUnbondTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetRawUnbondTransactionRequest} */ proto.pactus.GetRawUnbondTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setLockTime(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setValidatorAddress(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setDelegateOwner(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetRawUnbondTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetRawUnbondTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetRawUnbondTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawUnbondTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getLockTime(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getValidatorAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getDelegateOwner(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional uint32 lock_time = 1; * @return {number} */ proto.pactus.GetRawUnbondTransactionRequest.prototype.getLockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawUnbondTransactionRequest} returns this */ proto.pactus.GetRawUnbondTransactionRequest.prototype.setLockTime = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string validator_address = 2; * @return {string} */ proto.pactus.GetRawUnbondTransactionRequest.prototype.getValidatorAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawUnbondTransactionRequest} returns this */ proto.pactus.GetRawUnbondTransactionRequest.prototype.setValidatorAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string memo = 3; * @return {string} */ proto.pactus.GetRawUnbondTransactionRequest.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawUnbondTransactionRequest} returns this */ proto.pactus.GetRawUnbondTransactionRequest.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string delegate_owner = 4; * @return {string} */ proto.pactus.GetRawUnbondTransactionRequest.prototype.getDelegateOwner = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawUnbondTransactionRequest} returns this */ proto.pactus.GetRawUnbondTransactionRequest.prototype.setDelegateOwner = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetRawWithdrawTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetRawWithdrawTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawWithdrawTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { lockTime: jspb.Message.getFieldWithDefault(msg, 1, 0), validatorAddress: jspb.Message.getFieldWithDefault(msg, 2, ""), accountAddress: jspb.Message.getFieldWithDefault(msg, 3, ""), amount: jspb.Message.getFieldWithDefault(msg, 4, 0), fee: jspb.Message.getFieldWithDefault(msg, 5, 0), memo: jspb.Message.getFieldWithDefault(msg, 6, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetRawWithdrawTransactionRequest} */ proto.pactus.GetRawWithdrawTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetRawWithdrawTransactionRequest; return proto.pactus.GetRawWithdrawTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetRawWithdrawTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetRawWithdrawTransactionRequest} */ proto.pactus.GetRawWithdrawTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setLockTime(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setValidatorAddress(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAccountAddress(value); break; case 4: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; case 5: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; case 6: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetRawWithdrawTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetRawWithdrawTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawWithdrawTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getLockTime(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getValidatorAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAccountAddress(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 4, f ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 5, f ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 6, f ); } }; /** * optional uint32 lock_time = 1; * @return {number} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.getLockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawWithdrawTransactionRequest} returns this */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.setLockTime = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string validator_address = 2; * @return {string} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.getValidatorAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawWithdrawTransactionRequest} returns this */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.setValidatorAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string account_address = 3; * @return {string} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.getAccountAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawWithdrawTransactionRequest} returns this */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.setAccountAddress = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional int64 amount = 4; * @return {number} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawWithdrawTransactionRequest} returns this */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int64 fee = 5; * @return {number} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawWithdrawTransactionRequest} returns this */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * optional string memo = 6; * @return {string} */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 6, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawWithdrawTransactionRequest} returns this */ proto.pactus.GetRawWithdrawTransactionRequest.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 6, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.GetRawBatchTransferTransactionRequest.repeatedFields_ = [3]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetRawBatchTransferTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetRawBatchTransferTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawBatchTransferTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { lockTime: jspb.Message.getFieldWithDefault(msg, 1, 0), sender: jspb.Message.getFieldWithDefault(msg, 2, ""), recipientsList: jspb.Message.toObjectList(msg.getRecipientsList(), proto.pactus.Recipient.toObject, includeInstance), fee: jspb.Message.getFieldWithDefault(msg, 4, 0), memo: jspb.Message.getFieldWithDefault(msg, 5, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} */ proto.pactus.GetRawBatchTransferTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetRawBatchTransferTransactionRequest; return proto.pactus.GetRawBatchTransferTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetRawBatchTransferTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} */ proto.pactus.GetRawBatchTransferTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readUint32()); msg.setLockTime(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 3: var value = new proto.pactus.Recipient; reader.readMessage(value,proto.pactus.Recipient.deserializeBinaryFromReader); msg.addRecipients(value); break; case 4: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetRawBatchTransferTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetRawBatchTransferTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawBatchTransferTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getLockTime(); if (f !== 0) { writer.writeUint32( 1, f ); } f = message.getSender(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getRecipientsList(); if (f.length > 0) { writer.writeRepeatedMessage( 3, f, proto.pactus.Recipient.serializeBinaryToWriter ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 4, f ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 5, f ); } }; /** * optional uint32 lock_time = 1; * @return {number} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.getLockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} returns this */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.setLockTime = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string sender = 2; * @return {string} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} returns this */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * repeated Recipient recipients = 3; * @return {!Array} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.getRecipientsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.Recipient, 3)); }; /** * @param {!Array} value * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} returns this */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.setRecipientsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 3, value); }; /** * @param {!proto.pactus.Recipient=} opt_value * @param {number=} opt_index * @return {!proto.pactus.Recipient} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.addRecipients = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 3, opt_value, proto.pactus.Recipient, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} returns this */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.clearRecipientsList = function() { return this.setRecipientsList([]); }; /** * optional int64 fee = 4; * @return {number} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} returns this */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional string memo = 5; * @return {string} */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawBatchTransferTransactionRequest} returns this */ proto.pactus.GetRawBatchTransferTransactionRequest.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetRawTransactionResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetRawTransactionResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetRawTransactionResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawTransactionResponse.toObject = function(includeInstance, msg) { var f, obj = { rawTransaction: jspb.Message.getFieldWithDefault(msg, 1, ""), id: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetRawTransactionResponse} */ proto.pactus.GetRawTransactionResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetRawTransactionResponse; return proto.pactus.GetRawTransactionResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetRawTransactionResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetRawTransactionResponse} */ proto.pactus.GetRawTransactionResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setRawTransaction(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setId(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetRawTransactionResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetRawTransactionResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetRawTransactionResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetRawTransactionResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getRawTransaction(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getId(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string raw_transaction = 1; * @return {string} */ proto.pactus.GetRawTransactionResponse.prototype.getRawTransaction = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawTransactionResponse} returns this */ proto.pactus.GetRawTransactionResponse.prototype.setRawTransaction = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string id = 2; * @return {string} */ proto.pactus.GetRawTransactionResponse.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetRawTransactionResponse} returns this */ proto.pactus.GetRawTransactionResponse.prototype.setId = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PayloadTransfer.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PayloadTransfer.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PayloadTransfer} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadTransfer.toObject = function(includeInstance, msg) { var f, obj = { sender: jspb.Message.getFieldWithDefault(msg, 1, ""), receiver: jspb.Message.getFieldWithDefault(msg, 2, ""), amount: jspb.Message.getFieldWithDefault(msg, 3, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PayloadTransfer} */ proto.pactus.PayloadTransfer.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PayloadTransfer; return proto.pactus.PayloadTransfer.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PayloadTransfer} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PayloadTransfer} */ proto.pactus.PayloadTransfer.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReceiver(value); break; case 3: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PayloadTransfer.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PayloadTransfer.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PayloadTransfer} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadTransfer.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSender(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getReceiver(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 3, f ); } }; /** * optional string sender = 1; * @return {string} */ proto.pactus.PayloadTransfer.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadTransfer} returns this */ proto.pactus.PayloadTransfer.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string receiver = 2; * @return {string} */ proto.pactus.PayloadTransfer.prototype.getReceiver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadTransfer} returns this */ proto.pactus.PayloadTransfer.prototype.setReceiver = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int64 amount = 3; * @return {number} */ proto.pactus.PayloadTransfer.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.PayloadTransfer} returns this */ proto.pactus.PayloadTransfer.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PayloadBond.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PayloadBond.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PayloadBond} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadBond.toObject = function(includeInstance, msg) { var f, obj = { sender: jspb.Message.getFieldWithDefault(msg, 1, ""), receiver: jspb.Message.getFieldWithDefault(msg, 2, ""), stake: jspb.Message.getFieldWithDefault(msg, 3, 0), publicKey: jspb.Message.getFieldWithDefault(msg, 4, ""), isDelegated: jspb.Message.getBooleanFieldWithDefault(msg, 5, false), delegateOwner: jspb.Message.getFieldWithDefault(msg, 6, ""), delegateShare: jspb.Message.getFieldWithDefault(msg, 7, 0), delegateExpiry: jspb.Message.getFieldWithDefault(msg, 8, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PayloadBond} */ proto.pactus.PayloadBond.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PayloadBond; return proto.pactus.PayloadBond.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PayloadBond} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PayloadBond} */ proto.pactus.PayloadBond.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReceiver(value); break; case 3: var value = /** @type {number} */ (reader.readInt64()); msg.setStake(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; case 5: var value = /** @type {boolean} */ (reader.readBool()); msg.setIsDelegated(value); break; case 6: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setDelegateOwner(value); break; case 7: var value = /** @type {number} */ (reader.readInt64()); msg.setDelegateShare(value); break; case 8: var value = /** @type {number} */ (reader.readUint32()); msg.setDelegateExpiry(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PayloadBond.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PayloadBond.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PayloadBond} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadBond.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSender(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getReceiver(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getStake(); if (f !== 0) { writer.writeInt64( 3, f ); } f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 4, f ); } f = message.getIsDelegated(); if (f) { writer.writeBool( 5, f ); } f = message.getDelegateOwner(); if (f.length > 0) { writer.writeString( 6, f ); } f = message.getDelegateShare(); if (f !== 0) { writer.writeInt64( 7, f ); } f = message.getDelegateExpiry(); if (f !== 0) { writer.writeUint32( 8, f ); } }; /** * optional string sender = 1; * @return {string} */ proto.pactus.PayloadBond.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string receiver = 2; * @return {string} */ proto.pactus.PayloadBond.prototype.getReceiver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setReceiver = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int64 stake = 3; * @return {number} */ proto.pactus.PayloadBond.prototype.getStake = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setStake = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * optional string public_key = 4; * @return {string} */ proto.pactus.PayloadBond.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; /** * optional bool is_delegated = 5; * @return {boolean} */ proto.pactus.PayloadBond.prototype.getIsDelegated = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 5, false)); }; /** * @param {boolean} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setIsDelegated = function(value) { return jspb.Message.setProto3BooleanField(this, 5, value); }; /** * optional string delegate_owner = 6; * @return {string} */ proto.pactus.PayloadBond.prototype.getDelegateOwner = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 6, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setDelegateOwner = function(value) { return jspb.Message.setProto3StringField(this, 6, value); }; /** * optional int64 delegate_share = 7; * @return {number} */ proto.pactus.PayloadBond.prototype.getDelegateShare = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {number} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setDelegateShare = function(value) { return jspb.Message.setProto3IntField(this, 7, value); }; /** * optional uint32 delegate_expiry = 8; * @return {number} */ proto.pactus.PayloadBond.prototype.getDelegateExpiry = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 8, 0)); }; /** * @param {number} value * @return {!proto.pactus.PayloadBond} returns this */ proto.pactus.PayloadBond.prototype.setDelegateExpiry = function(value) { return jspb.Message.setProto3IntField(this, 8, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PayloadSortition.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PayloadSortition.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PayloadSortition} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadSortition.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, ""), proof: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PayloadSortition} */ proto.pactus.PayloadSortition.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PayloadSortition; return proto.pactus.PayloadSortition.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PayloadSortition} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PayloadSortition} */ proto.pactus.PayloadSortition.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setProof(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PayloadSortition.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PayloadSortition.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PayloadSortition} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadSortition.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getProof(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.PayloadSortition.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadSortition} returns this */ proto.pactus.PayloadSortition.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string proof = 2; * @return {string} */ proto.pactus.PayloadSortition.prototype.getProof = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadSortition} returns this */ proto.pactus.PayloadSortition.prototype.setProof = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PayloadUnbond.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PayloadUnbond.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PayloadUnbond} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadUnbond.toObject = function(includeInstance, msg) { var f, obj = { validator: jspb.Message.getFieldWithDefault(msg, 1, ""), delegateOwner: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PayloadUnbond} */ proto.pactus.PayloadUnbond.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PayloadUnbond; return proto.pactus.PayloadUnbond.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PayloadUnbond} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PayloadUnbond} */ proto.pactus.PayloadUnbond.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setValidator(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setDelegateOwner(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PayloadUnbond.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PayloadUnbond.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PayloadUnbond} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadUnbond.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getValidator(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getDelegateOwner(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string validator = 1; * @return {string} */ proto.pactus.PayloadUnbond.prototype.getValidator = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadUnbond} returns this */ proto.pactus.PayloadUnbond.prototype.setValidator = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string delegate_owner = 2; * @return {string} */ proto.pactus.PayloadUnbond.prototype.getDelegateOwner = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadUnbond} returns this */ proto.pactus.PayloadUnbond.prototype.setDelegateOwner = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PayloadWithdraw.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PayloadWithdraw.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PayloadWithdraw} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadWithdraw.toObject = function(includeInstance, msg) { var f, obj = { validatorAddress: jspb.Message.getFieldWithDefault(msg, 1, ""), accountAddress: jspb.Message.getFieldWithDefault(msg, 2, ""), amount: jspb.Message.getFieldWithDefault(msg, 3, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PayloadWithdraw} */ proto.pactus.PayloadWithdraw.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PayloadWithdraw; return proto.pactus.PayloadWithdraw.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PayloadWithdraw} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PayloadWithdraw} */ proto.pactus.PayloadWithdraw.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setValidatorAddress(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAccountAddress(value); break; case 3: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PayloadWithdraw.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PayloadWithdraw.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PayloadWithdraw} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadWithdraw.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getValidatorAddress(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAccountAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 3, f ); } }; /** * optional string validator_address = 1; * @return {string} */ proto.pactus.PayloadWithdraw.prototype.getValidatorAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadWithdraw} returns this */ proto.pactus.PayloadWithdraw.prototype.setValidatorAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string account_address = 2; * @return {string} */ proto.pactus.PayloadWithdraw.prototype.getAccountAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadWithdraw} returns this */ proto.pactus.PayloadWithdraw.prototype.setAccountAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int64 amount = 3; * @return {number} */ proto.pactus.PayloadWithdraw.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.PayloadWithdraw} returns this */ proto.pactus.PayloadWithdraw.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.PayloadBatchTransfer.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PayloadBatchTransfer.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PayloadBatchTransfer.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PayloadBatchTransfer} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadBatchTransfer.toObject = function(includeInstance, msg) { var f, obj = { sender: jspb.Message.getFieldWithDefault(msg, 1, ""), recipientsList: jspb.Message.toObjectList(msg.getRecipientsList(), proto.pactus.Recipient.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PayloadBatchTransfer} */ proto.pactus.PayloadBatchTransfer.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PayloadBatchTransfer; return proto.pactus.PayloadBatchTransfer.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PayloadBatchTransfer} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PayloadBatchTransfer} */ proto.pactus.PayloadBatchTransfer.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 2: var value = new proto.pactus.Recipient; reader.readMessage(value,proto.pactus.Recipient.deserializeBinaryFromReader); msg.addRecipients(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PayloadBatchTransfer.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PayloadBatchTransfer.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PayloadBatchTransfer} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PayloadBatchTransfer.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSender(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getRecipientsList(); if (f.length > 0) { writer.writeRepeatedMessage( 2, f, proto.pactus.Recipient.serializeBinaryToWriter ); } }; /** * optional string sender = 1; * @return {string} */ proto.pactus.PayloadBatchTransfer.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PayloadBatchTransfer} returns this */ proto.pactus.PayloadBatchTransfer.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * repeated Recipient recipients = 2; * @return {!Array} */ proto.pactus.PayloadBatchTransfer.prototype.getRecipientsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.Recipient, 2)); }; /** * @param {!Array} value * @return {!proto.pactus.PayloadBatchTransfer} returns this */ proto.pactus.PayloadBatchTransfer.prototype.setRecipientsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 2, value); }; /** * @param {!proto.pactus.Recipient=} opt_value * @param {number=} opt_index * @return {!proto.pactus.Recipient} */ proto.pactus.PayloadBatchTransfer.prototype.addRecipients = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 2, opt_value, proto.pactus.Recipient, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.PayloadBatchTransfer} returns this */ proto.pactus.PayloadBatchTransfer.prototype.clearRecipientsList = function() { return this.setRecipientsList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.Recipient.prototype.toObject = function(opt_includeInstance) { return proto.pactus.Recipient.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.Recipient} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.Recipient.toObject = function(includeInstance, msg) { var f, obj = { receiver: jspb.Message.getFieldWithDefault(msg, 1, ""), amount: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.Recipient} */ proto.pactus.Recipient.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.Recipient; return proto.pactus.Recipient.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.Recipient} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.Recipient} */ proto.pactus.Recipient.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReceiver(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.Recipient.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.Recipient.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.Recipient} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.Recipient.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getReceiver(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 2, f ); } }; /** * optional string receiver = 1; * @return {string} */ proto.pactus.Recipient.prototype.getReceiver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.Recipient} returns this */ proto.pactus.Recipient.prototype.setReceiver = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional int64 amount = 2; * @return {number} */ proto.pactus.Recipient.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.Recipient} returns this */ proto.pactus.Recipient.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * Oneof group definitions for this message. Each group defines the field * numbers belonging to that group. When of these fields' value is set, all * other fields in the group are cleared. During deserialization, if multiple * fields are encountered for a group, only the last value seen will be kept. * @private {!Array>} * @const */ proto.pactus.TransactionInfo.oneofGroups_ = [[30,31,32,33,34,35]]; /** * @enum {number} */ proto.pactus.TransactionInfo.PayloadCase = { PAYLOAD_NOT_SET: 0, TRANSFER: 30, BOND: 31, SORTITION: 32, UNBOND: 33, WITHDRAW: 34, BATCH_TRANSFER: 35 }; /** * @return {proto.pactus.TransactionInfo.PayloadCase} */ proto.pactus.TransactionInfo.prototype.getPayloadCase = function() { return /** @type {proto.pactus.TransactionInfo.PayloadCase} */(jspb.Message.computeOneofCase(this, proto.pactus.TransactionInfo.oneofGroups_[0])); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.TransactionInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.TransactionInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.TransactionInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.TransactionInfo.toObject = function(includeInstance, msg) { var f, obj = { id: jspb.Message.getFieldWithDefault(msg, 1, ""), data: jspb.Message.getFieldWithDefault(msg, 2, ""), version: jspb.Message.getFieldWithDefault(msg, 3, 0), lockTime: jspb.Message.getFieldWithDefault(msg, 4, 0), value: jspb.Message.getFieldWithDefault(msg, 5, 0), fee: jspb.Message.getFieldWithDefault(msg, 6, 0), payloadType: jspb.Message.getFieldWithDefault(msg, 7, 0), transfer: (f = msg.getTransfer()) && proto.pactus.PayloadTransfer.toObject(includeInstance, f), bond: (f = msg.getBond()) && proto.pactus.PayloadBond.toObject(includeInstance, f), sortition: (f = msg.getSortition()) && proto.pactus.PayloadSortition.toObject(includeInstance, f), unbond: (f = msg.getUnbond()) && proto.pactus.PayloadUnbond.toObject(includeInstance, f), withdraw: (f = msg.getWithdraw()) && proto.pactus.PayloadWithdraw.toObject(includeInstance, f), batchTransfer: (f = msg.getBatchTransfer()) && proto.pactus.PayloadBatchTransfer.toObject(includeInstance, f), memo: jspb.Message.getFieldWithDefault(msg, 8, ""), publicKey: jspb.Message.getFieldWithDefault(msg, 9, ""), signature: jspb.Message.getFieldWithDefault(msg, 10, ""), blockHeight: jspb.Message.getFieldWithDefault(msg, 11, 0), confirmed: jspb.Message.getBooleanFieldWithDefault(msg, 12, false), confirmations: jspb.Message.getFieldWithDefault(msg, 13, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.TransactionInfo} */ proto.pactus.TransactionInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.TransactionInfo; return proto.pactus.TransactionInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.TransactionInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.TransactionInfo} */ proto.pactus.TransactionInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setId(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setData(value); break; case 3: var value = /** @type {number} */ (reader.readInt32()); msg.setVersion(value); break; case 4: var value = /** @type {number} */ (reader.readUint32()); msg.setLockTime(value); break; case 5: var value = /** @type {number} */ (reader.readInt64()); msg.setValue(value); break; case 6: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; case 7: var value = /** @type {!proto.pactus.PayloadType} */ (reader.readEnum()); msg.setPayloadType(value); break; case 30: var value = new proto.pactus.PayloadTransfer; reader.readMessage(value,proto.pactus.PayloadTransfer.deserializeBinaryFromReader); msg.setTransfer(value); break; case 31: var value = new proto.pactus.PayloadBond; reader.readMessage(value,proto.pactus.PayloadBond.deserializeBinaryFromReader); msg.setBond(value); break; case 32: var value = new proto.pactus.PayloadSortition; reader.readMessage(value,proto.pactus.PayloadSortition.deserializeBinaryFromReader); msg.setSortition(value); break; case 33: var value = new proto.pactus.PayloadUnbond; reader.readMessage(value,proto.pactus.PayloadUnbond.deserializeBinaryFromReader); msg.setUnbond(value); break; case 34: var value = new proto.pactus.PayloadWithdraw; reader.readMessage(value,proto.pactus.PayloadWithdraw.deserializeBinaryFromReader); msg.setWithdraw(value); break; case 35: var value = new proto.pactus.PayloadBatchTransfer; reader.readMessage(value,proto.pactus.PayloadBatchTransfer.deserializeBinaryFromReader); msg.setBatchTransfer(value); break; case 8: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; case 9: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; case 10: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; case 11: var value = /** @type {number} */ (reader.readUint32()); msg.setBlockHeight(value); break; case 12: var value = /** @type {boolean} */ (reader.readBool()); msg.setConfirmed(value); break; case 13: var value = /** @type {number} */ (reader.readInt32()); msg.setConfirmations(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.TransactionInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.TransactionInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.TransactionInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.TransactionInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getId(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getData(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getVersion(); if (f !== 0) { writer.writeInt32( 3, f ); } f = message.getLockTime(); if (f !== 0) { writer.writeUint32( 4, f ); } f = message.getValue(); if (f !== 0) { writer.writeInt64( 5, f ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 6, f ); } f = message.getPayloadType(); if (f !== 0.0) { writer.writeEnum( 7, f ); } f = message.getTransfer(); if (f != null) { writer.writeMessage( 30, f, proto.pactus.PayloadTransfer.serializeBinaryToWriter ); } f = message.getBond(); if (f != null) { writer.writeMessage( 31, f, proto.pactus.PayloadBond.serializeBinaryToWriter ); } f = message.getSortition(); if (f != null) { writer.writeMessage( 32, f, proto.pactus.PayloadSortition.serializeBinaryToWriter ); } f = message.getUnbond(); if (f != null) { writer.writeMessage( 33, f, proto.pactus.PayloadUnbond.serializeBinaryToWriter ); } f = message.getWithdraw(); if (f != null) { writer.writeMessage( 34, f, proto.pactus.PayloadWithdraw.serializeBinaryToWriter ); } f = message.getBatchTransfer(); if (f != null) { writer.writeMessage( 35, f, proto.pactus.PayloadBatchTransfer.serializeBinaryToWriter ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 8, f ); } f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 9, f ); } f = message.getSignature(); if (f.length > 0) { writer.writeString( 10, f ); } f = message.getBlockHeight(); if (f !== 0) { writer.writeUint32( 11, f ); } f = message.getConfirmed(); if (f) { writer.writeBool( 12, f ); } f = message.getConfirmations(); if (f !== 0) { writer.writeInt32( 13, f ); } }; /** * optional string id = 1; * @return {string} */ proto.pactus.TransactionInfo.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setId = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string data = 2; * @return {string} */ proto.pactus.TransactionInfo.prototype.getData = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setData = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional int32 version = 3; * @return {number} */ proto.pactus.TransactionInfo.prototype.getVersion = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {number} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setVersion = function(value) { return jspb.Message.setProto3IntField(this, 3, value); }; /** * optional uint32 lock_time = 4; * @return {number} */ proto.pactus.TransactionInfo.prototype.getLockTime = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setLockTime = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int64 value = 5; * @return {number} */ proto.pactus.TransactionInfo.prototype.getValue = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setValue = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * optional int64 fee = 6; * @return {number} */ proto.pactus.TransactionInfo.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional PayloadType payload_type = 7; * @return {!proto.pactus.PayloadType} */ proto.pactus.TransactionInfo.prototype.getPayloadType = function() { return /** @type {!proto.pactus.PayloadType} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {!proto.pactus.PayloadType} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setPayloadType = function(value) { return jspb.Message.setProto3EnumField(this, 7, value); }; /** * optional PayloadTransfer transfer = 30; * @return {?proto.pactus.PayloadTransfer} */ proto.pactus.TransactionInfo.prototype.getTransfer = function() { return /** @type{?proto.pactus.PayloadTransfer} */ ( jspb.Message.getWrapperField(this, proto.pactus.PayloadTransfer, 30)); }; /** * @param {?proto.pactus.PayloadTransfer|undefined} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setTransfer = function(value) { return jspb.Message.setOneofWrapperField(this, 30, proto.pactus.TransactionInfo.oneofGroups_[0], value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.clearTransfer = function() { return this.setTransfer(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.TransactionInfo.prototype.hasTransfer = function() { return jspb.Message.getField(this, 30) != null; }; /** * optional PayloadBond bond = 31; * @return {?proto.pactus.PayloadBond} */ proto.pactus.TransactionInfo.prototype.getBond = function() { return /** @type{?proto.pactus.PayloadBond} */ ( jspb.Message.getWrapperField(this, proto.pactus.PayloadBond, 31)); }; /** * @param {?proto.pactus.PayloadBond|undefined} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setBond = function(value) { return jspb.Message.setOneofWrapperField(this, 31, proto.pactus.TransactionInfo.oneofGroups_[0], value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.clearBond = function() { return this.setBond(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.TransactionInfo.prototype.hasBond = function() { return jspb.Message.getField(this, 31) != null; }; /** * optional PayloadSortition sortition = 32; * @return {?proto.pactus.PayloadSortition} */ proto.pactus.TransactionInfo.prototype.getSortition = function() { return /** @type{?proto.pactus.PayloadSortition} */ ( jspb.Message.getWrapperField(this, proto.pactus.PayloadSortition, 32)); }; /** * @param {?proto.pactus.PayloadSortition|undefined} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setSortition = function(value) { return jspb.Message.setOneofWrapperField(this, 32, proto.pactus.TransactionInfo.oneofGroups_[0], value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.clearSortition = function() { return this.setSortition(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.TransactionInfo.prototype.hasSortition = function() { return jspb.Message.getField(this, 32) != null; }; /** * optional PayloadUnbond unbond = 33; * @return {?proto.pactus.PayloadUnbond} */ proto.pactus.TransactionInfo.prototype.getUnbond = function() { return /** @type{?proto.pactus.PayloadUnbond} */ ( jspb.Message.getWrapperField(this, proto.pactus.PayloadUnbond, 33)); }; /** * @param {?proto.pactus.PayloadUnbond|undefined} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setUnbond = function(value) { return jspb.Message.setOneofWrapperField(this, 33, proto.pactus.TransactionInfo.oneofGroups_[0], value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.clearUnbond = function() { return this.setUnbond(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.TransactionInfo.prototype.hasUnbond = function() { return jspb.Message.getField(this, 33) != null; }; /** * optional PayloadWithdraw withdraw = 34; * @return {?proto.pactus.PayloadWithdraw} */ proto.pactus.TransactionInfo.prototype.getWithdraw = function() { return /** @type{?proto.pactus.PayloadWithdraw} */ ( jspb.Message.getWrapperField(this, proto.pactus.PayloadWithdraw, 34)); }; /** * @param {?proto.pactus.PayloadWithdraw|undefined} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setWithdraw = function(value) { return jspb.Message.setOneofWrapperField(this, 34, proto.pactus.TransactionInfo.oneofGroups_[0], value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.clearWithdraw = function() { return this.setWithdraw(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.TransactionInfo.prototype.hasWithdraw = function() { return jspb.Message.getField(this, 34) != null; }; /** * optional PayloadBatchTransfer batch_transfer = 35; * @return {?proto.pactus.PayloadBatchTransfer} */ proto.pactus.TransactionInfo.prototype.getBatchTransfer = function() { return /** @type{?proto.pactus.PayloadBatchTransfer} */ ( jspb.Message.getWrapperField(this, proto.pactus.PayloadBatchTransfer, 35)); }; /** * @param {?proto.pactus.PayloadBatchTransfer|undefined} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setBatchTransfer = function(value) { return jspb.Message.setOneofWrapperField(this, 35, proto.pactus.TransactionInfo.oneofGroups_[0], value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.clearBatchTransfer = function() { return this.setBatchTransfer(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.TransactionInfo.prototype.hasBatchTransfer = function() { return jspb.Message.getField(this, 35) != null; }; /** * optional string memo = 8; * @return {string} */ proto.pactus.TransactionInfo.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, "")); }; /** * @param {string} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 8, value); }; /** * optional string public_key = 9; * @return {string} */ proto.pactus.TransactionInfo.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 9, "")); }; /** * @param {string} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 9, value); }; /** * optional string signature = 10; * @return {string} */ proto.pactus.TransactionInfo.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 10, "")); }; /** * @param {string} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 10, value); }; /** * optional uint32 block_height = 11; * @return {number} */ proto.pactus.TransactionInfo.prototype.getBlockHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 11, 0)); }; /** * @param {number} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setBlockHeight = function(value) { return jspb.Message.setProto3IntField(this, 11, value); }; /** * optional bool confirmed = 12; * @return {boolean} */ proto.pactus.TransactionInfo.prototype.getConfirmed = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 12, false)); }; /** * @param {boolean} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setConfirmed = function(value) { return jspb.Message.setProto3BooleanField(this, 12, value); }; /** * optional int32 confirmations = 13; * @return {number} */ proto.pactus.TransactionInfo.prototype.getConfirmations = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 13, 0)); }; /** * @param {number} value * @return {!proto.pactus.TransactionInfo} returns this */ proto.pactus.TransactionInfo.prototype.setConfirmations = function(value) { return jspb.Message.setProto3IntField(this, 13, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.DecodeRawTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.DecodeRawTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.DecodeRawTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.DecodeRawTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { rawTransaction: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.DecodeRawTransactionRequest} */ proto.pactus.DecodeRawTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.DecodeRawTransactionRequest; return proto.pactus.DecodeRawTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.DecodeRawTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.DecodeRawTransactionRequest} */ proto.pactus.DecodeRawTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setRawTransaction(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.DecodeRawTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.DecodeRawTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.DecodeRawTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.DecodeRawTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getRawTransaction(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string raw_transaction = 1; * @return {string} */ proto.pactus.DecodeRawTransactionRequest.prototype.getRawTransaction = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.DecodeRawTransactionRequest} returns this */ proto.pactus.DecodeRawTransactionRequest.prototype.setRawTransaction = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.DecodeRawTransactionResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.DecodeRawTransactionResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.DecodeRawTransactionResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.DecodeRawTransactionResponse.toObject = function(includeInstance, msg) { var f, obj = { transaction: (f = msg.getTransaction()) && proto.pactus.TransactionInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.DecodeRawTransactionResponse} */ proto.pactus.DecodeRawTransactionResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.DecodeRawTransactionResponse; return proto.pactus.DecodeRawTransactionResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.DecodeRawTransactionResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.DecodeRawTransactionResponse} */ proto.pactus.DecodeRawTransactionResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.pactus.TransactionInfo; reader.readMessage(value,proto.pactus.TransactionInfo.deserializeBinaryFromReader); msg.setTransaction(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.DecodeRawTransactionResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.DecodeRawTransactionResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.DecodeRawTransactionResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.DecodeRawTransactionResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getTransaction(); if (f != null) { writer.writeMessage( 1, f, proto.pactus.TransactionInfo.serializeBinaryToWriter ); } }; /** * optional TransactionInfo transaction = 1; * @return {?proto.pactus.TransactionInfo} */ proto.pactus.DecodeRawTransactionResponse.prototype.getTransaction = function() { return /** @type{?proto.pactus.TransactionInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.TransactionInfo, 1)); }; /** * @param {?proto.pactus.TransactionInfo|undefined} value * @return {!proto.pactus.DecodeRawTransactionResponse} returns this */ proto.pactus.DecodeRawTransactionResponse.prototype.setTransaction = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.DecodeRawTransactionResponse} returns this */ proto.pactus.DecodeRawTransactionResponse.prototype.clearTransaction = function() { return this.setTransaction(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.DecodeRawTransactionResponse.prototype.hasTransaction = function() { return jspb.Message.getField(this, 1) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CheckTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CheckTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CheckTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CheckTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { rawTransaction: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CheckTransactionRequest} */ proto.pactus.CheckTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CheckTransactionRequest; return proto.pactus.CheckTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CheckTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CheckTransactionRequest} */ proto.pactus.CheckTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setRawTransaction(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CheckTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CheckTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CheckTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CheckTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getRawTransaction(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string raw_transaction = 1; * @return {string} */ proto.pactus.CheckTransactionRequest.prototype.getRawTransaction = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.CheckTransactionRequest} returns this */ proto.pactus.CheckTransactionRequest.prototype.setRawTransaction = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CheckTransactionResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CheckTransactionResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CheckTransactionResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CheckTransactionResponse.toObject = function(includeInstance, msg) { var f, obj = { isValid: jspb.Message.getBooleanFieldWithDefault(msg, 1, false), errorMessage: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CheckTransactionResponse} */ proto.pactus.CheckTransactionResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CheckTransactionResponse; return proto.pactus.CheckTransactionResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CheckTransactionResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CheckTransactionResponse} */ proto.pactus.CheckTransactionResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {boolean} */ (reader.readBool()); msg.setIsValid(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setErrorMessage(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CheckTransactionResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CheckTransactionResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CheckTransactionResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CheckTransactionResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getIsValid(); if (f) { writer.writeBool( 1, f ); } f = message.getErrorMessage(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional bool is_valid = 1; * @return {boolean} */ proto.pactus.CheckTransactionResponse.prototype.getIsValid = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); }; /** * @param {boolean} value * @return {!proto.pactus.CheckTransactionResponse} returns this */ proto.pactus.CheckTransactionResponse.prototype.setIsValid = function(value) { return jspb.Message.setProto3BooleanField(this, 1, value); }; /** * optional string error_message = 2; * @return {string} */ proto.pactus.CheckTransactionResponse.prototype.getErrorMessage = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.CheckTransactionResponse} returns this */ proto.pactus.CheckTransactionResponse.prototype.setErrorMessage = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * @enum {number} */ proto.pactus.PayloadType = { PAYLOAD_TYPE_UNSPECIFIED: 0, PAYLOAD_TYPE_TRANSFER: 1, PAYLOAD_TYPE_BOND: 2, PAYLOAD_TYPE_SORTITION: 3, PAYLOAD_TYPE_UNBOND: 4, PAYLOAD_TYPE_WITHDRAW: 5, PAYLOAD_TYPE_BATCH_TRANSFER: 6 }; /** * @enum {number} */ proto.pactus.TransactionVerbosity = { TRANSACTION_VERBOSITY_DATA: 0, TRANSACTION_VERBOSITY_INFO: 1 }; goog.object.extend(exports, proto.pactus); ================================================ FILE: www/grpc/gen/js/utils_grpc_pb.js ================================================ // GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('@grpc/grpc-js'); var utils_pb = require('./utils_pb.js'); function serialize_pactus_PublicKeyAggregationRequest(arg) { if (!(arg instanceof utils_pb.PublicKeyAggregationRequest)) { throw new Error('Expected argument of type pactus.PublicKeyAggregationRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_PublicKeyAggregationRequest(buffer_arg) { return utils_pb.PublicKeyAggregationRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_PublicKeyAggregationResponse(arg) { if (!(arg instanceof utils_pb.PublicKeyAggregationResponse)) { throw new Error('Expected argument of type pactus.PublicKeyAggregationResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_PublicKeyAggregationResponse(buffer_arg) { return utils_pb.PublicKeyAggregationResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignMessageWithPrivateKeyRequest(arg) { if (!(arg instanceof utils_pb.SignMessageWithPrivateKeyRequest)) { throw new Error('Expected argument of type pactus.SignMessageWithPrivateKeyRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignMessageWithPrivateKeyRequest(buffer_arg) { return utils_pb.SignMessageWithPrivateKeyRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignMessageWithPrivateKeyResponse(arg) { if (!(arg instanceof utils_pb.SignMessageWithPrivateKeyResponse)) { throw new Error('Expected argument of type pactus.SignMessageWithPrivateKeyResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignMessageWithPrivateKeyResponse(buffer_arg) { return utils_pb.SignMessageWithPrivateKeyResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignatureAggregationRequest(arg) { if (!(arg instanceof utils_pb.SignatureAggregationRequest)) { throw new Error('Expected argument of type pactus.SignatureAggregationRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignatureAggregationRequest(buffer_arg) { return utils_pb.SignatureAggregationRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignatureAggregationResponse(arg) { if (!(arg instanceof utils_pb.SignatureAggregationResponse)) { throw new Error('Expected argument of type pactus.SignatureAggregationResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignatureAggregationResponse(buffer_arg) { return utils_pb.SignatureAggregationResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_VerifyMessageRequest(arg) { if (!(arg instanceof utils_pb.VerifyMessageRequest)) { throw new Error('Expected argument of type pactus.VerifyMessageRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_VerifyMessageRequest(buffer_arg) { return utils_pb.VerifyMessageRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_VerifyMessageResponse(arg) { if (!(arg instanceof utils_pb.VerifyMessageResponse)) { throw new Error('Expected argument of type pactus.VerifyMessageResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_VerifyMessageResponse(buffer_arg) { return utils_pb.VerifyMessageResponse.deserializeBinary(new Uint8Array(buffer_arg)); } // Utils service defines RPC methods for utility functions such as message // signing, verification, and other cryptographic operations. var UtilsService = exports.UtilsService = { // SignMessageWithPrivateKey signs a message with the provided private key. signMessageWithPrivateKey: { path: '/pactus.Utils/SignMessageWithPrivateKey', requestStream: false, responseStream: false, requestType: utils_pb.SignMessageWithPrivateKeyRequest, responseType: utils_pb.SignMessageWithPrivateKeyResponse, requestSerialize: serialize_pactus_SignMessageWithPrivateKeyRequest, requestDeserialize: deserialize_pactus_SignMessageWithPrivateKeyRequest, responseSerialize: serialize_pactus_SignMessageWithPrivateKeyResponse, responseDeserialize: deserialize_pactus_SignMessageWithPrivateKeyResponse, }, // VerifyMessage verifies a signature against the public key and message. verifyMessage: { path: '/pactus.Utils/VerifyMessage', requestStream: false, responseStream: false, requestType: utils_pb.VerifyMessageRequest, responseType: utils_pb.VerifyMessageResponse, requestSerialize: serialize_pactus_VerifyMessageRequest, requestDeserialize: deserialize_pactus_VerifyMessageRequest, responseSerialize: serialize_pactus_VerifyMessageResponse, responseDeserialize: deserialize_pactus_VerifyMessageResponse, }, // PublicKeyAggregation aggregates multiple BLS public keys into a single key. publicKeyAggregation: { path: '/pactus.Utils/PublicKeyAggregation', requestStream: false, responseStream: false, requestType: utils_pb.PublicKeyAggregationRequest, responseType: utils_pb.PublicKeyAggregationResponse, requestSerialize: serialize_pactus_PublicKeyAggregationRequest, requestDeserialize: deserialize_pactus_PublicKeyAggregationRequest, responseSerialize: serialize_pactus_PublicKeyAggregationResponse, responseDeserialize: deserialize_pactus_PublicKeyAggregationResponse, }, // SignatureAggregation aggregates multiple BLS signatures into a single signature. signatureAggregation: { path: '/pactus.Utils/SignatureAggregation', requestStream: false, responseStream: false, requestType: utils_pb.SignatureAggregationRequest, responseType: utils_pb.SignatureAggregationResponse, requestSerialize: serialize_pactus_SignatureAggregationRequest, requestDeserialize: deserialize_pactus_SignatureAggregationRequest, responseSerialize: serialize_pactus_SignatureAggregationResponse, responseDeserialize: deserialize_pactus_SignatureAggregationResponse, }, }; exports.UtilsClient = grpc.makeGenericClientConstructor(UtilsService, 'Utils'); ================================================ FILE: www/grpc/gen/js/utils_grpc_web_pb.js ================================================ /** * @fileoverview gRPC-Web generated client stub for pactus * @enhanceable * @public */ // Code generated by protoc-gen-grpc-web. DO NOT EDIT. // versions: // protoc-gen-grpc-web v2.0.2 // protoc v0.0.0 // source: utils.proto /* eslint-disable */ // @ts-nocheck const grpc = {}; grpc.web = require('grpc-web'); const proto = {}; proto.pactus = require('./utils_pb.js'); /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.UtilsClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.UtilsPromiseClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.SignMessageWithPrivateKeyRequest, * !proto.pactus.SignMessageWithPrivateKeyResponse>} */ const methodDescriptor_Utils_SignMessageWithPrivateKey = new grpc.web.MethodDescriptor( '/pactus.Utils/SignMessageWithPrivateKey', grpc.web.MethodType.UNARY, proto.pactus.SignMessageWithPrivateKeyRequest, proto.pactus.SignMessageWithPrivateKeyResponse, /** * @param {!proto.pactus.SignMessageWithPrivateKeyRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.SignMessageWithPrivateKeyResponse.deserializeBinary ); /** * @param {!proto.pactus.SignMessageWithPrivateKeyRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.SignMessageWithPrivateKeyResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.UtilsClient.prototype.signMessageWithPrivateKey = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Utils/SignMessageWithPrivateKey', request, metadata || {}, methodDescriptor_Utils_SignMessageWithPrivateKey, callback); }; /** * @param {!proto.pactus.SignMessageWithPrivateKeyRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.UtilsPromiseClient.prototype.signMessageWithPrivateKey = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Utils/SignMessageWithPrivateKey', request, metadata || {}, methodDescriptor_Utils_SignMessageWithPrivateKey); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.VerifyMessageRequest, * !proto.pactus.VerifyMessageResponse>} */ const methodDescriptor_Utils_VerifyMessage = new grpc.web.MethodDescriptor( '/pactus.Utils/VerifyMessage', grpc.web.MethodType.UNARY, proto.pactus.VerifyMessageRequest, proto.pactus.VerifyMessageResponse, /** * @param {!proto.pactus.VerifyMessageRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.VerifyMessageResponse.deserializeBinary ); /** * @param {!proto.pactus.VerifyMessageRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.VerifyMessageResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.UtilsClient.prototype.verifyMessage = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Utils/VerifyMessage', request, metadata || {}, methodDescriptor_Utils_VerifyMessage, callback); }; /** * @param {!proto.pactus.VerifyMessageRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.UtilsPromiseClient.prototype.verifyMessage = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Utils/VerifyMessage', request, metadata || {}, methodDescriptor_Utils_VerifyMessage); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.PublicKeyAggregationRequest, * !proto.pactus.PublicKeyAggregationResponse>} */ const methodDescriptor_Utils_PublicKeyAggregation = new grpc.web.MethodDescriptor( '/pactus.Utils/PublicKeyAggregation', grpc.web.MethodType.UNARY, proto.pactus.PublicKeyAggregationRequest, proto.pactus.PublicKeyAggregationResponse, /** * @param {!proto.pactus.PublicKeyAggregationRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.PublicKeyAggregationResponse.deserializeBinary ); /** * @param {!proto.pactus.PublicKeyAggregationRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.PublicKeyAggregationResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.UtilsClient.prototype.publicKeyAggregation = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Utils/PublicKeyAggregation', request, metadata || {}, methodDescriptor_Utils_PublicKeyAggregation, callback); }; /** * @param {!proto.pactus.PublicKeyAggregationRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.UtilsPromiseClient.prototype.publicKeyAggregation = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Utils/PublicKeyAggregation', request, metadata || {}, methodDescriptor_Utils_PublicKeyAggregation); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.SignatureAggregationRequest, * !proto.pactus.SignatureAggregationResponse>} */ const methodDescriptor_Utils_SignatureAggregation = new grpc.web.MethodDescriptor( '/pactus.Utils/SignatureAggregation', grpc.web.MethodType.UNARY, proto.pactus.SignatureAggregationRequest, proto.pactus.SignatureAggregationResponse, /** * @param {!proto.pactus.SignatureAggregationRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.SignatureAggregationResponse.deserializeBinary ); /** * @param {!proto.pactus.SignatureAggregationRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.SignatureAggregationResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.UtilsClient.prototype.signatureAggregation = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Utils/SignatureAggregation', request, metadata || {}, methodDescriptor_Utils_SignatureAggregation, callback); }; /** * @param {!proto.pactus.SignatureAggregationRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.UtilsPromiseClient.prototype.signatureAggregation = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Utils/SignatureAggregation', request, metadata || {}, methodDescriptor_Utils_SignatureAggregation); }; module.exports = proto.pactus; ================================================ FILE: www/grpc/gen/js/utils_pb.js ================================================ // source: utils.proto /** * @fileoverview * @enhanceable * @suppress {missingRequire} reports error on implicit type usages. * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var global = globalThis; goog.exportSymbol('proto.pactus.PublicKeyAggregationRequest', null, global); goog.exportSymbol('proto.pactus.PublicKeyAggregationResponse', null, global); goog.exportSymbol('proto.pactus.SignMessageWithPrivateKeyRequest', null, global); goog.exportSymbol('proto.pactus.SignMessageWithPrivateKeyResponse', null, global); goog.exportSymbol('proto.pactus.SignatureAggregationRequest', null, global); goog.exportSymbol('proto.pactus.SignatureAggregationResponse', null, global); goog.exportSymbol('proto.pactus.VerifyMessageRequest', null, global); goog.exportSymbol('proto.pactus.VerifyMessageResponse', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignMessageWithPrivateKeyRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignMessageWithPrivateKeyRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignMessageWithPrivateKeyRequest.displayName = 'proto.pactus.SignMessageWithPrivateKeyRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignMessageWithPrivateKeyResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignMessageWithPrivateKeyResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignMessageWithPrivateKeyResponse.displayName = 'proto.pactus.SignMessageWithPrivateKeyResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.VerifyMessageRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.VerifyMessageRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.VerifyMessageRequest.displayName = 'proto.pactus.VerifyMessageRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.VerifyMessageResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.VerifyMessageResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.VerifyMessageResponse.displayName = 'proto.pactus.VerifyMessageResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PublicKeyAggregationRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.PublicKeyAggregationRequest.repeatedFields_, null); }; goog.inherits(proto.pactus.PublicKeyAggregationRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PublicKeyAggregationRequest.displayName = 'proto.pactus.PublicKeyAggregationRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.PublicKeyAggregationResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.PublicKeyAggregationResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.PublicKeyAggregationResponse.displayName = 'proto.pactus.PublicKeyAggregationResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignatureAggregationRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.SignatureAggregationRequest.repeatedFields_, null); }; goog.inherits(proto.pactus.SignatureAggregationRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignatureAggregationRequest.displayName = 'proto.pactus.SignatureAggregationRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignatureAggregationResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignatureAggregationResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignatureAggregationResponse.displayName = 'proto.pactus.SignatureAggregationResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignMessageWithPrivateKeyRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignMessageWithPrivateKeyRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignMessageWithPrivateKeyRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageWithPrivateKeyRequest.toObject = function(includeInstance, msg) { var f, obj = { privateKey: jspb.Message.getFieldWithDefault(msg, 1, ""), message: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignMessageWithPrivateKeyRequest} */ proto.pactus.SignMessageWithPrivateKeyRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignMessageWithPrivateKeyRequest; return proto.pactus.SignMessageWithPrivateKeyRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignMessageWithPrivateKeyRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignMessageWithPrivateKeyRequest} */ proto.pactus.SignMessageWithPrivateKeyRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPrivateKey(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMessage(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignMessageWithPrivateKeyRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignMessageWithPrivateKeyRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignMessageWithPrivateKeyRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageWithPrivateKeyRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPrivateKey(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getMessage(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string private_key = 1; * @return {string} */ proto.pactus.SignMessageWithPrivateKeyRequest.prototype.getPrivateKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageWithPrivateKeyRequest} returns this */ proto.pactus.SignMessageWithPrivateKeyRequest.prototype.setPrivateKey = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string message = 2; * @return {string} */ proto.pactus.SignMessageWithPrivateKeyRequest.prototype.getMessage = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageWithPrivateKeyRequest} returns this */ proto.pactus.SignMessageWithPrivateKeyRequest.prototype.setMessage = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignMessageWithPrivateKeyResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignMessageWithPrivateKeyResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignMessageWithPrivateKeyResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageWithPrivateKeyResponse.toObject = function(includeInstance, msg) { var f, obj = { signature: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignMessageWithPrivateKeyResponse} */ proto.pactus.SignMessageWithPrivateKeyResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignMessageWithPrivateKeyResponse; return proto.pactus.SignMessageWithPrivateKeyResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignMessageWithPrivateKeyResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignMessageWithPrivateKeyResponse} */ proto.pactus.SignMessageWithPrivateKeyResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignMessageWithPrivateKeyResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignMessageWithPrivateKeyResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignMessageWithPrivateKeyResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageWithPrivateKeyResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSignature(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string signature = 1; * @return {string} */ proto.pactus.SignMessageWithPrivateKeyResponse.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageWithPrivateKeyResponse} returns this */ proto.pactus.SignMessageWithPrivateKeyResponse.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.VerifyMessageRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.VerifyMessageRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.VerifyMessageRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.VerifyMessageRequest.toObject = function(includeInstance, msg) { var f, obj = { message: jspb.Message.getFieldWithDefault(msg, 1, ""), signature: jspb.Message.getFieldWithDefault(msg, 2, ""), publicKey: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.VerifyMessageRequest} */ proto.pactus.VerifyMessageRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.VerifyMessageRequest; return proto.pactus.VerifyMessageRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.VerifyMessageRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.VerifyMessageRequest} */ proto.pactus.VerifyMessageRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMessage(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.VerifyMessageRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.VerifyMessageRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.VerifyMessageRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.VerifyMessageRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getMessage(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getSignature(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string message = 1; * @return {string} */ proto.pactus.VerifyMessageRequest.prototype.getMessage = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.VerifyMessageRequest} returns this */ proto.pactus.VerifyMessageRequest.prototype.setMessage = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string signature = 2; * @return {string} */ proto.pactus.VerifyMessageRequest.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.VerifyMessageRequest} returns this */ proto.pactus.VerifyMessageRequest.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string public_key = 3; * @return {string} */ proto.pactus.VerifyMessageRequest.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.VerifyMessageRequest} returns this */ proto.pactus.VerifyMessageRequest.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.VerifyMessageResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.VerifyMessageResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.VerifyMessageResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.VerifyMessageResponse.toObject = function(includeInstance, msg) { var f, obj = { isValid: jspb.Message.getBooleanFieldWithDefault(msg, 1, false) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.VerifyMessageResponse} */ proto.pactus.VerifyMessageResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.VerifyMessageResponse; return proto.pactus.VerifyMessageResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.VerifyMessageResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.VerifyMessageResponse} */ proto.pactus.VerifyMessageResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {boolean} */ (reader.readBool()); msg.setIsValid(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.VerifyMessageResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.VerifyMessageResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.VerifyMessageResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.VerifyMessageResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getIsValid(); if (f) { writer.writeBool( 1, f ); } }; /** * optional bool is_valid = 1; * @return {boolean} */ proto.pactus.VerifyMessageResponse.prototype.getIsValid = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false)); }; /** * @param {boolean} value * @return {!proto.pactus.VerifyMessageResponse} returns this */ proto.pactus.VerifyMessageResponse.prototype.setIsValid = function(value) { return jspb.Message.setProto3BooleanField(this, 1, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.PublicKeyAggregationRequest.repeatedFields_ = [1]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PublicKeyAggregationRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PublicKeyAggregationRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PublicKeyAggregationRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PublicKeyAggregationRequest.toObject = function(includeInstance, msg) { var f, obj = { publicKeysList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PublicKeyAggregationRequest} */ proto.pactus.PublicKeyAggregationRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PublicKeyAggregationRequest; return proto.pactus.PublicKeyAggregationRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PublicKeyAggregationRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PublicKeyAggregationRequest} */ proto.pactus.PublicKeyAggregationRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addPublicKeys(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PublicKeyAggregationRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PublicKeyAggregationRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PublicKeyAggregationRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PublicKeyAggregationRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPublicKeysList(); if (f.length > 0) { writer.writeRepeatedString( 1, f ); } }; /** * repeated string public_keys = 1; * @return {!Array} */ proto.pactus.PublicKeyAggregationRequest.prototype.getPublicKeysList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1)); }; /** * @param {!Array} value * @return {!proto.pactus.PublicKeyAggregationRequest} returns this */ proto.pactus.PublicKeyAggregationRequest.prototype.setPublicKeysList = function(value) { return jspb.Message.setField(this, 1, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.PublicKeyAggregationRequest} returns this */ proto.pactus.PublicKeyAggregationRequest.prototype.addPublicKeys = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 1, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.PublicKeyAggregationRequest} returns this */ proto.pactus.PublicKeyAggregationRequest.prototype.clearPublicKeysList = function() { return this.setPublicKeysList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.PublicKeyAggregationResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.PublicKeyAggregationResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.PublicKeyAggregationResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PublicKeyAggregationResponse.toObject = function(includeInstance, msg) { var f, obj = { publicKey: jspb.Message.getFieldWithDefault(msg, 1, ""), address: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.PublicKeyAggregationResponse} */ proto.pactus.PublicKeyAggregationResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.PublicKeyAggregationResponse; return proto.pactus.PublicKeyAggregationResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.PublicKeyAggregationResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.PublicKeyAggregationResponse} */ proto.pactus.PublicKeyAggregationResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.PublicKeyAggregationResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.PublicKeyAggregationResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.PublicKeyAggregationResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.PublicKeyAggregationResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string public_key = 1; * @return {string} */ proto.pactus.PublicKeyAggregationResponse.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.PublicKeyAggregationResponse} returns this */ proto.pactus.PublicKeyAggregationResponse.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string address = 2; * @return {string} */ proto.pactus.PublicKeyAggregationResponse.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.PublicKeyAggregationResponse} returns this */ proto.pactus.PublicKeyAggregationResponse.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.SignatureAggregationRequest.repeatedFields_ = [1]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignatureAggregationRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignatureAggregationRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignatureAggregationRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignatureAggregationRequest.toObject = function(includeInstance, msg) { var f, obj = { signaturesList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignatureAggregationRequest} */ proto.pactus.SignatureAggregationRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignatureAggregationRequest; return proto.pactus.SignatureAggregationRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignatureAggregationRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignatureAggregationRequest} */ proto.pactus.SignatureAggregationRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addSignatures(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignatureAggregationRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignatureAggregationRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignatureAggregationRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignatureAggregationRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSignaturesList(); if (f.length > 0) { writer.writeRepeatedString( 1, f ); } }; /** * repeated string signatures = 1; * @return {!Array} */ proto.pactus.SignatureAggregationRequest.prototype.getSignaturesList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1)); }; /** * @param {!Array} value * @return {!proto.pactus.SignatureAggregationRequest} returns this */ proto.pactus.SignatureAggregationRequest.prototype.setSignaturesList = function(value) { return jspb.Message.setField(this, 1, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.SignatureAggregationRequest} returns this */ proto.pactus.SignatureAggregationRequest.prototype.addSignatures = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 1, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.SignatureAggregationRequest} returns this */ proto.pactus.SignatureAggregationRequest.prototype.clearSignaturesList = function() { return this.setSignaturesList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignatureAggregationResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignatureAggregationResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignatureAggregationResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignatureAggregationResponse.toObject = function(includeInstance, msg) { var f, obj = { signature: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignatureAggregationResponse} */ proto.pactus.SignatureAggregationResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignatureAggregationResponse; return proto.pactus.SignatureAggregationResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignatureAggregationResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignatureAggregationResponse} */ proto.pactus.SignatureAggregationResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignatureAggregationResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignatureAggregationResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignatureAggregationResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignatureAggregationResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSignature(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string signature = 1; * @return {string} */ proto.pactus.SignatureAggregationResponse.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignatureAggregationResponse} returns this */ proto.pactus.SignatureAggregationResponse.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; goog.object.extend(exports, proto.pactus); ================================================ FILE: www/grpc/gen/js/wallet_grpc_pb.js ================================================ // GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('@grpc/grpc-js'); var wallet_pb = require('./wallet_pb.js'); var transaction_pb = require('./transaction_pb.js'); function serialize_pactus_CreateWalletRequest(arg) { if (!(arg instanceof wallet_pb.CreateWalletRequest)) { throw new Error('Expected argument of type pactus.CreateWalletRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_CreateWalletRequest(buffer_arg) { return wallet_pb.CreateWalletRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_CreateWalletResponse(arg) { if (!(arg instanceof wallet_pb.CreateWalletResponse)) { throw new Error('Expected argument of type pactus.CreateWalletResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_CreateWalletResponse(buffer_arg) { return wallet_pb.CreateWalletResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetAddressInfoRequest(arg) { if (!(arg instanceof wallet_pb.GetAddressInfoRequest)) { throw new Error('Expected argument of type pactus.GetAddressInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetAddressInfoRequest(buffer_arg) { return wallet_pb.GetAddressInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetAddressInfoResponse(arg) { if (!(arg instanceof wallet_pb.GetAddressInfoResponse)) { throw new Error('Expected argument of type pactus.GetAddressInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetAddressInfoResponse(buffer_arg) { return wallet_pb.GetAddressInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetMnemonicRequest(arg) { if (!(arg instanceof wallet_pb.GetMnemonicRequest)) { throw new Error('Expected argument of type pactus.GetMnemonicRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetMnemonicRequest(buffer_arg) { return wallet_pb.GetMnemonicRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetMnemonicResponse(arg) { if (!(arg instanceof wallet_pb.GetMnemonicResponse)) { throw new Error('Expected argument of type pactus.GetMnemonicResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetMnemonicResponse(buffer_arg) { return wallet_pb.GetMnemonicResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetNewAddressRequest(arg) { if (!(arg instanceof wallet_pb.GetNewAddressRequest)) { throw new Error('Expected argument of type pactus.GetNewAddressRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetNewAddressRequest(buffer_arg) { return wallet_pb.GetNewAddressRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetNewAddressResponse(arg) { if (!(arg instanceof wallet_pb.GetNewAddressResponse)) { throw new Error('Expected argument of type pactus.GetNewAddressResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetNewAddressResponse(buffer_arg) { return wallet_pb.GetNewAddressResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetPrivateKeyRequest(arg) { if (!(arg instanceof wallet_pb.GetPrivateKeyRequest)) { throw new Error('Expected argument of type pactus.GetPrivateKeyRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetPrivateKeyRequest(buffer_arg) { return wallet_pb.GetPrivateKeyRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetPrivateKeyResponse(arg) { if (!(arg instanceof wallet_pb.GetPrivateKeyResponse)) { throw new Error('Expected argument of type pactus.GetPrivateKeyResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetPrivateKeyResponse(buffer_arg) { return wallet_pb.GetPrivateKeyResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTotalBalanceRequest(arg) { if (!(arg instanceof wallet_pb.GetTotalBalanceRequest)) { throw new Error('Expected argument of type pactus.GetTotalBalanceRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTotalBalanceRequest(buffer_arg) { return wallet_pb.GetTotalBalanceRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTotalBalanceResponse(arg) { if (!(arg instanceof wallet_pb.GetTotalBalanceResponse)) { throw new Error('Expected argument of type pactus.GetTotalBalanceResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTotalBalanceResponse(buffer_arg) { return wallet_pb.GetTotalBalanceResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTotalStakeRequest(arg) { if (!(arg instanceof wallet_pb.GetTotalStakeRequest)) { throw new Error('Expected argument of type pactus.GetTotalStakeRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTotalStakeRequest(buffer_arg) { return wallet_pb.GetTotalStakeRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetTotalStakeResponse(arg) { if (!(arg instanceof wallet_pb.GetTotalStakeResponse)) { throw new Error('Expected argument of type pactus.GetTotalStakeResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetTotalStakeResponse(buffer_arg) { return wallet_pb.GetTotalStakeResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorAddressRequest(arg) { if (!(arg instanceof wallet_pb.GetValidatorAddressRequest)) { throw new Error('Expected argument of type pactus.GetValidatorAddressRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorAddressRequest(buffer_arg) { return wallet_pb.GetValidatorAddressRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetValidatorAddressResponse(arg) { if (!(arg instanceof wallet_pb.GetValidatorAddressResponse)) { throw new Error('Expected argument of type pactus.GetValidatorAddressResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetValidatorAddressResponse(buffer_arg) { return wallet_pb.GetValidatorAddressResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetWalletInfoRequest(arg) { if (!(arg instanceof wallet_pb.GetWalletInfoRequest)) { throw new Error('Expected argument of type pactus.GetWalletInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetWalletInfoRequest(buffer_arg) { return wallet_pb.GetWalletInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_GetWalletInfoResponse(arg) { if (!(arg instanceof wallet_pb.GetWalletInfoResponse)) { throw new Error('Expected argument of type pactus.GetWalletInfoResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_GetWalletInfoResponse(buffer_arg) { return wallet_pb.GetWalletInfoResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListAddressesRequest(arg) { if (!(arg instanceof wallet_pb.ListAddressesRequest)) { throw new Error('Expected argument of type pactus.ListAddressesRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListAddressesRequest(buffer_arg) { return wallet_pb.ListAddressesRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListAddressesResponse(arg) { if (!(arg instanceof wallet_pb.ListAddressesResponse)) { throw new Error('Expected argument of type pactus.ListAddressesResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListAddressesResponse(buffer_arg) { return wallet_pb.ListAddressesResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListTransactionsRequest(arg) { if (!(arg instanceof wallet_pb.ListTransactionsRequest)) { throw new Error('Expected argument of type pactus.ListTransactionsRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListTransactionsRequest(buffer_arg) { return wallet_pb.ListTransactionsRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListTransactionsResponse(arg) { if (!(arg instanceof wallet_pb.ListTransactionsResponse)) { throw new Error('Expected argument of type pactus.ListTransactionsResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListTransactionsResponse(buffer_arg) { return wallet_pb.ListTransactionsResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListWalletsRequest(arg) { if (!(arg instanceof wallet_pb.ListWalletsRequest)) { throw new Error('Expected argument of type pactus.ListWalletsRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListWalletsRequest(buffer_arg) { return wallet_pb.ListWalletsRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_ListWalletsResponse(arg) { if (!(arg instanceof wallet_pb.ListWalletsResponse)) { throw new Error('Expected argument of type pactus.ListWalletsResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_ListWalletsResponse(buffer_arg) { return wallet_pb.ListWalletsResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_LoadWalletRequest(arg) { if (!(arg instanceof wallet_pb.LoadWalletRequest)) { throw new Error('Expected argument of type pactus.LoadWalletRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_LoadWalletRequest(buffer_arg) { return wallet_pb.LoadWalletRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_LoadWalletResponse(arg) { if (!(arg instanceof wallet_pb.LoadWalletResponse)) { throw new Error('Expected argument of type pactus.LoadWalletResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_LoadWalletResponse(buffer_arg) { return wallet_pb.LoadWalletResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_RestoreWalletRequest(arg) { if (!(arg instanceof wallet_pb.RestoreWalletRequest)) { throw new Error('Expected argument of type pactus.RestoreWalletRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_RestoreWalletRequest(buffer_arg) { return wallet_pb.RestoreWalletRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_RestoreWalletResponse(arg) { if (!(arg instanceof wallet_pb.RestoreWalletResponse)) { throw new Error('Expected argument of type pactus.RestoreWalletResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_RestoreWalletResponse(buffer_arg) { return wallet_pb.RestoreWalletResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SetAddressLabelRequest(arg) { if (!(arg instanceof wallet_pb.SetAddressLabelRequest)) { throw new Error('Expected argument of type pactus.SetAddressLabelRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SetAddressLabelRequest(buffer_arg) { return wallet_pb.SetAddressLabelRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SetAddressLabelResponse(arg) { if (!(arg instanceof wallet_pb.SetAddressLabelResponse)) { throw new Error('Expected argument of type pactus.SetAddressLabelResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SetAddressLabelResponse(buffer_arg) { return wallet_pb.SetAddressLabelResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SetDefaultFeeRequest(arg) { if (!(arg instanceof wallet_pb.SetDefaultFeeRequest)) { throw new Error('Expected argument of type pactus.SetDefaultFeeRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SetDefaultFeeRequest(buffer_arg) { return wallet_pb.SetDefaultFeeRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SetDefaultFeeResponse(arg) { if (!(arg instanceof wallet_pb.SetDefaultFeeResponse)) { throw new Error('Expected argument of type pactus.SetDefaultFeeResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SetDefaultFeeResponse(buffer_arg) { return wallet_pb.SetDefaultFeeResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignMessageRequest(arg) { if (!(arg instanceof wallet_pb.SignMessageRequest)) { throw new Error('Expected argument of type pactus.SignMessageRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignMessageRequest(buffer_arg) { return wallet_pb.SignMessageRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignMessageResponse(arg) { if (!(arg instanceof wallet_pb.SignMessageResponse)) { throw new Error('Expected argument of type pactus.SignMessageResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignMessageResponse(buffer_arg) { return wallet_pb.SignMessageResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignRawTransactionRequest(arg) { if (!(arg instanceof wallet_pb.SignRawTransactionRequest)) { throw new Error('Expected argument of type pactus.SignRawTransactionRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignRawTransactionRequest(buffer_arg) { return wallet_pb.SignRawTransactionRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_SignRawTransactionResponse(arg) { if (!(arg instanceof wallet_pb.SignRawTransactionResponse)) { throw new Error('Expected argument of type pactus.SignRawTransactionResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_SignRawTransactionResponse(buffer_arg) { return wallet_pb.SignRawTransactionResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_UnloadWalletRequest(arg) { if (!(arg instanceof wallet_pb.UnloadWalletRequest)) { throw new Error('Expected argument of type pactus.UnloadWalletRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_UnloadWalletRequest(buffer_arg) { return wallet_pb.UnloadWalletRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_UnloadWalletResponse(arg) { if (!(arg instanceof wallet_pb.UnloadWalletResponse)) { throw new Error('Expected argument of type pactus.UnloadWalletResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_UnloadWalletResponse(buffer_arg) { return wallet_pb.UnloadWalletResponse.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_UpdatePasswordRequest(arg) { if (!(arg instanceof wallet_pb.UpdatePasswordRequest)) { throw new Error('Expected argument of type pactus.UpdatePasswordRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_UpdatePasswordRequest(buffer_arg) { return wallet_pb.UpdatePasswordRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_pactus_UpdatePasswordResponse(arg) { if (!(arg instanceof wallet_pb.UpdatePasswordResponse)) { throw new Error('Expected argument of type pactus.UpdatePasswordResponse'); } return Buffer.from(arg.serializeBinary()); } function deserialize_pactus_UpdatePasswordResponse(buffer_arg) { return wallet_pb.UpdatePasswordResponse.deserializeBinary(new Uint8Array(buffer_arg)); } // Wallet service provides RPC methods for wallet management operations. var WalletService = exports.WalletService = { // CreateWallet creates a new wallet with the specified parameters. createWallet: { path: '/pactus.Wallet/CreateWallet', requestStream: false, responseStream: false, requestType: wallet_pb.CreateWalletRequest, responseType: wallet_pb.CreateWalletResponse, requestSerialize: serialize_pactus_CreateWalletRequest, requestDeserialize: deserialize_pactus_CreateWalletRequest, responseSerialize: serialize_pactus_CreateWalletResponse, responseDeserialize: deserialize_pactus_CreateWalletResponse, }, // RestoreWallet restores an existing wallet with the given mnemonic. restoreWallet: { path: '/pactus.Wallet/RestoreWallet', requestStream: false, responseStream: false, requestType: wallet_pb.RestoreWalletRequest, responseType: wallet_pb.RestoreWalletResponse, requestSerialize: serialize_pactus_RestoreWalletRequest, requestDeserialize: deserialize_pactus_RestoreWalletRequest, responseSerialize: serialize_pactus_RestoreWalletResponse, responseDeserialize: deserialize_pactus_RestoreWalletResponse, }, // LoadWallet loads an existing wallet with the given name. // deprecated: It will be removed in a future version. loadWallet: { path: '/pactus.Wallet/LoadWallet', requestStream: false, responseStream: false, requestType: wallet_pb.LoadWalletRequest, responseType: wallet_pb.LoadWalletResponse, requestSerialize: serialize_pactus_LoadWalletRequest, requestDeserialize: deserialize_pactus_LoadWalletRequest, responseSerialize: serialize_pactus_LoadWalletResponse, responseDeserialize: deserialize_pactus_LoadWalletResponse, }, // UnloadWallet unloads a currently loaded wallet with the specified name. // deprecated: It will be removed in a future version. unloadWallet: { path: '/pactus.Wallet/UnloadWallet', requestStream: false, responseStream: false, requestType: wallet_pb.UnloadWalletRequest, responseType: wallet_pb.UnloadWalletResponse, requestSerialize: serialize_pactus_UnloadWalletRequest, requestDeserialize: deserialize_pactus_UnloadWalletRequest, responseSerialize: serialize_pactus_UnloadWalletResponse, responseDeserialize: deserialize_pactus_UnloadWalletResponse, }, // ListWallets returns a list of all available wallets. listWallets: { path: '/pactus.Wallet/ListWallets', requestStream: false, responseStream: false, requestType: wallet_pb.ListWalletsRequest, responseType: wallet_pb.ListWalletsResponse, requestSerialize: serialize_pactus_ListWalletsRequest, requestDeserialize: deserialize_pactus_ListWalletsRequest, responseSerialize: serialize_pactus_ListWalletsResponse, responseDeserialize: deserialize_pactus_ListWalletsResponse, }, // GetWalletInfo returns detailed information about a specific wallet. getWalletInfo: { path: '/pactus.Wallet/GetWalletInfo', requestStream: false, responseStream: false, requestType: wallet_pb.GetWalletInfoRequest, responseType: wallet_pb.GetWalletInfoResponse, requestSerialize: serialize_pactus_GetWalletInfoRequest, requestDeserialize: deserialize_pactus_GetWalletInfoRequest, responseSerialize: serialize_pactus_GetWalletInfoResponse, responseDeserialize: deserialize_pactus_GetWalletInfoResponse, }, // UpdatePassword updates the password of an existing wallet. updatePassword: { path: '/pactus.Wallet/UpdatePassword', requestStream: false, responseStream: false, requestType: wallet_pb.UpdatePasswordRequest, responseType: wallet_pb.UpdatePasswordResponse, requestSerialize: serialize_pactus_UpdatePasswordRequest, requestDeserialize: deserialize_pactus_UpdatePasswordRequest, responseSerialize: serialize_pactus_UpdatePasswordResponse, responseDeserialize: deserialize_pactus_UpdatePasswordResponse, }, // GetTotalBalance returns the total available balance of the wallet. getTotalBalance: { path: '/pactus.Wallet/GetTotalBalance', requestStream: false, responseStream: false, requestType: wallet_pb.GetTotalBalanceRequest, responseType: wallet_pb.GetTotalBalanceResponse, requestSerialize: serialize_pactus_GetTotalBalanceRequest, requestDeserialize: deserialize_pactus_GetTotalBalanceRequest, responseSerialize: serialize_pactus_GetTotalBalanceResponse, responseDeserialize: deserialize_pactus_GetTotalBalanceResponse, }, // GetTotalStake returns the total stake amount in the wallet. getTotalStake: { path: '/pactus.Wallet/GetTotalStake', requestStream: false, responseStream: false, requestType: wallet_pb.GetTotalStakeRequest, responseType: wallet_pb.GetTotalStakeResponse, requestSerialize: serialize_pactus_GetTotalStakeRequest, requestDeserialize: deserialize_pactus_GetTotalStakeRequest, responseSerialize: serialize_pactus_GetTotalStakeResponse, responseDeserialize: deserialize_pactus_GetTotalStakeResponse, }, // GetValidatorAddress retrieves the validator address associated with a public key. // Deprecated: Will move into utils. getValidatorAddress: { path: '/pactus.Wallet/GetValidatorAddress', requestStream: false, responseStream: false, requestType: wallet_pb.GetValidatorAddressRequest, responseType: wallet_pb.GetValidatorAddressResponse, requestSerialize: serialize_pactus_GetValidatorAddressRequest, requestDeserialize: deserialize_pactus_GetValidatorAddressRequest, responseSerialize: serialize_pactus_GetValidatorAddressResponse, responseDeserialize: deserialize_pactus_GetValidatorAddressResponse, }, // GetAddressInfo returns detailed information about a specific address. getAddressInfo: { path: '/pactus.Wallet/GetAddressInfo', requestStream: false, responseStream: false, requestType: wallet_pb.GetAddressInfoRequest, responseType: wallet_pb.GetAddressInfoResponse, requestSerialize: serialize_pactus_GetAddressInfoRequest, requestDeserialize: deserialize_pactus_GetAddressInfoRequest, responseSerialize: serialize_pactus_GetAddressInfoResponse, responseDeserialize: deserialize_pactus_GetAddressInfoResponse, }, // SetAddressLabel sets or updates the label for a given address. setAddressLabel: { path: '/pactus.Wallet/SetAddressLabel', requestStream: false, responseStream: false, requestType: wallet_pb.SetAddressLabelRequest, responseType: wallet_pb.SetAddressLabelResponse, requestSerialize: serialize_pactus_SetAddressLabelRequest, requestDeserialize: deserialize_pactus_SetAddressLabelRequest, responseSerialize: serialize_pactus_SetAddressLabelResponse, responseDeserialize: deserialize_pactus_SetAddressLabelResponse, }, // GetNewAddress generates a new address for the specified wallet. getNewAddress: { path: '/pactus.Wallet/GetNewAddress', requestStream: false, responseStream: false, requestType: wallet_pb.GetNewAddressRequest, responseType: wallet_pb.GetNewAddressResponse, requestSerialize: serialize_pactus_GetNewAddressRequest, requestDeserialize: deserialize_pactus_GetNewAddressRequest, responseSerialize: serialize_pactus_GetNewAddressResponse, responseDeserialize: deserialize_pactus_GetNewAddressResponse, }, // ListAddresses returns all addresses in the specified wallet. listAddresses: { path: '/pactus.Wallet/ListAddresses', requestStream: false, responseStream: false, requestType: wallet_pb.ListAddressesRequest, responseType: wallet_pb.ListAddressesResponse, requestSerialize: serialize_pactus_ListAddressesRequest, requestDeserialize: deserialize_pactus_ListAddressesRequest, responseSerialize: serialize_pactus_ListAddressesResponse, responseDeserialize: deserialize_pactus_ListAddressesResponse, }, // SignMessage signs an arbitrary message using a wallet's private key. signMessage: { path: '/pactus.Wallet/SignMessage', requestStream: false, responseStream: false, requestType: wallet_pb.SignMessageRequest, responseType: wallet_pb.SignMessageResponse, requestSerialize: serialize_pactus_SignMessageRequest, requestDeserialize: deserialize_pactus_SignMessageRequest, responseSerialize: serialize_pactus_SignMessageResponse, responseDeserialize: deserialize_pactus_SignMessageResponse, }, // SignRawTransaction signs a raw transaction for a specified wallet. signRawTransaction: { path: '/pactus.Wallet/SignRawTransaction', requestStream: false, responseStream: false, requestType: wallet_pb.SignRawTransactionRequest, responseType: wallet_pb.SignRawTransactionResponse, requestSerialize: serialize_pactus_SignRawTransactionRequest, requestDeserialize: deserialize_pactus_SignRawTransactionRequest, responseSerialize: serialize_pactus_SignRawTransactionResponse, responseDeserialize: deserialize_pactus_SignRawTransactionResponse, }, // ListTransactions returns a list of transactions for a wallet, // optionally filtered by a specific address, with pagination support. listTransactions: { path: '/pactus.Wallet/ListTransactions', requestStream: false, responseStream: false, requestType: wallet_pb.ListTransactionsRequest, responseType: wallet_pb.ListTransactionsResponse, requestSerialize: serialize_pactus_ListTransactionsRequest, requestDeserialize: deserialize_pactus_ListTransactionsRequest, responseSerialize: serialize_pactus_ListTransactionsResponse, responseDeserialize: deserialize_pactus_ListTransactionsResponse, }, // SetDefaultFee sets the default fee for the wallet. setDefaultFee: { path: '/pactus.Wallet/SetDefaultFee', requestStream: false, responseStream: false, requestType: wallet_pb.SetDefaultFeeRequest, responseType: wallet_pb.SetDefaultFeeResponse, requestSerialize: serialize_pactus_SetDefaultFeeRequest, requestDeserialize: deserialize_pactus_SetDefaultFeeRequest, responseSerialize: serialize_pactus_SetDefaultFeeResponse, responseDeserialize: deserialize_pactus_SetDefaultFeeResponse, }, // GetMnemonic returns the mnemonic (seed phrase) for the wallet. getMnemonic: { path: '/pactus.Wallet/GetMnemonic', requestStream: false, responseStream: false, requestType: wallet_pb.GetMnemonicRequest, responseType: wallet_pb.GetMnemonicResponse, requestSerialize: serialize_pactus_GetMnemonicRequest, requestDeserialize: deserialize_pactus_GetMnemonicRequest, responseSerialize: serialize_pactus_GetMnemonicResponse, responseDeserialize: deserialize_pactus_GetMnemonicResponse, }, // GetPrivateKey returns the private key for a given address. getPrivateKey: { path: '/pactus.Wallet/GetPrivateKey', requestStream: false, responseStream: false, requestType: wallet_pb.GetPrivateKeyRequest, responseType: wallet_pb.GetPrivateKeyResponse, requestSerialize: serialize_pactus_GetPrivateKeyRequest, requestDeserialize: deserialize_pactus_GetPrivateKeyRequest, responseSerialize: serialize_pactus_GetPrivateKeyResponse, responseDeserialize: deserialize_pactus_GetPrivateKeyResponse, }, }; exports.WalletClient = grpc.makeGenericClientConstructor(WalletService, 'Wallet'); ================================================ FILE: www/grpc/gen/js/wallet_grpc_web_pb.js ================================================ /** * @fileoverview gRPC-Web generated client stub for pactus * @enhanceable * @public */ // Code generated by protoc-gen-grpc-web. DO NOT EDIT. // versions: // protoc-gen-grpc-web v2.0.2 // protoc v0.0.0 // source: wallet.proto /* eslint-disable */ // @ts-nocheck const grpc = {}; grpc.web = require('grpc-web'); var transaction_pb = require('./transaction_pb.js') const proto = {}; proto.pactus = require('./wallet_pb.js'); /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.WalletClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @param {string} hostname * @param {?Object} credentials * @param {?grpc.web.ClientOptions} options * @constructor * @struct * @final */ proto.pactus.WalletPromiseClient = function(hostname, credentials, options) { if (!options) options = {}; options.format = 'binary'; /** * @private @const {!grpc.web.GrpcWebClientBase} The client */ this.client_ = new grpc.web.GrpcWebClientBase(options); /** * @private @const {string} The hostname */ this.hostname_ = hostname.replace(/\/+$/, ''); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.CreateWalletRequest, * !proto.pactus.CreateWalletResponse>} */ const methodDescriptor_Wallet_CreateWallet = new grpc.web.MethodDescriptor( '/pactus.Wallet/CreateWallet', grpc.web.MethodType.UNARY, proto.pactus.CreateWalletRequest, proto.pactus.CreateWalletResponse, /** * @param {!proto.pactus.CreateWalletRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.CreateWalletResponse.deserializeBinary ); /** * @param {!proto.pactus.CreateWalletRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.CreateWalletResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.createWallet = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/CreateWallet', request, metadata || {}, methodDescriptor_Wallet_CreateWallet, callback); }; /** * @param {!proto.pactus.CreateWalletRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.createWallet = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/CreateWallet', request, metadata || {}, methodDescriptor_Wallet_CreateWallet); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.RestoreWalletRequest, * !proto.pactus.RestoreWalletResponse>} */ const methodDescriptor_Wallet_RestoreWallet = new grpc.web.MethodDescriptor( '/pactus.Wallet/RestoreWallet', grpc.web.MethodType.UNARY, proto.pactus.RestoreWalletRequest, proto.pactus.RestoreWalletResponse, /** * @param {!proto.pactus.RestoreWalletRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.RestoreWalletResponse.deserializeBinary ); /** * @param {!proto.pactus.RestoreWalletRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.RestoreWalletResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.restoreWallet = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/RestoreWallet', request, metadata || {}, methodDescriptor_Wallet_RestoreWallet, callback); }; /** * @param {!proto.pactus.RestoreWalletRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.restoreWallet = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/RestoreWallet', request, metadata || {}, methodDescriptor_Wallet_RestoreWallet); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.LoadWalletRequest, * !proto.pactus.LoadWalletResponse>} */ const methodDescriptor_Wallet_LoadWallet = new grpc.web.MethodDescriptor( '/pactus.Wallet/LoadWallet', grpc.web.MethodType.UNARY, proto.pactus.LoadWalletRequest, proto.pactus.LoadWalletResponse, /** * @param {!proto.pactus.LoadWalletRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.LoadWalletResponse.deserializeBinary ); /** * @param {!proto.pactus.LoadWalletRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.LoadWalletResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.loadWallet = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/LoadWallet', request, metadata || {}, methodDescriptor_Wallet_LoadWallet, callback); }; /** * @param {!proto.pactus.LoadWalletRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.loadWallet = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/LoadWallet', request, metadata || {}, methodDescriptor_Wallet_LoadWallet); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.UnloadWalletRequest, * !proto.pactus.UnloadWalletResponse>} */ const methodDescriptor_Wallet_UnloadWallet = new grpc.web.MethodDescriptor( '/pactus.Wallet/UnloadWallet', grpc.web.MethodType.UNARY, proto.pactus.UnloadWalletRequest, proto.pactus.UnloadWalletResponse, /** * @param {!proto.pactus.UnloadWalletRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.UnloadWalletResponse.deserializeBinary ); /** * @param {!proto.pactus.UnloadWalletRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.UnloadWalletResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.unloadWallet = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/UnloadWallet', request, metadata || {}, methodDescriptor_Wallet_UnloadWallet, callback); }; /** * @param {!proto.pactus.UnloadWalletRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.unloadWallet = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/UnloadWallet', request, metadata || {}, methodDescriptor_Wallet_UnloadWallet); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.ListWalletsRequest, * !proto.pactus.ListWalletsResponse>} */ const methodDescriptor_Wallet_ListWallets = new grpc.web.MethodDescriptor( '/pactus.Wallet/ListWallets', grpc.web.MethodType.UNARY, proto.pactus.ListWalletsRequest, proto.pactus.ListWalletsResponse, /** * @param {!proto.pactus.ListWalletsRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.ListWalletsResponse.deserializeBinary ); /** * @param {!proto.pactus.ListWalletsRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.ListWalletsResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.listWallets = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/ListWallets', request, metadata || {}, methodDescriptor_Wallet_ListWallets, callback); }; /** * @param {!proto.pactus.ListWalletsRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.listWallets = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/ListWallets', request, metadata || {}, methodDescriptor_Wallet_ListWallets); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetWalletInfoRequest, * !proto.pactus.GetWalletInfoResponse>} */ const methodDescriptor_Wallet_GetWalletInfo = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetWalletInfo', grpc.web.MethodType.UNARY, proto.pactus.GetWalletInfoRequest, proto.pactus.GetWalletInfoResponse, /** * @param {!proto.pactus.GetWalletInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetWalletInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetWalletInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetWalletInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getWalletInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetWalletInfo', request, metadata || {}, methodDescriptor_Wallet_GetWalletInfo, callback); }; /** * @param {!proto.pactus.GetWalletInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getWalletInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetWalletInfo', request, metadata || {}, methodDescriptor_Wallet_GetWalletInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.UpdatePasswordRequest, * !proto.pactus.UpdatePasswordResponse>} */ const methodDescriptor_Wallet_UpdatePassword = new grpc.web.MethodDescriptor( '/pactus.Wallet/UpdatePassword', grpc.web.MethodType.UNARY, proto.pactus.UpdatePasswordRequest, proto.pactus.UpdatePasswordResponse, /** * @param {!proto.pactus.UpdatePasswordRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.UpdatePasswordResponse.deserializeBinary ); /** * @param {!proto.pactus.UpdatePasswordRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.UpdatePasswordResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.updatePassword = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/UpdatePassword', request, metadata || {}, methodDescriptor_Wallet_UpdatePassword, callback); }; /** * @param {!proto.pactus.UpdatePasswordRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.updatePassword = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/UpdatePassword', request, metadata || {}, methodDescriptor_Wallet_UpdatePassword); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetTotalBalanceRequest, * !proto.pactus.GetTotalBalanceResponse>} */ const methodDescriptor_Wallet_GetTotalBalance = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetTotalBalance', grpc.web.MethodType.UNARY, proto.pactus.GetTotalBalanceRequest, proto.pactus.GetTotalBalanceResponse, /** * @param {!proto.pactus.GetTotalBalanceRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetTotalBalanceResponse.deserializeBinary ); /** * @param {!proto.pactus.GetTotalBalanceRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetTotalBalanceResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getTotalBalance = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetTotalBalance', request, metadata || {}, methodDescriptor_Wallet_GetTotalBalance, callback); }; /** * @param {!proto.pactus.GetTotalBalanceRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getTotalBalance = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetTotalBalance', request, metadata || {}, methodDescriptor_Wallet_GetTotalBalance); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetTotalStakeRequest, * !proto.pactus.GetTotalStakeResponse>} */ const methodDescriptor_Wallet_GetTotalStake = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetTotalStake', grpc.web.MethodType.UNARY, proto.pactus.GetTotalStakeRequest, proto.pactus.GetTotalStakeResponse, /** * @param {!proto.pactus.GetTotalStakeRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetTotalStakeResponse.deserializeBinary ); /** * @param {!proto.pactus.GetTotalStakeRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetTotalStakeResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getTotalStake = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetTotalStake', request, metadata || {}, methodDescriptor_Wallet_GetTotalStake, callback); }; /** * @param {!proto.pactus.GetTotalStakeRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getTotalStake = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetTotalStake', request, metadata || {}, methodDescriptor_Wallet_GetTotalStake); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetValidatorAddressRequest, * !proto.pactus.GetValidatorAddressResponse>} */ const methodDescriptor_Wallet_GetValidatorAddress = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetValidatorAddress', grpc.web.MethodType.UNARY, proto.pactus.GetValidatorAddressRequest, proto.pactus.GetValidatorAddressResponse, /** * @param {!proto.pactus.GetValidatorAddressRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetValidatorAddressResponse.deserializeBinary ); /** * @param {!proto.pactus.GetValidatorAddressRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetValidatorAddressResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getValidatorAddress = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetValidatorAddress', request, metadata || {}, methodDescriptor_Wallet_GetValidatorAddress, callback); }; /** * @param {!proto.pactus.GetValidatorAddressRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getValidatorAddress = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetValidatorAddress', request, metadata || {}, methodDescriptor_Wallet_GetValidatorAddress); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetAddressInfoRequest, * !proto.pactus.GetAddressInfoResponse>} */ const methodDescriptor_Wallet_GetAddressInfo = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetAddressInfo', grpc.web.MethodType.UNARY, proto.pactus.GetAddressInfoRequest, proto.pactus.GetAddressInfoResponse, /** * @param {!proto.pactus.GetAddressInfoRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetAddressInfoResponse.deserializeBinary ); /** * @param {!proto.pactus.GetAddressInfoRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetAddressInfoResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getAddressInfo = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetAddressInfo', request, metadata || {}, methodDescriptor_Wallet_GetAddressInfo, callback); }; /** * @param {!proto.pactus.GetAddressInfoRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getAddressInfo = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetAddressInfo', request, metadata || {}, methodDescriptor_Wallet_GetAddressInfo); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.SetAddressLabelRequest, * !proto.pactus.SetAddressLabelResponse>} */ const methodDescriptor_Wallet_SetAddressLabel = new grpc.web.MethodDescriptor( '/pactus.Wallet/SetAddressLabel', grpc.web.MethodType.UNARY, proto.pactus.SetAddressLabelRequest, proto.pactus.SetAddressLabelResponse, /** * @param {!proto.pactus.SetAddressLabelRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.SetAddressLabelResponse.deserializeBinary ); /** * @param {!proto.pactus.SetAddressLabelRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.SetAddressLabelResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.setAddressLabel = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/SetAddressLabel', request, metadata || {}, methodDescriptor_Wallet_SetAddressLabel, callback); }; /** * @param {!proto.pactus.SetAddressLabelRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.setAddressLabel = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/SetAddressLabel', request, metadata || {}, methodDescriptor_Wallet_SetAddressLabel); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetNewAddressRequest, * !proto.pactus.GetNewAddressResponse>} */ const methodDescriptor_Wallet_GetNewAddress = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetNewAddress', grpc.web.MethodType.UNARY, proto.pactus.GetNewAddressRequest, proto.pactus.GetNewAddressResponse, /** * @param {!proto.pactus.GetNewAddressRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetNewAddressResponse.deserializeBinary ); /** * @param {!proto.pactus.GetNewAddressRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetNewAddressResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getNewAddress = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetNewAddress', request, metadata || {}, methodDescriptor_Wallet_GetNewAddress, callback); }; /** * @param {!proto.pactus.GetNewAddressRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getNewAddress = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetNewAddress', request, metadata || {}, methodDescriptor_Wallet_GetNewAddress); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.ListAddressesRequest, * !proto.pactus.ListAddressesResponse>} */ const methodDescriptor_Wallet_ListAddresses = new grpc.web.MethodDescriptor( '/pactus.Wallet/ListAddresses', grpc.web.MethodType.UNARY, proto.pactus.ListAddressesRequest, proto.pactus.ListAddressesResponse, /** * @param {!proto.pactus.ListAddressesRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.ListAddressesResponse.deserializeBinary ); /** * @param {!proto.pactus.ListAddressesRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.ListAddressesResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.listAddresses = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/ListAddresses', request, metadata || {}, methodDescriptor_Wallet_ListAddresses, callback); }; /** * @param {!proto.pactus.ListAddressesRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.listAddresses = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/ListAddresses', request, metadata || {}, methodDescriptor_Wallet_ListAddresses); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.SignMessageRequest, * !proto.pactus.SignMessageResponse>} */ const methodDescriptor_Wallet_SignMessage = new grpc.web.MethodDescriptor( '/pactus.Wallet/SignMessage', grpc.web.MethodType.UNARY, proto.pactus.SignMessageRequest, proto.pactus.SignMessageResponse, /** * @param {!proto.pactus.SignMessageRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.SignMessageResponse.deserializeBinary ); /** * @param {!proto.pactus.SignMessageRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.SignMessageResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.signMessage = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/SignMessage', request, metadata || {}, methodDescriptor_Wallet_SignMessage, callback); }; /** * @param {!proto.pactus.SignMessageRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.signMessage = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/SignMessage', request, metadata || {}, methodDescriptor_Wallet_SignMessage); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.SignRawTransactionRequest, * !proto.pactus.SignRawTransactionResponse>} */ const methodDescriptor_Wallet_SignRawTransaction = new grpc.web.MethodDescriptor( '/pactus.Wallet/SignRawTransaction', grpc.web.MethodType.UNARY, proto.pactus.SignRawTransactionRequest, proto.pactus.SignRawTransactionResponse, /** * @param {!proto.pactus.SignRawTransactionRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.SignRawTransactionResponse.deserializeBinary ); /** * @param {!proto.pactus.SignRawTransactionRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.SignRawTransactionResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.signRawTransaction = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/SignRawTransaction', request, metadata || {}, methodDescriptor_Wallet_SignRawTransaction, callback); }; /** * @param {!proto.pactus.SignRawTransactionRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.signRawTransaction = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/SignRawTransaction', request, metadata || {}, methodDescriptor_Wallet_SignRawTransaction); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.ListTransactionsRequest, * !proto.pactus.ListTransactionsResponse>} */ const methodDescriptor_Wallet_ListTransactions = new grpc.web.MethodDescriptor( '/pactus.Wallet/ListTransactions', grpc.web.MethodType.UNARY, proto.pactus.ListTransactionsRequest, proto.pactus.ListTransactionsResponse, /** * @param {!proto.pactus.ListTransactionsRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.ListTransactionsResponse.deserializeBinary ); /** * @param {!proto.pactus.ListTransactionsRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.ListTransactionsResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.listTransactions = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/ListTransactions', request, metadata || {}, methodDescriptor_Wallet_ListTransactions, callback); }; /** * @param {!proto.pactus.ListTransactionsRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.listTransactions = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/ListTransactions', request, metadata || {}, methodDescriptor_Wallet_ListTransactions); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.SetDefaultFeeRequest, * !proto.pactus.SetDefaultFeeResponse>} */ const methodDescriptor_Wallet_SetDefaultFee = new grpc.web.MethodDescriptor( '/pactus.Wallet/SetDefaultFee', grpc.web.MethodType.UNARY, proto.pactus.SetDefaultFeeRequest, proto.pactus.SetDefaultFeeResponse, /** * @param {!proto.pactus.SetDefaultFeeRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.SetDefaultFeeResponse.deserializeBinary ); /** * @param {!proto.pactus.SetDefaultFeeRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.SetDefaultFeeResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.setDefaultFee = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/SetDefaultFee', request, metadata || {}, methodDescriptor_Wallet_SetDefaultFee, callback); }; /** * @param {!proto.pactus.SetDefaultFeeRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.setDefaultFee = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/SetDefaultFee', request, metadata || {}, methodDescriptor_Wallet_SetDefaultFee); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetMnemonicRequest, * !proto.pactus.GetMnemonicResponse>} */ const methodDescriptor_Wallet_GetMnemonic = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetMnemonic', grpc.web.MethodType.UNARY, proto.pactus.GetMnemonicRequest, proto.pactus.GetMnemonicResponse, /** * @param {!proto.pactus.GetMnemonicRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetMnemonicResponse.deserializeBinary ); /** * @param {!proto.pactus.GetMnemonicRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetMnemonicResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getMnemonic = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetMnemonic', request, metadata || {}, methodDescriptor_Wallet_GetMnemonic, callback); }; /** * @param {!proto.pactus.GetMnemonicRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getMnemonic = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetMnemonic', request, metadata || {}, methodDescriptor_Wallet_GetMnemonic); }; /** * @const * @type {!grpc.web.MethodDescriptor< * !proto.pactus.GetPrivateKeyRequest, * !proto.pactus.GetPrivateKeyResponse>} */ const methodDescriptor_Wallet_GetPrivateKey = new grpc.web.MethodDescriptor( '/pactus.Wallet/GetPrivateKey', grpc.web.MethodType.UNARY, proto.pactus.GetPrivateKeyRequest, proto.pactus.GetPrivateKeyResponse, /** * @param {!proto.pactus.GetPrivateKeyRequest} request * @return {!Uint8Array} */ function(request) { return request.serializeBinary(); }, proto.pactus.GetPrivateKeyResponse.deserializeBinary ); /** * @param {!proto.pactus.GetPrivateKeyRequest} request The * request proto * @param {?Object} metadata User defined * call metadata * @param {function(?grpc.web.RpcError, ?proto.pactus.GetPrivateKeyResponse)} * callback The callback function(error, response) * @return {!grpc.web.ClientReadableStream|undefined} * The XHR Node Readable Stream */ proto.pactus.WalletClient.prototype.getPrivateKey = function(request, metadata, callback) { return this.client_.rpcCall(this.hostname_ + '/pactus.Wallet/GetPrivateKey', request, metadata || {}, methodDescriptor_Wallet_GetPrivateKey, callback); }; /** * @param {!proto.pactus.GetPrivateKeyRequest} request The * request proto * @param {?Object=} metadata User defined * call metadata * @return {!Promise} * Promise that resolves to the response */ proto.pactus.WalletPromiseClient.prototype.getPrivateKey = function(request, metadata) { return this.client_.unaryCall(this.hostname_ + '/pactus.Wallet/GetPrivateKey', request, metadata || {}, methodDescriptor_Wallet_GetPrivateKey); }; module.exports = proto.pactus; ================================================ FILE: www/grpc/gen/js/wallet_pb.js ================================================ // source: wallet.proto /** * @fileoverview * @enhanceable * @suppress {missingRequire} reports error on implicit type usages. * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var global = globalThis; var transaction_pb = require('./transaction_pb.js'); goog.object.extend(proto, transaction_pb); goog.exportSymbol('proto.pactus.AddressInfo', null, global); goog.exportSymbol('proto.pactus.AddressType', null, global); goog.exportSymbol('proto.pactus.CreateWalletRequest', null, global); goog.exportSymbol('proto.pactus.CreateWalletResponse', null, global); goog.exportSymbol('proto.pactus.GetAddressInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetAddressInfoResponse', null, global); goog.exportSymbol('proto.pactus.GetMnemonicRequest', null, global); goog.exportSymbol('proto.pactus.GetMnemonicResponse', null, global); goog.exportSymbol('proto.pactus.GetNewAddressRequest', null, global); goog.exportSymbol('proto.pactus.GetNewAddressResponse', null, global); goog.exportSymbol('proto.pactus.GetPrivateKeyRequest', null, global); goog.exportSymbol('proto.pactus.GetPrivateKeyResponse', null, global); goog.exportSymbol('proto.pactus.GetTotalBalanceRequest', null, global); goog.exportSymbol('proto.pactus.GetTotalBalanceResponse', null, global); goog.exportSymbol('proto.pactus.GetTotalStakeRequest', null, global); goog.exportSymbol('proto.pactus.GetTotalStakeResponse', null, global); goog.exportSymbol('proto.pactus.GetValidatorAddressRequest', null, global); goog.exportSymbol('proto.pactus.GetValidatorAddressResponse', null, global); goog.exportSymbol('proto.pactus.GetWalletInfoRequest', null, global); goog.exportSymbol('proto.pactus.GetWalletInfoResponse', null, global); goog.exportSymbol('proto.pactus.ListAddressesRequest', null, global); goog.exportSymbol('proto.pactus.ListAddressesResponse', null, global); goog.exportSymbol('proto.pactus.ListTransactionsRequest', null, global); goog.exportSymbol('proto.pactus.ListTransactionsResponse', null, global); goog.exportSymbol('proto.pactus.ListWalletsRequest', null, global); goog.exportSymbol('proto.pactus.ListWalletsResponse', null, global); goog.exportSymbol('proto.pactus.LoadWalletRequest', null, global); goog.exportSymbol('proto.pactus.LoadWalletResponse', null, global); goog.exportSymbol('proto.pactus.RestoreWalletRequest', null, global); goog.exportSymbol('proto.pactus.RestoreWalletResponse', null, global); goog.exportSymbol('proto.pactus.SetAddressLabelRequest', null, global); goog.exportSymbol('proto.pactus.SetAddressLabelResponse', null, global); goog.exportSymbol('proto.pactus.SetDefaultFeeRequest', null, global); goog.exportSymbol('proto.pactus.SetDefaultFeeResponse', null, global); goog.exportSymbol('proto.pactus.SignMessageRequest', null, global); goog.exportSymbol('proto.pactus.SignMessageResponse', null, global); goog.exportSymbol('proto.pactus.SignRawTransactionRequest', null, global); goog.exportSymbol('proto.pactus.SignRawTransactionResponse', null, global); goog.exportSymbol('proto.pactus.TransactionStatus', null, global); goog.exportSymbol('proto.pactus.TxDirection', null, global); goog.exportSymbol('proto.pactus.UnloadWalletRequest', null, global); goog.exportSymbol('proto.pactus.UnloadWalletResponse', null, global); goog.exportSymbol('proto.pactus.UpdatePasswordRequest', null, global); goog.exportSymbol('proto.pactus.UpdatePasswordResponse', null, global); goog.exportSymbol('proto.pactus.WalletTransactionInfo', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.AddressInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.AddressInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.AddressInfo.displayName = 'proto.pactus.AddressInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetNewAddressRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetNewAddressRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetNewAddressRequest.displayName = 'proto.pactus.GetNewAddressRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetNewAddressResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetNewAddressResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetNewAddressResponse.displayName = 'proto.pactus.GetNewAddressResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.RestoreWalletRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.RestoreWalletRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.RestoreWalletRequest.displayName = 'proto.pactus.RestoreWalletRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.RestoreWalletResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.RestoreWalletResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.RestoreWalletResponse.displayName = 'proto.pactus.RestoreWalletResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CreateWalletRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CreateWalletRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CreateWalletRequest.displayName = 'proto.pactus.CreateWalletRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.CreateWalletResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.CreateWalletResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.CreateWalletResponse.displayName = 'proto.pactus.CreateWalletResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.LoadWalletRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.LoadWalletRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.LoadWalletRequest.displayName = 'proto.pactus.LoadWalletRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.LoadWalletResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.LoadWalletResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.LoadWalletResponse.displayName = 'proto.pactus.LoadWalletResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.UnloadWalletRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.UnloadWalletRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.UnloadWalletRequest.displayName = 'proto.pactus.UnloadWalletRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.UnloadWalletResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.UnloadWalletResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.UnloadWalletResponse.displayName = 'proto.pactus.UnloadWalletResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorAddressRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetValidatorAddressRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorAddressRequest.displayName = 'proto.pactus.GetValidatorAddressRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetValidatorAddressResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetValidatorAddressResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetValidatorAddressResponse.displayName = 'proto.pactus.GetValidatorAddressResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignRawTransactionRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignRawTransactionRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignRawTransactionRequest.displayName = 'proto.pactus.SignRawTransactionRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignRawTransactionResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignRawTransactionResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignRawTransactionResponse.displayName = 'proto.pactus.SignRawTransactionResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTotalBalanceRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTotalBalanceRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTotalBalanceRequest.displayName = 'proto.pactus.GetTotalBalanceRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTotalBalanceResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTotalBalanceResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTotalBalanceResponse.displayName = 'proto.pactus.GetTotalBalanceResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignMessageRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignMessageRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignMessageRequest.displayName = 'proto.pactus.SignMessageRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SignMessageResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SignMessageResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SignMessageResponse.displayName = 'proto.pactus.SignMessageResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTotalStakeRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTotalStakeRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTotalStakeRequest.displayName = 'proto.pactus.GetTotalStakeRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetTotalStakeResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetTotalStakeResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetTotalStakeResponse.displayName = 'proto.pactus.GetTotalStakeResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetAddressInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetAddressInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetAddressInfoRequest.displayName = 'proto.pactus.GetAddressInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetAddressInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetAddressInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetAddressInfoResponse.displayName = 'proto.pactus.GetAddressInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SetAddressLabelRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SetAddressLabelRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SetAddressLabelRequest.displayName = 'proto.pactus.SetAddressLabelRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SetAddressLabelResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SetAddressLabelResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SetAddressLabelResponse.displayName = 'proto.pactus.SetAddressLabelResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListWalletsRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ListWalletsRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListWalletsRequest.displayName = 'proto.pactus.ListWalletsRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListWalletsResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.ListWalletsResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.ListWalletsResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListWalletsResponse.displayName = 'proto.pactus.ListWalletsResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetWalletInfoRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetWalletInfoRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetWalletInfoRequest.displayName = 'proto.pactus.GetWalletInfoRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetWalletInfoResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetWalletInfoResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetWalletInfoResponse.displayName = 'proto.pactus.GetWalletInfoResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListAddressesRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.ListAddressesRequest.repeatedFields_, null); }; goog.inherits(proto.pactus.ListAddressesRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListAddressesRequest.displayName = 'proto.pactus.ListAddressesRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListAddressesResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.ListAddressesResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.ListAddressesResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListAddressesResponse.displayName = 'proto.pactus.ListAddressesResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.UpdatePasswordRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.UpdatePasswordRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.UpdatePasswordRequest.displayName = 'proto.pactus.UpdatePasswordRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.UpdatePasswordResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.UpdatePasswordResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.UpdatePasswordResponse.displayName = 'proto.pactus.UpdatePasswordResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.WalletTransactionInfo = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.WalletTransactionInfo, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.WalletTransactionInfo.displayName = 'proto.pactus.WalletTransactionInfo'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListTransactionsRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.ListTransactionsRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListTransactionsRequest.displayName = 'proto.pactus.ListTransactionsRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.ListTransactionsResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.pactus.ListTransactionsResponse.repeatedFields_, null); }; goog.inherits(proto.pactus.ListTransactionsResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.ListTransactionsResponse.displayName = 'proto.pactus.ListTransactionsResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SetDefaultFeeRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SetDefaultFeeRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SetDefaultFeeRequest.displayName = 'proto.pactus.SetDefaultFeeRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.SetDefaultFeeResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.SetDefaultFeeResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.SetDefaultFeeResponse.displayName = 'proto.pactus.SetDefaultFeeResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetMnemonicRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetMnemonicRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetMnemonicRequest.displayName = 'proto.pactus.GetMnemonicRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetMnemonicResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetMnemonicResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetMnemonicResponse.displayName = 'proto.pactus.GetMnemonicResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetPrivateKeyRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetPrivateKeyRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetPrivateKeyRequest.displayName = 'proto.pactus.GetPrivateKeyRequest'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.pactus.GetPrivateKeyResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.pactus.GetPrivateKeyResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.pactus.GetPrivateKeyResponse.displayName = 'proto.pactus.GetPrivateKeyResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.AddressInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.AddressInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.AddressInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.AddressInfo.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, ""), publicKey: jspb.Message.getFieldWithDefault(msg, 2, ""), label: jspb.Message.getFieldWithDefault(msg, 3, ""), path: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.AddressInfo} */ proto.pactus.AddressInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.AddressInfo; return proto.pactus.AddressInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.AddressInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.AddressInfo} */ proto.pactus.AddressInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setLabel(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPath(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.AddressInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.AddressInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.AddressInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.AddressInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getLabel(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getPath(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.AddressInfo.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.AddressInfo} returns this */ proto.pactus.AddressInfo.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string public_key = 2; * @return {string} */ proto.pactus.AddressInfo.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.AddressInfo} returns this */ proto.pactus.AddressInfo.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string label = 3; * @return {string} */ proto.pactus.AddressInfo.prototype.getLabel = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.AddressInfo} returns this */ proto.pactus.AddressInfo.prototype.setLabel = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string path = 4; * @return {string} */ proto.pactus.AddressInfo.prototype.getPath = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.AddressInfo} returns this */ proto.pactus.AddressInfo.prototype.setPath = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetNewAddressRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetNewAddressRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetNewAddressRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNewAddressRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), addressType: jspb.Message.getFieldWithDefault(msg, 2, 0), label: jspb.Message.getFieldWithDefault(msg, 3, ""), password: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetNewAddressRequest} */ proto.pactus.GetNewAddressRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetNewAddressRequest; return proto.pactus.GetNewAddressRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetNewAddressRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetNewAddressRequest} */ proto.pactus.GetNewAddressRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {!proto.pactus.AddressType} */ (reader.readEnum()); msg.setAddressType(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setLabel(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetNewAddressRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetNewAddressRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetNewAddressRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNewAddressRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddressType(); if (f !== 0.0) { writer.writeEnum( 2, f ); } f = message.getLabel(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetNewAddressRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNewAddressRequest} returns this */ proto.pactus.GetNewAddressRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional AddressType address_type = 2; * @return {!proto.pactus.AddressType} */ proto.pactus.GetNewAddressRequest.prototype.getAddressType = function() { return /** @type {!proto.pactus.AddressType} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {!proto.pactus.AddressType} value * @return {!proto.pactus.GetNewAddressRequest} returns this */ proto.pactus.GetNewAddressRequest.prototype.setAddressType = function(value) { return jspb.Message.setProto3EnumField(this, 2, value); }; /** * optional string label = 3; * @return {string} */ proto.pactus.GetNewAddressRequest.prototype.getLabel = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNewAddressRequest} returns this */ proto.pactus.GetNewAddressRequest.prototype.setLabel = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string password = 4; * @return {string} */ proto.pactus.GetNewAddressRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNewAddressRequest} returns this */ proto.pactus.GetNewAddressRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetNewAddressResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetNewAddressResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetNewAddressResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNewAddressResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), addr: (f = msg.getAddr()) && proto.pactus.AddressInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetNewAddressResponse} */ proto.pactus.GetNewAddressResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetNewAddressResponse; return proto.pactus.GetNewAddressResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetNewAddressResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetNewAddressResponse} */ proto.pactus.GetNewAddressResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = new proto.pactus.AddressInfo; reader.readMessage(value,proto.pactus.AddressInfo.deserializeBinaryFromReader); msg.setAddr(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetNewAddressResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetNewAddressResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetNewAddressResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetNewAddressResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddr(); if (f != null) { writer.writeMessage( 2, f, proto.pactus.AddressInfo.serializeBinaryToWriter ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetNewAddressResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetNewAddressResponse} returns this */ proto.pactus.GetNewAddressResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional AddressInfo addr = 2; * @return {?proto.pactus.AddressInfo} */ proto.pactus.GetNewAddressResponse.prototype.getAddr = function() { return /** @type{?proto.pactus.AddressInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.AddressInfo, 2)); }; /** * @param {?proto.pactus.AddressInfo|undefined} value * @return {!proto.pactus.GetNewAddressResponse} returns this */ proto.pactus.GetNewAddressResponse.prototype.setAddr = function(value) { return jspb.Message.setWrapperField(this, 2, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetNewAddressResponse} returns this */ proto.pactus.GetNewAddressResponse.prototype.clearAddr = function() { return this.setAddr(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetNewAddressResponse.prototype.hasAddr = function() { return jspb.Message.getField(this, 2) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.RestoreWalletRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.RestoreWalletRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.RestoreWalletRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.RestoreWalletRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), mnemonic: jspb.Message.getFieldWithDefault(msg, 2, ""), password: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.RestoreWalletRequest} */ proto.pactus.RestoreWalletRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.RestoreWalletRequest; return proto.pactus.RestoreWalletRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.RestoreWalletRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.RestoreWalletRequest} */ proto.pactus.RestoreWalletRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMnemonic(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.RestoreWalletRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.RestoreWalletRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.RestoreWalletRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.RestoreWalletRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getMnemonic(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.RestoreWalletRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.RestoreWalletRequest} returns this */ proto.pactus.RestoreWalletRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string mnemonic = 2; * @return {string} */ proto.pactus.RestoreWalletRequest.prototype.getMnemonic = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.RestoreWalletRequest} returns this */ proto.pactus.RestoreWalletRequest.prototype.setMnemonic = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string password = 3; * @return {string} */ proto.pactus.RestoreWalletRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.RestoreWalletRequest} returns this */ proto.pactus.RestoreWalletRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.RestoreWalletResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.RestoreWalletResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.RestoreWalletResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.RestoreWalletResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.RestoreWalletResponse} */ proto.pactus.RestoreWalletResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.RestoreWalletResponse; return proto.pactus.RestoreWalletResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.RestoreWalletResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.RestoreWalletResponse} */ proto.pactus.RestoreWalletResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.RestoreWalletResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.RestoreWalletResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.RestoreWalletResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.RestoreWalletResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.RestoreWalletResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.RestoreWalletResponse} returns this */ proto.pactus.RestoreWalletResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CreateWalletRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CreateWalletRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CreateWalletRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CreateWalletRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), password: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CreateWalletRequest} */ proto.pactus.CreateWalletRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CreateWalletRequest; return proto.pactus.CreateWalletRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CreateWalletRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CreateWalletRequest} */ proto.pactus.CreateWalletRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CreateWalletRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CreateWalletRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CreateWalletRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CreateWalletRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.CreateWalletRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.CreateWalletRequest} returns this */ proto.pactus.CreateWalletRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string password = 2; * @return {string} */ proto.pactus.CreateWalletRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.CreateWalletRequest} returns this */ proto.pactus.CreateWalletRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.CreateWalletResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.CreateWalletResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.CreateWalletResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CreateWalletResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), mnemonic: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.CreateWalletResponse} */ proto.pactus.CreateWalletResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.CreateWalletResponse; return proto.pactus.CreateWalletResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.CreateWalletResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.CreateWalletResponse} */ proto.pactus.CreateWalletResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMnemonic(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.CreateWalletResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.CreateWalletResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.CreateWalletResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.CreateWalletResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getMnemonic(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.CreateWalletResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.CreateWalletResponse} returns this */ proto.pactus.CreateWalletResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string mnemonic = 2; * @return {string} */ proto.pactus.CreateWalletResponse.prototype.getMnemonic = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.CreateWalletResponse} returns this */ proto.pactus.CreateWalletResponse.prototype.setMnemonic = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.LoadWalletRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.LoadWalletRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.LoadWalletRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.LoadWalletRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.LoadWalletRequest} */ proto.pactus.LoadWalletRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.LoadWalletRequest; return proto.pactus.LoadWalletRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.LoadWalletRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.LoadWalletRequest} */ proto.pactus.LoadWalletRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.LoadWalletRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.LoadWalletRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.LoadWalletRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.LoadWalletRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.LoadWalletRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.LoadWalletRequest} returns this */ proto.pactus.LoadWalletRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.LoadWalletResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.LoadWalletResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.LoadWalletResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.LoadWalletResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.LoadWalletResponse} */ proto.pactus.LoadWalletResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.LoadWalletResponse; return proto.pactus.LoadWalletResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.LoadWalletResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.LoadWalletResponse} */ proto.pactus.LoadWalletResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.LoadWalletResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.LoadWalletResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.LoadWalletResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.LoadWalletResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.LoadWalletResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.LoadWalletResponse} returns this */ proto.pactus.LoadWalletResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.UnloadWalletRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.UnloadWalletRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.UnloadWalletRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UnloadWalletRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.UnloadWalletRequest} */ proto.pactus.UnloadWalletRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.UnloadWalletRequest; return proto.pactus.UnloadWalletRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.UnloadWalletRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.UnloadWalletRequest} */ proto.pactus.UnloadWalletRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.UnloadWalletRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.UnloadWalletRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.UnloadWalletRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UnloadWalletRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.UnloadWalletRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.UnloadWalletRequest} returns this */ proto.pactus.UnloadWalletRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.UnloadWalletResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.UnloadWalletResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.UnloadWalletResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UnloadWalletResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.UnloadWalletResponse} */ proto.pactus.UnloadWalletResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.UnloadWalletResponse; return proto.pactus.UnloadWalletResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.UnloadWalletResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.UnloadWalletResponse} */ proto.pactus.UnloadWalletResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.UnloadWalletResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.UnloadWalletResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.UnloadWalletResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UnloadWalletResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.UnloadWalletResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.UnloadWalletResponse} returns this */ proto.pactus.UnloadWalletResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorAddressRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorAddressRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorAddressRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressRequest.toObject = function(includeInstance, msg) { var f, obj = { publicKey: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorAddressRequest} */ proto.pactus.GetValidatorAddressRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorAddressRequest; return proto.pactus.GetValidatorAddressRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorAddressRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorAddressRequest} */ proto.pactus.GetValidatorAddressRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPublicKey(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorAddressRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorAddressRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorAddressRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPublicKey(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string public_key = 1; * @return {string} */ proto.pactus.GetValidatorAddressRequest.prototype.getPublicKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetValidatorAddressRequest} returns this */ proto.pactus.GetValidatorAddressRequest.prototype.setPublicKey = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetValidatorAddressResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetValidatorAddressResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetValidatorAddressResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressResponse.toObject = function(includeInstance, msg) { var f, obj = { address: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetValidatorAddressResponse} */ proto.pactus.GetValidatorAddressResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetValidatorAddressResponse; return proto.pactus.GetValidatorAddressResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetValidatorAddressResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetValidatorAddressResponse} */ proto.pactus.GetValidatorAddressResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetValidatorAddressResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetValidatorAddressResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetValidatorAddressResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetValidatorAddressResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getAddress(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string address = 1; * @return {string} */ proto.pactus.GetValidatorAddressResponse.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetValidatorAddressResponse} returns this */ proto.pactus.GetValidatorAddressResponse.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignRawTransactionRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignRawTransactionRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignRawTransactionRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignRawTransactionRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), rawTransaction: jspb.Message.getFieldWithDefault(msg, 2, ""), password: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignRawTransactionRequest} */ proto.pactus.SignRawTransactionRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignRawTransactionRequest; return proto.pactus.SignRawTransactionRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignRawTransactionRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignRawTransactionRequest} */ proto.pactus.SignRawTransactionRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setRawTransaction(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignRawTransactionRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignRawTransactionRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignRawTransactionRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignRawTransactionRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getRawTransaction(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.SignRawTransactionRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignRawTransactionRequest} returns this */ proto.pactus.SignRawTransactionRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string raw_transaction = 2; * @return {string} */ proto.pactus.SignRawTransactionRequest.prototype.getRawTransaction = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.SignRawTransactionRequest} returns this */ proto.pactus.SignRawTransactionRequest.prototype.setRawTransaction = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string password = 3; * @return {string} */ proto.pactus.SignRawTransactionRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.SignRawTransactionRequest} returns this */ proto.pactus.SignRawTransactionRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignRawTransactionResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignRawTransactionResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignRawTransactionResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignRawTransactionResponse.toObject = function(includeInstance, msg) { var f, obj = { transactionId: jspb.Message.getFieldWithDefault(msg, 1, ""), signedRawTransaction: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignRawTransactionResponse} */ proto.pactus.SignRawTransactionResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignRawTransactionResponse; return proto.pactus.SignRawTransactionResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignRawTransactionResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignRawTransactionResponse} */ proto.pactus.SignRawTransactionResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setTransactionId(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignedRawTransaction(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignRawTransactionResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignRawTransactionResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignRawTransactionResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignRawTransactionResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getTransactionId(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getSignedRawTransaction(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string transaction_id = 1; * @return {string} */ proto.pactus.SignRawTransactionResponse.prototype.getTransactionId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignRawTransactionResponse} returns this */ proto.pactus.SignRawTransactionResponse.prototype.setTransactionId = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string signed_raw_transaction = 2; * @return {string} */ proto.pactus.SignRawTransactionResponse.prototype.getSignedRawTransaction = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.SignRawTransactionResponse} returns this */ proto.pactus.SignRawTransactionResponse.prototype.setSignedRawTransaction = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTotalBalanceRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTotalBalanceRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTotalBalanceRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalBalanceRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTotalBalanceRequest} */ proto.pactus.GetTotalBalanceRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTotalBalanceRequest; return proto.pactus.GetTotalBalanceRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTotalBalanceRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTotalBalanceRequest} */ proto.pactus.GetTotalBalanceRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTotalBalanceRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTotalBalanceRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTotalBalanceRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalBalanceRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetTotalBalanceRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetTotalBalanceRequest} returns this */ proto.pactus.GetTotalBalanceRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTotalBalanceResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTotalBalanceResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTotalBalanceResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalBalanceResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), totalBalance: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTotalBalanceResponse} */ proto.pactus.GetTotalBalanceResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTotalBalanceResponse; return proto.pactus.GetTotalBalanceResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTotalBalanceResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTotalBalanceResponse} */ proto.pactus.GetTotalBalanceResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setTotalBalance(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTotalBalanceResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTotalBalanceResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTotalBalanceResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalBalanceResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getTotalBalance(); if (f !== 0) { writer.writeInt64( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetTotalBalanceResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetTotalBalanceResponse} returns this */ proto.pactus.GetTotalBalanceResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional int64 total_balance = 2; * @return {number} */ proto.pactus.GetTotalBalanceResponse.prototype.getTotalBalance = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetTotalBalanceResponse} returns this */ proto.pactus.GetTotalBalanceResponse.prototype.setTotalBalance = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignMessageRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignMessageRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignMessageRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), password: jspb.Message.getFieldWithDefault(msg, 2, ""), address: jspb.Message.getFieldWithDefault(msg, 3, ""), message: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignMessageRequest} */ proto.pactus.SignMessageRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignMessageRequest; return proto.pactus.SignMessageRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignMessageRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignMessageRequest} */ proto.pactus.SignMessageRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMessage(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignMessageRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignMessageRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignMessageRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getMessage(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.SignMessageRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageRequest} returns this */ proto.pactus.SignMessageRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string password = 2; * @return {string} */ proto.pactus.SignMessageRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageRequest} returns this */ proto.pactus.SignMessageRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string address = 3; * @return {string} */ proto.pactus.SignMessageRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageRequest} returns this */ proto.pactus.SignMessageRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string message = 4; * @return {string} */ proto.pactus.SignMessageRequest.prototype.getMessage = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageRequest} returns this */ proto.pactus.SignMessageRequest.prototype.setMessage = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SignMessageResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SignMessageResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SignMessageResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageResponse.toObject = function(includeInstance, msg) { var f, obj = { signature: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SignMessageResponse} */ proto.pactus.SignMessageResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SignMessageResponse; return proto.pactus.SignMessageResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SignMessageResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SignMessageResponse} */ proto.pactus.SignMessageResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSignature(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SignMessageResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SignMessageResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SignMessageResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SignMessageResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSignature(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string signature = 1; * @return {string} */ proto.pactus.SignMessageResponse.prototype.getSignature = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SignMessageResponse} returns this */ proto.pactus.SignMessageResponse.prototype.setSignature = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTotalStakeRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTotalStakeRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTotalStakeRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalStakeRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTotalStakeRequest} */ proto.pactus.GetTotalStakeRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTotalStakeRequest; return proto.pactus.GetTotalStakeRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTotalStakeRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTotalStakeRequest} */ proto.pactus.GetTotalStakeRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTotalStakeRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTotalStakeRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTotalStakeRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalStakeRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetTotalStakeRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetTotalStakeRequest} returns this */ proto.pactus.GetTotalStakeRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetTotalStakeResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetTotalStakeResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetTotalStakeResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalStakeResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), totalStake: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetTotalStakeResponse} */ proto.pactus.GetTotalStakeResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetTotalStakeResponse; return proto.pactus.GetTotalStakeResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetTotalStakeResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetTotalStakeResponse} */ proto.pactus.GetTotalStakeResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setTotalStake(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetTotalStakeResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetTotalStakeResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetTotalStakeResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetTotalStakeResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getTotalStake(); if (f !== 0) { writer.writeInt64( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetTotalStakeResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetTotalStakeResponse} returns this */ proto.pactus.GetTotalStakeResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional int64 total_stake = 2; * @return {number} */ proto.pactus.GetTotalStakeResponse.prototype.getTotalStake = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetTotalStakeResponse} returns this */ proto.pactus.GetTotalStakeResponse.prototype.setTotalStake = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetAddressInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetAddressInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetAddressInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAddressInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), address: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetAddressInfoRequest} */ proto.pactus.GetAddressInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetAddressInfoRequest; return proto.pactus.GetAddressInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetAddressInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetAddressInfoRequest} */ proto.pactus.GetAddressInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetAddressInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetAddressInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetAddressInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAddressInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetAddressInfoRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetAddressInfoRequest} returns this */ proto.pactus.GetAddressInfoRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string address = 2; * @return {string} */ proto.pactus.GetAddressInfoRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetAddressInfoRequest} returns this */ proto.pactus.GetAddressInfoRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetAddressInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetAddressInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetAddressInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAddressInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), addr: (f = msg.getAddr()) && proto.pactus.AddressInfo.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetAddressInfoResponse} */ proto.pactus.GetAddressInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetAddressInfoResponse; return proto.pactus.GetAddressInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetAddressInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetAddressInfoResponse} */ proto.pactus.GetAddressInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = new proto.pactus.AddressInfo; reader.readMessage(value,proto.pactus.AddressInfo.deserializeBinaryFromReader); msg.setAddr(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetAddressInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetAddressInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetAddressInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetAddressInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddr(); if (f != null) { writer.writeMessage( 2, f, proto.pactus.AddressInfo.serializeBinaryToWriter ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetAddressInfoResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetAddressInfoResponse} returns this */ proto.pactus.GetAddressInfoResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional AddressInfo addr = 2; * @return {?proto.pactus.AddressInfo} */ proto.pactus.GetAddressInfoResponse.prototype.getAddr = function() { return /** @type{?proto.pactus.AddressInfo} */ ( jspb.Message.getWrapperField(this, proto.pactus.AddressInfo, 2)); }; /** * @param {?proto.pactus.AddressInfo|undefined} value * @return {!proto.pactus.GetAddressInfoResponse} returns this */ proto.pactus.GetAddressInfoResponse.prototype.setAddr = function(value) { return jspb.Message.setWrapperField(this, 2, value); }; /** * Clears the message field making it undefined. * @return {!proto.pactus.GetAddressInfoResponse} returns this */ proto.pactus.GetAddressInfoResponse.prototype.clearAddr = function() { return this.setAddr(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.pactus.GetAddressInfoResponse.prototype.hasAddr = function() { return jspb.Message.getField(this, 2) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SetAddressLabelRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SetAddressLabelRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SetAddressLabelRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetAddressLabelRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), password: jspb.Message.getFieldWithDefault(msg, 2, ""), address: jspb.Message.getFieldWithDefault(msg, 3, ""), label: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SetAddressLabelRequest} */ proto.pactus.SetAddressLabelRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SetAddressLabelRequest; return proto.pactus.SetAddressLabelRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SetAddressLabelRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SetAddressLabelRequest} */ proto.pactus.SetAddressLabelRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setLabel(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SetAddressLabelRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SetAddressLabelRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SetAddressLabelRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetAddressLabelRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getLabel(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.SetAddressLabelRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelRequest} returns this */ proto.pactus.SetAddressLabelRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string password = 2; * @return {string} */ proto.pactus.SetAddressLabelRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelRequest} returns this */ proto.pactus.SetAddressLabelRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string address = 3; * @return {string} */ proto.pactus.SetAddressLabelRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelRequest} returns this */ proto.pactus.SetAddressLabelRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string label = 4; * @return {string} */ proto.pactus.SetAddressLabelRequest.prototype.getLabel = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelRequest} returns this */ proto.pactus.SetAddressLabelRequest.prototype.setLabel = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SetAddressLabelResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SetAddressLabelResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SetAddressLabelResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetAddressLabelResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), address: jspb.Message.getFieldWithDefault(msg, 2, ""), label: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SetAddressLabelResponse} */ proto.pactus.SetAddressLabelResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SetAddressLabelResponse; return proto.pactus.SetAddressLabelResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SetAddressLabelResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SetAddressLabelResponse} */ proto.pactus.SetAddressLabelResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setLabel(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SetAddressLabelResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SetAddressLabelResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SetAddressLabelResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetAddressLabelResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getLabel(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.SetAddressLabelResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelResponse} returns this */ proto.pactus.SetAddressLabelResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string address = 2; * @return {string} */ proto.pactus.SetAddressLabelResponse.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelResponse} returns this */ proto.pactus.SetAddressLabelResponse.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string label = 3; * @return {string} */ proto.pactus.SetAddressLabelResponse.prototype.getLabel = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.SetAddressLabelResponse} returns this */ proto.pactus.SetAddressLabelResponse.prototype.setLabel = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListWalletsRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListWalletsRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListWalletsRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListWalletsRequest.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListWalletsRequest} */ proto.pactus.ListWalletsRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListWalletsRequest; return proto.pactus.ListWalletsRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListWalletsRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListWalletsRequest} */ proto.pactus.ListWalletsRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListWalletsRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListWalletsRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListWalletsRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListWalletsRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.ListWalletsResponse.repeatedFields_ = [1]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListWalletsResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListWalletsResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListWalletsResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListWalletsResponse.toObject = function(includeInstance, msg) { var f, obj = { walletsList: (f = jspb.Message.getRepeatedField(msg, 1)) == null ? undefined : f }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListWalletsResponse} */ proto.pactus.ListWalletsResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListWalletsResponse; return proto.pactus.ListWalletsResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListWalletsResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListWalletsResponse} */ proto.pactus.ListWalletsResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.addWallets(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListWalletsResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListWalletsResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListWalletsResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListWalletsResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletsList(); if (f.length > 0) { writer.writeRepeatedString( 1, f ); } }; /** * repeated string wallets = 1; * @return {!Array} */ proto.pactus.ListWalletsResponse.prototype.getWalletsList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 1)); }; /** * @param {!Array} value * @return {!proto.pactus.ListWalletsResponse} returns this */ proto.pactus.ListWalletsResponse.prototype.setWalletsList = function(value) { return jspb.Message.setField(this, 1, value || []); }; /** * @param {string} value * @param {number=} opt_index * @return {!proto.pactus.ListWalletsResponse} returns this */ proto.pactus.ListWalletsResponse.prototype.addWallets = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 1, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.ListWalletsResponse} returns this */ proto.pactus.ListWalletsResponse.prototype.clearWalletsList = function() { return this.setWalletsList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetWalletInfoRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetWalletInfoRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetWalletInfoRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetWalletInfoRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetWalletInfoRequest} */ proto.pactus.GetWalletInfoRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetWalletInfoRequest; return proto.pactus.GetWalletInfoRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetWalletInfoRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetWalletInfoRequest} */ proto.pactus.GetWalletInfoRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetWalletInfoRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetWalletInfoRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetWalletInfoRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetWalletInfoRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetWalletInfoRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetWalletInfoRequest} returns this */ proto.pactus.GetWalletInfoRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetWalletInfoResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetWalletInfoResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetWalletInfoResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetWalletInfoResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), version: jspb.Message.getFieldWithDefault(msg, 2, 0), network: jspb.Message.getFieldWithDefault(msg, 3, ""), encrypted: jspb.Message.getBooleanFieldWithDefault(msg, 4, false), uuid: jspb.Message.getFieldWithDefault(msg, 5, ""), createdAt: jspb.Message.getFieldWithDefault(msg, 6, 0), defaultFee: jspb.Message.getFieldWithDefault(msg, 7, 0), driver: jspb.Message.getFieldWithDefault(msg, 8, ""), path: jspb.Message.getFieldWithDefault(msg, 9, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetWalletInfoResponse} */ proto.pactus.GetWalletInfoResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetWalletInfoResponse; return proto.pactus.GetWalletInfoResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetWalletInfoResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetWalletInfoResponse} */ proto.pactus.GetWalletInfoResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {number} */ (reader.readInt32()); msg.setVersion(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setNetwork(value); break; case 4: var value = /** @type {boolean} */ (reader.readBool()); msg.setEncrypted(value); break; case 5: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setUuid(value); break; case 6: var value = /** @type {number} */ (reader.readInt64()); msg.setCreatedAt(value); break; case 7: var value = /** @type {number} */ (reader.readInt64()); msg.setDefaultFee(value); break; case 8: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setDriver(value); break; case 9: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPath(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetWalletInfoResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetWalletInfoResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetWalletInfoResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetWalletInfoResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getVersion(); if (f !== 0) { writer.writeInt32( 2, f ); } f = message.getNetwork(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getEncrypted(); if (f) { writer.writeBool( 4, f ); } f = message.getUuid(); if (f.length > 0) { writer.writeString( 5, f ); } f = message.getCreatedAt(); if (f !== 0) { writer.writeInt64( 6, f ); } f = message.getDefaultFee(); if (f !== 0) { writer.writeInt64( 7, f ); } f = message.getDriver(); if (f.length > 0) { writer.writeString( 8, f ); } f = message.getPath(); if (f.length > 0) { writer.writeString( 9, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetWalletInfoResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional int32 version = 2; * @return {number} */ proto.pactus.GetWalletInfoResponse.prototype.getVersion = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setVersion = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; /** * optional string network = 3; * @return {string} */ proto.pactus.GetWalletInfoResponse.prototype.getNetwork = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setNetwork = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional bool encrypted = 4; * @return {boolean} */ proto.pactus.GetWalletInfoResponse.prototype.getEncrypted = function() { return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 4, false)); }; /** * @param {boolean} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setEncrypted = function(value) { return jspb.Message.setProto3BooleanField(this, 4, value); }; /** * optional string uuid = 5; * @return {string} */ proto.pactus.GetWalletInfoResponse.prototype.getUuid = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); }; /** * @param {string} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setUuid = function(value) { return jspb.Message.setProto3StringField(this, 5, value); }; /** * optional int64 created_at = 6; * @return {number} */ proto.pactus.GetWalletInfoResponse.prototype.getCreatedAt = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setCreatedAt = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional int64 default_fee = 7; * @return {number} */ proto.pactus.GetWalletInfoResponse.prototype.getDefaultFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {number} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setDefaultFee = function(value) { return jspb.Message.setProto3IntField(this, 7, value); }; /** * optional string driver = 8; * @return {string} */ proto.pactus.GetWalletInfoResponse.prototype.getDriver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, "")); }; /** * @param {string} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setDriver = function(value) { return jspb.Message.setProto3StringField(this, 8, value); }; /** * optional string path = 9; * @return {string} */ proto.pactus.GetWalletInfoResponse.prototype.getPath = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 9, "")); }; /** * @param {string} value * @return {!proto.pactus.GetWalletInfoResponse} returns this */ proto.pactus.GetWalletInfoResponse.prototype.setPath = function(value) { return jspb.Message.setProto3StringField(this, 9, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.ListAddressesRequest.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListAddressesRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListAddressesRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListAddressesRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListAddressesRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), addressTypesList: (f = jspb.Message.getRepeatedField(msg, 2)) == null ? undefined : f }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListAddressesRequest} */ proto.pactus.ListAddressesRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListAddressesRequest; return proto.pactus.ListAddressesRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListAddressesRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListAddressesRequest} */ proto.pactus.ListAddressesRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: reader.readPackableEnumInto(msg.getAddressTypesList()); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListAddressesRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListAddressesRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListAddressesRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListAddressesRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddressTypesList(); if (f.length > 0) { writer.writePackedEnum( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.ListAddressesRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ListAddressesRequest} returns this */ proto.pactus.ListAddressesRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * repeated AddressType address_types = 2; * @return {!Array} */ proto.pactus.ListAddressesRequest.prototype.getAddressTypesList = function() { return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 2)); }; /** * @param {!Array} value * @return {!proto.pactus.ListAddressesRequest} returns this */ proto.pactus.ListAddressesRequest.prototype.setAddressTypesList = function(value) { return jspb.Message.setField(this, 2, value || []); }; /** * @param {!proto.pactus.AddressType} value * @param {number=} opt_index * @return {!proto.pactus.ListAddressesRequest} returns this */ proto.pactus.ListAddressesRequest.prototype.addAddressTypes = function(value, opt_index) { return jspb.Message.addToRepeatedField(this, 2, value, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.ListAddressesRequest} returns this */ proto.pactus.ListAddressesRequest.prototype.clearAddressTypesList = function() { return this.setAddressTypesList([]); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.ListAddressesResponse.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListAddressesResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListAddressesResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListAddressesResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListAddressesResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), addrsList: jspb.Message.toObjectList(msg.getAddrsList(), proto.pactus.AddressInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListAddressesResponse} */ proto.pactus.ListAddressesResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListAddressesResponse; return proto.pactus.ListAddressesResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListAddressesResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListAddressesResponse} */ proto.pactus.ListAddressesResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = new proto.pactus.AddressInfo; reader.readMessage(value,proto.pactus.AddressInfo.deserializeBinaryFromReader); msg.addAddrs(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListAddressesResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListAddressesResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListAddressesResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListAddressesResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddrsList(); if (f.length > 0) { writer.writeRepeatedMessage( 2, f, proto.pactus.AddressInfo.serializeBinaryToWriter ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.ListAddressesResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ListAddressesResponse} returns this */ proto.pactus.ListAddressesResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * repeated AddressInfo addrs = 2; * @return {!Array} */ proto.pactus.ListAddressesResponse.prototype.getAddrsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.AddressInfo, 2)); }; /** * @param {!Array} value * @return {!proto.pactus.ListAddressesResponse} returns this */ proto.pactus.ListAddressesResponse.prototype.setAddrsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 2, value); }; /** * @param {!proto.pactus.AddressInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.AddressInfo} */ proto.pactus.ListAddressesResponse.prototype.addAddrs = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 2, opt_value, proto.pactus.AddressInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.ListAddressesResponse} returns this */ proto.pactus.ListAddressesResponse.prototype.clearAddrsList = function() { return this.setAddrsList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.UpdatePasswordRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.UpdatePasswordRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.UpdatePasswordRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UpdatePasswordRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), oldPassword: jspb.Message.getFieldWithDefault(msg, 2, ""), newPassword: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.UpdatePasswordRequest} */ proto.pactus.UpdatePasswordRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.UpdatePasswordRequest; return proto.pactus.UpdatePasswordRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.UpdatePasswordRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.UpdatePasswordRequest} */ proto.pactus.UpdatePasswordRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setOldPassword(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setNewPassword(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.UpdatePasswordRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.UpdatePasswordRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.UpdatePasswordRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UpdatePasswordRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getOldPassword(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getNewPassword(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.UpdatePasswordRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.UpdatePasswordRequest} returns this */ proto.pactus.UpdatePasswordRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string old_password = 2; * @return {string} */ proto.pactus.UpdatePasswordRequest.prototype.getOldPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.UpdatePasswordRequest} returns this */ proto.pactus.UpdatePasswordRequest.prototype.setOldPassword = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string new_password = 3; * @return {string} */ proto.pactus.UpdatePasswordRequest.prototype.getNewPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.UpdatePasswordRequest} returns this */ proto.pactus.UpdatePasswordRequest.prototype.setNewPassword = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.UpdatePasswordResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.UpdatePasswordResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.UpdatePasswordResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UpdatePasswordResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.UpdatePasswordResponse} */ proto.pactus.UpdatePasswordResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.UpdatePasswordResponse; return proto.pactus.UpdatePasswordResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.UpdatePasswordResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.UpdatePasswordResponse} */ proto.pactus.UpdatePasswordResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.UpdatePasswordResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.UpdatePasswordResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.UpdatePasswordResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.UpdatePasswordResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.UpdatePasswordResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.UpdatePasswordResponse} returns this */ proto.pactus.UpdatePasswordResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.WalletTransactionInfo.prototype.toObject = function(opt_includeInstance) { return proto.pactus.WalletTransactionInfo.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.WalletTransactionInfo} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.WalletTransactionInfo.toObject = function(includeInstance, msg) { var f, obj = { no: jspb.Message.getFieldWithDefault(msg, 1, 0), txId: jspb.Message.getFieldWithDefault(msg, 2, ""), sender: jspb.Message.getFieldWithDefault(msg, 3, ""), receiver: jspb.Message.getFieldWithDefault(msg, 4, ""), direction: jspb.Message.getFieldWithDefault(msg, 5, 0), amount: jspb.Message.getFieldWithDefault(msg, 6, 0), fee: jspb.Message.getFieldWithDefault(msg, 7, 0), memo: jspb.Message.getFieldWithDefault(msg, 8, ""), status: jspb.Message.getFieldWithDefault(msg, 9, 0), blockHeight: jspb.Message.getFieldWithDefault(msg, 10, 0), payloadType: jspb.Message.getFieldWithDefault(msg, 11, 0), data: msg.getData_asB64(), comment: jspb.Message.getFieldWithDefault(msg, 13, ""), createdAt: jspb.Message.getFieldWithDefault(msg, 14, 0), updatedAt: jspb.Message.getFieldWithDefault(msg, 15, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.WalletTransactionInfo} */ proto.pactus.WalletTransactionInfo.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.WalletTransactionInfo; return proto.pactus.WalletTransactionInfo.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.WalletTransactionInfo} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.WalletTransactionInfo} */ proto.pactus.WalletTransactionInfo.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt64()); msg.setNo(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setTxId(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setSender(value); break; case 4: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setReceiver(value); break; case 5: var value = /** @type {!proto.pactus.TxDirection} */ (reader.readEnum()); msg.setDirection(value); break; case 6: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; case 7: var value = /** @type {number} */ (reader.readInt64()); msg.setFee(value); break; case 8: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMemo(value); break; case 9: var value = /** @type {!proto.pactus.TransactionStatus} */ (reader.readEnum()); msg.setStatus(value); break; case 10: var value = /** @type {number} */ (reader.readUint32()); msg.setBlockHeight(value); break; case 11: var value = /** @type {!proto.pactus.PayloadType} */ (reader.readEnum()); msg.setPayloadType(value); break; case 12: var value = /** @type {!Uint8Array} */ (reader.readBytes()); msg.setData(value); break; case 13: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setComment(value); break; case 14: var value = /** @type {number} */ (reader.readInt64()); msg.setCreatedAt(value); break; case 15: var value = /** @type {number} */ (reader.readInt64()); msg.setUpdatedAt(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.WalletTransactionInfo.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.WalletTransactionInfo.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.WalletTransactionInfo} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.WalletTransactionInfo.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getNo(); if (f !== 0) { writer.writeInt64( 1, f ); } f = message.getTxId(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getSender(); if (f.length > 0) { writer.writeString( 3, f ); } f = message.getReceiver(); if (f.length > 0) { writer.writeString( 4, f ); } f = message.getDirection(); if (f !== 0.0) { writer.writeEnum( 5, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 6, f ); } f = message.getFee(); if (f !== 0) { writer.writeInt64( 7, f ); } f = message.getMemo(); if (f.length > 0) { writer.writeString( 8, f ); } f = message.getStatus(); if (f !== 0.0) { writer.writeEnum( 9, f ); } f = message.getBlockHeight(); if (f !== 0) { writer.writeUint32( 10, f ); } f = message.getPayloadType(); if (f !== 0.0) { writer.writeEnum( 11, f ); } f = message.getData_asU8(); if (f.length > 0) { writer.writeBytes( 12, f ); } f = message.getComment(); if (f.length > 0) { writer.writeString( 13, f ); } f = message.getCreatedAt(); if (f !== 0) { writer.writeInt64( 14, f ); } f = message.getUpdatedAt(); if (f !== 0) { writer.writeInt64( 15, f ); } }; /** * optional int64 no = 1; * @return {number} */ proto.pactus.WalletTransactionInfo.prototype.getNo = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); }; /** * @param {number} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setNo = function(value) { return jspb.Message.setProto3IntField(this, 1, value); }; /** * optional string tx_id = 2; * @return {string} */ proto.pactus.WalletTransactionInfo.prototype.getTxId = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setTxId = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string sender = 3; * @return {string} */ proto.pactus.WalletTransactionInfo.prototype.getSender = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setSender = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; /** * optional string receiver = 4; * @return {string} */ proto.pactus.WalletTransactionInfo.prototype.getReceiver = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setReceiver = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; /** * optional TxDirection direction = 5; * @return {!proto.pactus.TxDirection} */ proto.pactus.WalletTransactionInfo.prototype.getDirection = function() { return /** @type {!proto.pactus.TxDirection} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {!proto.pactus.TxDirection} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setDirection = function(value) { return jspb.Message.setProto3EnumField(this, 5, value); }; /** * optional int64 amount = 6; * @return {number} */ proto.pactus.WalletTransactionInfo.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0)); }; /** * @param {number} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 6, value); }; /** * optional int64 fee = 7; * @return {number} */ proto.pactus.WalletTransactionInfo.prototype.getFee = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 7, 0)); }; /** * @param {number} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setFee = function(value) { return jspb.Message.setProto3IntField(this, 7, value); }; /** * optional string memo = 8; * @return {string} */ proto.pactus.WalletTransactionInfo.prototype.getMemo = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 8, "")); }; /** * @param {string} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setMemo = function(value) { return jspb.Message.setProto3StringField(this, 8, value); }; /** * optional TransactionStatus status = 9; * @return {!proto.pactus.TransactionStatus} */ proto.pactus.WalletTransactionInfo.prototype.getStatus = function() { return /** @type {!proto.pactus.TransactionStatus} */ (jspb.Message.getFieldWithDefault(this, 9, 0)); }; /** * @param {!proto.pactus.TransactionStatus} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setStatus = function(value) { return jspb.Message.setProto3EnumField(this, 9, value); }; /** * optional uint32 block_height = 10; * @return {number} */ proto.pactus.WalletTransactionInfo.prototype.getBlockHeight = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 10, 0)); }; /** * @param {number} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setBlockHeight = function(value) { return jspb.Message.setProto3IntField(this, 10, value); }; /** * optional PayloadType payload_type = 11; * @return {!proto.pactus.PayloadType} */ proto.pactus.WalletTransactionInfo.prototype.getPayloadType = function() { return /** @type {!proto.pactus.PayloadType} */ (jspb.Message.getFieldWithDefault(this, 11, 0)); }; /** * @param {!proto.pactus.PayloadType} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setPayloadType = function(value) { return jspb.Message.setProto3EnumField(this, 11, value); }; /** * optional bytes data = 12; * @return {!(string|Uint8Array)} */ proto.pactus.WalletTransactionInfo.prototype.getData = function() { return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 12, "")); }; /** * optional bytes data = 12; * This is a type-conversion wrapper around `getData()` * @return {string} */ proto.pactus.WalletTransactionInfo.prototype.getData_asB64 = function() { return /** @type {string} */ (jspb.Message.bytesAsB64( this.getData())); }; /** * optional bytes data = 12; * Note that Uint8Array is not supported on all browsers. * @see http://caniuse.com/Uint8Array * This is a type-conversion wrapper around `getData()` * @return {!Uint8Array} */ proto.pactus.WalletTransactionInfo.prototype.getData_asU8 = function() { return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( this.getData())); }; /** * @param {!(string|Uint8Array)} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setData = function(value) { return jspb.Message.setProto3BytesField(this, 12, value); }; /** * optional string comment = 13; * @return {string} */ proto.pactus.WalletTransactionInfo.prototype.getComment = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 13, "")); }; /** * @param {string} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setComment = function(value) { return jspb.Message.setProto3StringField(this, 13, value); }; /** * optional int64 created_at = 14; * @return {number} */ proto.pactus.WalletTransactionInfo.prototype.getCreatedAt = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 14, 0)); }; /** * @param {number} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setCreatedAt = function(value) { return jspb.Message.setProto3IntField(this, 14, value); }; /** * optional int64 updated_at = 15; * @return {number} */ proto.pactus.WalletTransactionInfo.prototype.getUpdatedAt = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 15, 0)); }; /** * @param {number} value * @return {!proto.pactus.WalletTransactionInfo} returns this */ proto.pactus.WalletTransactionInfo.prototype.setUpdatedAt = function(value) { return jspb.Message.setProto3IntField(this, 15, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListTransactionsRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListTransactionsRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListTransactionsRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListTransactionsRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), address: jspb.Message.getFieldWithDefault(msg, 2, ""), direction: jspb.Message.getFieldWithDefault(msg, 3, 0), count: jspb.Message.getFieldWithDefault(msg, 4, 0), skip: jspb.Message.getFieldWithDefault(msg, 5, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListTransactionsRequest} */ proto.pactus.ListTransactionsRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListTransactionsRequest; return proto.pactus.ListTransactionsRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListTransactionsRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListTransactionsRequest} */ proto.pactus.ListTransactionsRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; case 3: var value = /** @type {!proto.pactus.TxDirection} */ (reader.readEnum()); msg.setDirection(value); break; case 4: var value = /** @type {number} */ (reader.readInt32()); msg.setCount(value); break; case 5: var value = /** @type {number} */ (reader.readInt32()); msg.setSkip(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListTransactionsRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListTransactionsRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListTransactionsRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListTransactionsRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getDirection(); if (f !== 0.0) { writer.writeEnum( 3, f ); } f = message.getCount(); if (f !== 0) { writer.writeInt32( 4, f ); } f = message.getSkip(); if (f !== 0) { writer.writeInt32( 5, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.ListTransactionsRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ListTransactionsRequest} returns this */ proto.pactus.ListTransactionsRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string address = 2; * @return {string} */ proto.pactus.ListTransactionsRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.ListTransactionsRequest} returns this */ proto.pactus.ListTransactionsRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional TxDirection direction = 3; * @return {!proto.pactus.TxDirection} */ proto.pactus.ListTransactionsRequest.prototype.getDirection = function() { return /** @type {!proto.pactus.TxDirection} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); }; /** * @param {!proto.pactus.TxDirection} value * @return {!proto.pactus.ListTransactionsRequest} returns this */ proto.pactus.ListTransactionsRequest.prototype.setDirection = function(value) { return jspb.Message.setProto3EnumField(this, 3, value); }; /** * optional int32 count = 4; * @return {number} */ proto.pactus.ListTransactionsRequest.prototype.getCount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); }; /** * @param {number} value * @return {!proto.pactus.ListTransactionsRequest} returns this */ proto.pactus.ListTransactionsRequest.prototype.setCount = function(value) { return jspb.Message.setProto3IntField(this, 4, value); }; /** * optional int32 skip = 5; * @return {number} */ proto.pactus.ListTransactionsRequest.prototype.getSkip = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); }; /** * @param {number} value * @return {!proto.pactus.ListTransactionsRequest} returns this */ proto.pactus.ListTransactionsRequest.prototype.setSkip = function(value) { return jspb.Message.setProto3IntField(this, 5, value); }; /** * List of repeated fields within this message type. * @private {!Array} * @const */ proto.pactus.ListTransactionsResponse.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.ListTransactionsResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.ListTransactionsResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.ListTransactionsResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListTransactionsResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), txsList: jspb.Message.toObjectList(msg.getTxsList(), proto.pactus.WalletTransactionInfo.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.ListTransactionsResponse} */ proto.pactus.ListTransactionsResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.ListTransactionsResponse; return proto.pactus.ListTransactionsResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.ListTransactionsResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.ListTransactionsResponse} */ proto.pactus.ListTransactionsResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = new proto.pactus.WalletTransactionInfo; reader.readMessage(value,proto.pactus.WalletTransactionInfo.deserializeBinaryFromReader); msg.addTxs(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.ListTransactionsResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.ListTransactionsResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.ListTransactionsResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.ListTransactionsResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getTxsList(); if (f.length > 0) { writer.writeRepeatedMessage( 2, f, proto.pactus.WalletTransactionInfo.serializeBinaryToWriter ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.ListTransactionsResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.ListTransactionsResponse} returns this */ proto.pactus.ListTransactionsResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * repeated WalletTransactionInfo txs = 2; * @return {!Array} */ proto.pactus.ListTransactionsResponse.prototype.getTxsList = function() { return /** @type{!Array} */ ( jspb.Message.getRepeatedWrapperField(this, proto.pactus.WalletTransactionInfo, 2)); }; /** * @param {!Array} value * @return {!proto.pactus.ListTransactionsResponse} returns this */ proto.pactus.ListTransactionsResponse.prototype.setTxsList = function(value) { return jspb.Message.setRepeatedWrapperField(this, 2, value); }; /** * @param {!proto.pactus.WalletTransactionInfo=} opt_value * @param {number=} opt_index * @return {!proto.pactus.WalletTransactionInfo} */ proto.pactus.ListTransactionsResponse.prototype.addTxs = function(opt_value, opt_index) { return jspb.Message.addToRepeatedWrapperField(this, 2, opt_value, proto.pactus.WalletTransactionInfo, opt_index); }; /** * Clears the list making it empty but non-null. * @return {!proto.pactus.ListTransactionsResponse} returns this */ proto.pactus.ListTransactionsResponse.prototype.clearTxsList = function() { return this.setTxsList([]); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SetDefaultFeeRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SetDefaultFeeRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SetDefaultFeeRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetDefaultFeeRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), amount: jspb.Message.getFieldWithDefault(msg, 2, 0) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SetDefaultFeeRequest} */ proto.pactus.SetDefaultFeeRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SetDefaultFeeRequest; return proto.pactus.SetDefaultFeeRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SetDefaultFeeRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SetDefaultFeeRequest} */ proto.pactus.SetDefaultFeeRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setAmount(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SetDefaultFeeRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SetDefaultFeeRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SetDefaultFeeRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetDefaultFeeRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getAmount(); if (f !== 0) { writer.writeInt64( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.SetDefaultFeeRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SetDefaultFeeRequest} returns this */ proto.pactus.SetDefaultFeeRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional int64 amount = 2; * @return {number} */ proto.pactus.SetDefaultFeeRequest.prototype.getAmount = function() { return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); }; /** * @param {number} value * @return {!proto.pactus.SetDefaultFeeRequest} returns this */ proto.pactus.SetDefaultFeeRequest.prototype.setAmount = function(value) { return jspb.Message.setProto3IntField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.SetDefaultFeeResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.SetDefaultFeeResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.SetDefaultFeeResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetDefaultFeeResponse.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.SetDefaultFeeResponse} */ proto.pactus.SetDefaultFeeResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.SetDefaultFeeResponse; return proto.pactus.SetDefaultFeeResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.SetDefaultFeeResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.SetDefaultFeeResponse} */ proto.pactus.SetDefaultFeeResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.SetDefaultFeeResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.SetDefaultFeeResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.SetDefaultFeeResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.SetDefaultFeeResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.SetDefaultFeeResponse.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.SetDefaultFeeResponse} returns this */ proto.pactus.SetDefaultFeeResponse.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetMnemonicRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetMnemonicRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetMnemonicRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetMnemonicRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), password: jspb.Message.getFieldWithDefault(msg, 2, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetMnemonicRequest} */ proto.pactus.GetMnemonicRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetMnemonicRequest; return proto.pactus.GetMnemonicRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetMnemonicRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetMnemonicRequest} */ proto.pactus.GetMnemonicRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetMnemonicRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetMnemonicRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetMnemonicRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetMnemonicRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetMnemonicRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetMnemonicRequest} returns this */ proto.pactus.GetMnemonicRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string password = 2; * @return {string} */ proto.pactus.GetMnemonicRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetMnemonicRequest} returns this */ proto.pactus.GetMnemonicRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetMnemonicResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetMnemonicResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetMnemonicResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetMnemonicResponse.toObject = function(includeInstance, msg) { var f, obj = { mnemonic: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetMnemonicResponse} */ proto.pactus.GetMnemonicResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetMnemonicResponse; return proto.pactus.GetMnemonicResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetMnemonicResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetMnemonicResponse} */ proto.pactus.GetMnemonicResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setMnemonic(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetMnemonicResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetMnemonicResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetMnemonicResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetMnemonicResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getMnemonic(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string mnemonic = 1; * @return {string} */ proto.pactus.GetMnemonicResponse.prototype.getMnemonic = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetMnemonicResponse} returns this */ proto.pactus.GetMnemonicResponse.prototype.setMnemonic = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetPrivateKeyRequest.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetPrivateKeyRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetPrivateKeyRequest} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPrivateKeyRequest.toObject = function(includeInstance, msg) { var f, obj = { walletName: jspb.Message.getFieldWithDefault(msg, 1, ""), password: jspb.Message.getFieldWithDefault(msg, 2, ""), address: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetPrivateKeyRequest} */ proto.pactus.GetPrivateKeyRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetPrivateKeyRequest; return proto.pactus.GetPrivateKeyRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetPrivateKeyRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetPrivateKeyRequest} */ proto.pactus.GetPrivateKeyRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setWalletName(value); break; case 2: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPassword(value); break; case 3: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setAddress(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetPrivateKeyRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetPrivateKeyRequest.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetPrivateKeyRequest} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPrivateKeyRequest.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getWalletName(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getPassword(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getAddress(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string wallet_name = 1; * @return {string} */ proto.pactus.GetPrivateKeyRequest.prototype.getWalletName = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetPrivateKeyRequest} returns this */ proto.pactus.GetPrivateKeyRequest.prototype.setWalletName = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string password = 2; * @return {string} */ proto.pactus.GetPrivateKeyRequest.prototype.getPassword = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.pactus.GetPrivateKeyRequest} returns this */ proto.pactus.GetPrivateKeyRequest.prototype.setPassword = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional string address = 3; * @return {string} */ proto.pactus.GetPrivateKeyRequest.prototype.getAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.pactus.GetPrivateKeyRequest} returns this */ proto.pactus.GetPrivateKeyRequest.prototype.setAddress = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.pactus.GetPrivateKeyResponse.prototype.toObject = function(opt_includeInstance) { return proto.pactus.GetPrivateKeyResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.pactus.GetPrivateKeyResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPrivateKeyResponse.toObject = function(includeInstance, msg) { var f, obj = { privateKey: jspb.Message.getFieldWithDefault(msg, 1, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.binary.bytesource.ByteSource} bytes The bytes to deserialize. * @return {!proto.pactus.GetPrivateKeyResponse} */ proto.pactus.GetPrivateKeyResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.pactus.GetPrivateKeyResponse; return proto.pactus.GetPrivateKeyResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.pactus.GetPrivateKeyResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.pactus.GetPrivateKeyResponse} */ proto.pactus.GetPrivateKeyResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readStringRequireUtf8()); msg.setPrivateKey(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.pactus.GetPrivateKeyResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.pactus.GetPrivateKeyResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.pactus.GetPrivateKeyResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.pactus.GetPrivateKeyResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getPrivateKey(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * optional string private_key = 1; * @return {string} */ proto.pactus.GetPrivateKeyResponse.prototype.getPrivateKey = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.pactus.GetPrivateKeyResponse} returns this */ proto.pactus.GetPrivateKeyResponse.prototype.setPrivateKey = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * @enum {number} */ proto.pactus.AddressType = { ADDRESS_TYPE_TREASURY: 0, ADDRESS_TYPE_VALIDATOR: 1, ADDRESS_TYPE_BLS_ACCOUNT: 2, ADDRESS_TYPE_ED25519_ACCOUNT: 3 }; /** * @enum {number} */ proto.pactus.TxDirection = { TX_DIRECTION_ANY: 0, TX_DIRECTION_INCOMING: 1, TX_DIRECTION_OUTGOING: 2 }; /** * @enum {number} */ proto.pactus.TransactionStatus = { TRANSACTION_STATUS_PENDING: 0, TRANSACTION_STATUS_CONFIRMED: 1, TRANSACTION_STATUS_FAILED: -1 }; goog.object.extend(exports, proto.pactus); ================================================ FILE: www/grpc/gen/open-rpc/pactus-openrpc.json ================================================ { "openrpc": "1.2.1", "info": { "title": "Pactus OpenRPC", "version": "1.2.1" }, "methods": [{ "name": "pactus.transaction.get_transaction", "description": "GetTransaction retrieves transaction details based on the provided request parameters.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "id", "description": "The unique ID of the transaction to retrieve.", "schema": { "type": "string" } },{ "name": "verbosity", "description": "The verbosity level for transaction details.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["block_height","block_time","transaction"], "properties": {"block_height": { "type": "integer" },"block_time": { "type": "integer" },"transaction": { "type": "object","required": ["id","data","version","lock_time","value","fee","payload_type","transfer","bond","sortition","unbond","withdraw","batch_transfer","memo","public_key","signature","block_height","confirmed","confirmations"], "properties": {"id": { "type": "string" },"data": { "type": "string" },"version": { "type": "integer" },"lock_time": { "type": "integer" },"value": { "type": "integer" },"fee": { "type": "integer" },"payload_type": { "type": "integer" },"transfer": { "type": "object","required": ["sender","receiver","amount"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"amount": { "type": "integer" }} },"bond": { "type": "object","required": ["sender","receiver","stake","public_key","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"stake": { "type": "integer" },"public_key": { "type": "string" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} },"sortition": { "type": "object","required": ["address","proof"], "properties": {"address": { "type": "string" },"proof": { "type": "string" }} },"unbond": { "type": "object","required": ["validator","delegate_owner"], "properties": {"validator": { "type": "string" },"delegate_owner": { "type": "string" }} },"withdraw": { "type": "object","required": ["validator_address","account_address","amount"], "properties": {"validator_address": { "type": "string" },"account_address": { "type": "string" },"amount": { "type": "integer" }} },"batch_transfer": { "type": "object","required": ["sender","recipients"], "properties": {"sender": { "type": "string" },"recipients": { "type": "array", "items": { "type": "object","required": ["receiver","amount"], "properties": {"receiver": { "type": "string" },"amount": { "type": "integer" }} } }} },"memo": { "type": "string" },"public_key": { "type": "string" },"signature": { "type": "string" },"block_height": { "type": "integer" },"confirmed": { "type": "boolean" },"confirmations": { "type": "integer" }} }} } } },{ "name": "pactus.transaction.calculate_fee", "description": "CalculateFee calculates the transaction fee based on the specified amount and payload type.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "amount", "description": "The amount involved in the transaction, specified in NanoPAC.", "schema": { "type": "integer" } },{ "name": "payload_type", "description": "The type of transaction payload.", "schema": { "type": "integer" } },{ "name": "fixed_amount", "description": "Indicates if the amount should be fixed and include the fee.", "schema": { "type": "boolean" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["amount","fee"], "properties": {"amount": { "type": "integer" },"fee": { "type": "integer" }} } } },{ "name": "pactus.transaction.broadcast_transaction", "description": "BroadcastTransaction broadcasts a signed transaction to the network.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "signed_raw_transaction", "description": "The signed raw transaction data to be broadcasted.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["id"], "properties": {"id": { "type": "string" }} } } },{ "name": "pactus.transaction.get_raw_transfer_transaction", "description": "GetRawTransferTransaction retrieves raw details of a transfer transaction.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "lock_time", "description": "The lock time for the transaction. If not set, defaults to the last block height.", "schema": { "type": "integer" } },{ "name": "sender", "description": "The sender's account address.", "schema": { "type": "string" } },{ "name": "receiver", "description": "The receiver's account address.", "schema": { "type": "string" } },{ "name": "amount", "description": "The amount to be transferred, specified in NanoPAC. Must be greater than 0.", "schema": { "type": "integer" } },{ "name": "fee", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.", "schema": { "type": "integer" } },{ "name": "memo", "description": "A memo string for the transaction.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["raw_transaction","id"], "properties": {"raw_transaction": { "type": "string" },"id": { "type": "string" }} } } },{ "name": "pactus.transaction.get_raw_bond_transaction", "description": "GetRawBondTransaction retrieves raw details of a bond transaction.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "lock_time", "description": "The lock time for the transaction. If not set, defaults to the last block height.", "schema": { "type": "integer" } },{ "name": "sender", "description": "The sender's account address.", "schema": { "type": "string" } },{ "name": "receiver", "description": "The receiver's validator address.", "schema": { "type": "string" } },{ "name": "stake", "description": "The stake amount in NanoPAC. Must be greater than 0.", "schema": { "type": "integer" } },{ "name": "public_key", "description": "The public key of the validator. Optional, but required when registering a new validator.;", "schema": { "type": "string" } },{ "name": "fee", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.", "schema": { "type": "integer" } },{ "name": "memo", "description": "A memo string for the transaction.", "schema": { "type": "string" } },{ "name": "delegate_owner", "description": "The address of the delegate owner. Optional, but required when registering a new validator with delegation.;", "schema": { "type": "string" } },{ "name": "delegate_share", "description": "The share percentage for the delegate owner. Optional, but required when registering a new validator with delegation.; Must be between 0 and 0.7 PAC in nano PAC.", "schema": { "type": "integer" } },{ "name": "delegate_expiry", "description": "The expiry height for the delegate relationship. Optional, but required when registering a new validator with delegation.;", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["raw_transaction","id"], "properties": {"raw_transaction": { "type": "string" },"id": { "type": "string" }} } } },{ "name": "pactus.transaction.get_raw_unbond_transaction", "description": "GetRawUnbondTransaction retrieves raw details of an unbond transaction.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "lock_time", "description": "The lock time for the transaction. If not set, defaults to the last block height.", "schema": { "type": "integer" } },{ "name": "validator_address", "description": "The address of the validator to unbond from.", "schema": { "type": "string" } },{ "name": "memo", "description": "A memo string for the transaction.", "schema": { "type": "string" } },{ "name": "delegate_owner", "description": "The address of the delegate owner. Optional, but required when the validator is a delegated validator.;", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["raw_transaction","id"], "properties": {"raw_transaction": { "type": "string" },"id": { "type": "string" }} } } },{ "name": "pactus.transaction.get_raw_withdraw_transaction", "description": "GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "lock_time", "description": "The lock time for the transaction. If not set, defaults to the last block height.", "schema": { "type": "integer" } },{ "name": "validator_address", "description": "The address of the validator to withdraw from.", "schema": { "type": "string" } },{ "name": "account_address", "description": "The address of the account to withdraw to.", "schema": { "type": "string" } },{ "name": "amount", "description": "The withdrawal amount in NanoPAC. Must be greater than 0.", "schema": { "type": "integer" } },{ "name": "fee", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.", "schema": { "type": "integer" } },{ "name": "memo", "description": "A memo string for the transaction.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["raw_transaction","id"], "properties": {"raw_transaction": { "type": "string" },"id": { "type": "string" }} } } },{ "name": "pactus.transaction.get_raw_batch_transfer_transaction", "description": "GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "lock_time", "description": "The lock time for the transaction. If not set, defaults to the last block height.", "schema": { "type": "integer" } },{ "name": "sender", "description": "The sender's account address.", "schema": { "type": "string" } },{ "name": "recipients", "description": "The list of recipients with their amounts. Minimum 2 recipients required.", "schema": { "type": "array", "items": { "type": "object","required": ["receiver","amount"], "properties": {"receiver": { "type": "string" },"amount": { "type": "integer" }} } } },{ "name": "fee", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee.", "schema": { "type": "integer" } },{ "name": "memo", "description": "A memo string for the transaction.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["raw_transaction","id"], "properties": {"raw_transaction": { "type": "string" },"id": { "type": "string" }} } } },{ "name": "pactus.transaction.decode_raw_transaction", "description": "DecodeRawTransaction accepts raw transaction and returns decoded transaction.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "raw_transaction", "description": "The raw transaction data in hexadecimal format.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["transaction"], "properties": {"transaction": { "type": "object","required": ["id","data","version","lock_time","value","fee","payload_type","transfer","bond","sortition","unbond","withdraw","batch_transfer","memo","public_key","signature","block_height","confirmed","confirmations"], "properties": {"id": { "type": "string" },"data": { "type": "string" },"version": { "type": "integer" },"lock_time": { "type": "integer" },"value": { "type": "integer" },"fee": { "type": "integer" },"payload_type": { "type": "integer" },"transfer": { "type": "object","required": ["sender","receiver","amount"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"amount": { "type": "integer" }} },"bond": { "type": "object","required": ["sender","receiver","stake","public_key","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"stake": { "type": "integer" },"public_key": { "type": "string" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} },"sortition": { "type": "object","required": ["address","proof"], "properties": {"address": { "type": "string" },"proof": { "type": "string" }} },"unbond": { "type": "object","required": ["validator","delegate_owner"], "properties": {"validator": { "type": "string" },"delegate_owner": { "type": "string" }} },"withdraw": { "type": "object","required": ["validator_address","account_address","amount"], "properties": {"validator_address": { "type": "string" },"account_address": { "type": "string" },"amount": { "type": "integer" }} },"batch_transfer": { "type": "object","required": ["sender","recipients"], "properties": {"sender": { "type": "string" },"recipients": { "type": "array", "items": { "type": "object","required": ["receiver","amount"], "properties": {"receiver": { "type": "string" },"amount": { "type": "integer" }} } }} },"memo": { "type": "string" },"public_key": { "type": "string" },"signature": { "type": "string" },"block_height": { "type": "integer" },"confirmed": { "type": "boolean" },"confirmations": { "type": "integer" }} }} } } },{ "name": "pactus.transaction.check_transaction", "description": "CheckTransaction checks if the transaction is valid and can be included in the blockchain.", "tags": [{ "name": "transaction"}], "paramStructure": "by-name", "params": [{ "name": "raw_transaction", "description": "The raw transaction data to be checked.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["is_valid","error_message"], "properties": {"is_valid": { "type": "boolean" },"error_message": { "type": "string" }} } } },{ "name": "pactus.blockchain.get_block", "description": "GetBlock retrieves information about a block based on the provided request parameters.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "height", "description": "The height of the block to retrieve.", "schema": { "type": "integer" } },{ "name": "verbosity", "description": "The verbosity level for block information.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["height","hash","data","block_time","header","prev_cert","txs"], "properties": {"height": { "type": "integer" },"hash": { "type": "string" },"data": { "type": "string" },"block_time": { "type": "integer" },"header": { "type": "object","required": ["version","prev_block_hash","state_root","sortition_seed","proposer_address"], "properties": {"version": { "type": "integer" },"prev_block_hash": { "type": "string" },"state_root": { "type": "string" },"sortition_seed": { "type": "string" },"proposer_address": { "type": "string" }} },"prev_cert": { "type": "object","required": ["hash","round","committers","absentees","signature"], "properties": {"hash": { "type": "string" },"round": { "type": "integer" },"committers": { "type": "array", "items": { "type": "integer" } },"absentees": { "type": "array", "items": { "type": "integer" } },"signature": { "type": "string" }} },"txs": { "type": "array", "items": { "type": "object","required": ["id","data","version","lock_time","value","fee","payload_type","transfer","bond","sortition","unbond","withdraw","batch_transfer","memo","public_key","signature","block_height","confirmed","confirmations"], "properties": {"id": { "type": "string" },"data": { "type": "string" },"version": { "type": "integer" },"lock_time": { "type": "integer" },"value": { "type": "integer" },"fee": { "type": "integer" },"payload_type": { "type": "integer" },"transfer": { "type": "object","required": ["sender","receiver","amount"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"amount": { "type": "integer" }} },"bond": { "type": "object","required": ["sender","receiver","stake","public_key","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"stake": { "type": "integer" },"public_key": { "type": "string" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} },"sortition": { "type": "object","required": ["address","proof"], "properties": {"address": { "type": "string" },"proof": { "type": "string" }} },"unbond": { "type": "object","required": ["validator","delegate_owner"], "properties": {"validator": { "type": "string" },"delegate_owner": { "type": "string" }} },"withdraw": { "type": "object","required": ["validator_address","account_address","amount"], "properties": {"validator_address": { "type": "string" },"account_address": { "type": "string" },"amount": { "type": "integer" }} },"batch_transfer": { "type": "object","required": ["sender","recipients"], "properties": {"sender": { "type": "string" },"recipients": { "type": "array", "items": { "type": "object","required": ["receiver","amount"], "properties": {"receiver": { "type": "string" },"amount": { "type": "integer" }} } }} },"memo": { "type": "string" },"public_key": { "type": "string" },"signature": { "type": "string" },"block_height": { "type": "integer" },"confirmed": { "type": "boolean" },"confirmations": { "type": "integer" }} } }} } } },{ "name": "pactus.blockchain.get_block_hash", "description": "GetBlockHash retrieves the hash of a block at the specified height.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "height", "description": "The height of the block to retrieve the hash for.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["hash"], "properties": {"hash": { "type": "string" }} } } },{ "name": "pactus.blockchain.get_block_height", "description": "GetBlockHeight retrieves the height of a block with the specified hash.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "hash", "description": "The hash of the block to retrieve the height for.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["height"], "properties": {"height": { "type": "integer" }} } } },{ "name": "pactus.blockchain.get_blockchain_info", "description": "GetBlockchainInfo retrieves general information about the blockchain.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["last_block_height","last_block_hash","last_block_time","total_accounts","total_validators","active_validators","total_power","committee_power","is_pruned","pruning_height","in_committee","committee_size","average_score"], "properties": {"last_block_height": { "type": "integer" },"last_block_hash": { "type": "string" },"last_block_time": { "type": "integer" },"total_accounts": { "type": "integer" },"total_validators": { "type": "integer" },"active_validators": { "type": "integer" },"total_power": { "type": "integer" },"committee_power": { "type": "integer" },"is_pruned": { "type": "boolean" },"pruning_height": { "type": "integer" },"in_committee": { "type": "boolean" },"committee_size": { "type": "integer" },"average_score": { "type": "number" }} } } },{ "name": "pactus.blockchain.get_committee_info", "description": "GetCommitteeInfo retrieves information about the current committee.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["committee_size","committee_power","total_power","validators","protocol_versions"], "properties": {"committee_size": { "type": "integer" },"committee_power": { "type": "integer" },"total_power": { "type": "integer" },"validators": { "type": "array", "items": { "type": "object","required": ["hash","data","public_key","number","stake","last_bonding_height","last_sortition_height","unbonding_height","address","availability_score","protocol_version","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"hash": { "type": "string" },"data": { "type": "string" },"public_key": { "type": "string" },"number": { "type": "integer" },"stake": { "type": "integer" },"last_bonding_height": { "type": "integer" },"last_sortition_height": { "type": "integer" },"unbonding_height": { "type": "integer" },"address": { "type": "string" },"availability_score": { "type": "number" },"protocol_version": { "type": "integer" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} } },"protocol_versions": { "type": "object" }} } } },{ "name": "pactus.blockchain.get_consensus_info", "description": "GetConsensusInfo retrieves information about the consensus instances.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["proposal","instances"], "properties": {"proposal": { "type": "object","required": ["height","round","block_data","signature"], "properties": {"height": { "type": "integer" },"round": { "type": "integer" },"block_data": { "type": "string" },"signature": { "type": "string" }} },"instances": { "type": "array", "items": { "type": "object","required": ["address","active","height","round","votes"], "properties": {"address": { "type": "string" },"active": { "type": "boolean" },"height": { "type": "integer" },"round": { "type": "integer" },"votes": { "type": "array", "items": { "type": "object","required": ["type","voter","block_hash","round","cp_round","cp_value"], "properties": {"type": { "type": "integer" },"voter": { "type": "string" },"block_hash": { "type": "string" },"round": { "type": "integer" },"cp_round": { "type": "integer" },"cp_value": { "type": "integer" }} } }} } }} } } },{ "name": "pactus.blockchain.get_account", "description": "GetAccount retrieves information about an account based on the provided address.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "address", "description": "The address of the account to retrieve information for.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["account"], "properties": {"account": { "type": "object","required": ["hash","data","number","balance","address"], "properties": {"hash": { "type": "string" },"data": { "type": "string" },"number": { "type": "integer" },"balance": { "type": "integer" },"address": { "type": "string" }} }} } } },{ "name": "pactus.blockchain.get_validator", "description": "GetValidator retrieves information about a validator based on the provided address.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "address", "description": "The address of the validator to retrieve information for.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["validator"], "properties": {"validator": { "type": "object","required": ["hash","data","public_key","number","stake","last_bonding_height","last_sortition_height","unbonding_height","address","availability_score","protocol_version","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"hash": { "type": "string" },"data": { "type": "string" },"public_key": { "type": "string" },"number": { "type": "integer" },"stake": { "type": "integer" },"last_bonding_height": { "type": "integer" },"last_sortition_height": { "type": "integer" },"unbonding_height": { "type": "integer" },"address": { "type": "string" },"availability_score": { "type": "number" },"protocol_version": { "type": "integer" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} }} } } },{ "name": "pactus.blockchain.get_validator_by_number", "description": "GetValidatorByNumber retrieves information about a validator based on the provided number.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "number", "description": "The unique number of the validator to retrieve information for.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["validator"], "properties": {"validator": { "type": "object","required": ["hash","data","public_key","number","stake","last_bonding_height","last_sortition_height","unbonding_height","address","availability_score","protocol_version","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"hash": { "type": "string" },"data": { "type": "string" },"public_key": { "type": "string" },"number": { "type": "integer" },"stake": { "type": "integer" },"last_bonding_height": { "type": "integer" },"last_sortition_height": { "type": "integer" },"unbonding_height": { "type": "integer" },"address": { "type": "string" },"availability_score": { "type": "number" },"protocol_version": { "type": "integer" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} }} } } },{ "name": "pactus.blockchain.get_validator_addresses", "description": "GetValidatorAddresses retrieves a list of all validator addresses.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["addresses"], "properties": {"addresses": { "type": "array", "items": { "type": "string" } }} } } },{ "name": "pactus.blockchain.get_public_key", "description": "GetPublicKey retrieves the public key of an account based on the provided address.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "address", "description": "The address for which to retrieve the public key.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["public_key"], "properties": {"public_key": { "type": "string" }} } } },{ "name": "pactus.blockchain.get_tx_pool_content", "description": "GetTxPoolContent retrieves current transactions in the transaction pool.", "tags": [{ "name": "blockchain"}], "paramStructure": "by-name", "params": [{ "name": "payload_type", "description": "The type of transactions to retrieve from the transaction pool. 0 means all types.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["txs"], "properties": {"txs": { "type": "array", "items": { "type": "object","required": ["id","data","version","lock_time","value","fee","payload_type","transfer","bond","sortition","unbond","withdraw","batch_transfer","memo","public_key","signature","block_height","confirmed","confirmations"], "properties": {"id": { "type": "string" },"data": { "type": "string" },"version": { "type": "integer" },"lock_time": { "type": "integer" },"value": { "type": "integer" },"fee": { "type": "integer" },"payload_type": { "type": "integer" },"transfer": { "type": "object","required": ["sender","receiver","amount"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"amount": { "type": "integer" }} },"bond": { "type": "object","required": ["sender","receiver","stake","public_key","is_delegated","delegate_owner","delegate_share","delegate_expiry"], "properties": {"sender": { "type": "string" },"receiver": { "type": "string" },"stake": { "type": "integer" },"public_key": { "type": "string" },"is_delegated": { "type": "boolean" },"delegate_owner": { "type": "string" },"delegate_share": { "type": "integer" },"delegate_expiry": { "type": "integer" }} },"sortition": { "type": "object","required": ["address","proof"], "properties": {"address": { "type": "string" },"proof": { "type": "string" }} },"unbond": { "type": "object","required": ["validator","delegate_owner"], "properties": {"validator": { "type": "string" },"delegate_owner": { "type": "string" }} },"withdraw": { "type": "object","required": ["validator_address","account_address","amount"], "properties": {"validator_address": { "type": "string" },"account_address": { "type": "string" },"amount": { "type": "integer" }} },"batch_transfer": { "type": "object","required": ["sender","recipients"], "properties": {"sender": { "type": "string" },"recipients": { "type": "array", "items": { "type": "object","required": ["receiver","amount"], "properties": {"receiver": { "type": "string" },"amount": { "type": "integer" }} } }} },"memo": { "type": "string" },"public_key": { "type": "string" },"signature": { "type": "string" },"block_height": { "type": "integer" },"confirmed": { "type": "boolean" },"confirmations": { "type": "integer" }} } }} } } },{ "name": "pactus.network.get_network_info", "description": "GetNetworkInfo retrieves information about the overall network.", "tags": [{ "name": "network"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["network_name","connected_peers_count","metric_info"], "properties": {"network_name": { "type": "string" },"connected_peers_count": { "type": "integer" },"metric_info": { "type": "object","required": ["total_invalid","total_sent","total_received","message_sent","message_received"], "properties": {"total_invalid": { "type": "object","required": ["bytes","bundles"], "properties": {"bytes": { "type": "integer" },"bundles": { "type": "integer" }} },"total_sent": { "type": "object","required": ["bytes","bundles"], "properties": {"bytes": { "type": "integer" },"bundles": { "type": "integer" }} },"total_received": { "type": "object","required": ["bytes","bundles"], "properties": {"bytes": { "type": "integer" },"bundles": { "type": "integer" }} },"message_sent": { "type": "object" },"message_received": { "type": "object" }} }} } } },{ "name": "pactus.network.list_peers", "description": "ListPeers lists all peers in the network.", "tags": [{ "name": "network"}], "paramStructure": "by-name", "params": [{ "name": "include_disconnected", "description": "If true, includes disconnected peers (default: connected peers only).", "schema": { "type": "boolean" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["peers"], "properties": {"peers": { "type": "array", "items": { "type": "object","required": ["status","moniker","agent","peer_id","consensus_keys","consensus_addresses","services","last_block_hash","height","last_sent","last_received","address","direction","protocols","total_sessions","completed_sessions","metric_info","outbound_hello_sent"], "properties": {"status": { "type": "integer" },"moniker": { "type": "string" },"agent": { "type": "string" },"peer_id": { "type": "string" },"consensus_keys": { "type": "array", "items": { "type": "string" } },"consensus_addresses": { "type": "array", "items": { "type": "string" } },"services": { "type": "integer" },"last_block_hash": { "type": "string" },"height": { "type": "integer" },"last_sent": { "type": "integer" },"last_received": { "type": "integer" },"address": { "type": "string" },"direction": { "type": "integer" },"protocols": { "type": "array", "items": { "type": "string" } },"total_sessions": { "type": "integer" },"completed_sessions": { "type": "integer" },"metric_info": { "type": "object","required": ["total_invalid","total_sent","total_received","message_sent","message_received"], "properties": {"total_invalid": { "type": "object","required": ["bytes","bundles"], "properties": {"bytes": { "type": "integer" },"bundles": { "type": "integer" }} },"total_sent": { "type": "object","required": ["bytes","bundles"], "properties": {"bytes": { "type": "integer" },"bundles": { "type": "integer" }} },"total_received": { "type": "object","required": ["bytes","bundles"], "properties": {"bytes": { "type": "integer" },"bundles": { "type": "integer" }} },"message_sent": { "type": "object" },"message_received": { "type": "object" }} },"outbound_hello_sent": { "type": "boolean" }} } }} } } },{ "name": "pactus.network.get_node_info", "description": "GetNodeInfo retrieves information about a specific node in the network.", "tags": [{ "name": "network"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["moniker","agent","peer_id","started_at","reachability","services","services_names","local_addrs","protocols","clock_offset","connection_info","zmq_publishers","current_time","network_name"], "properties": {"moniker": { "type": "string" },"agent": { "type": "string" },"peer_id": { "type": "string" },"started_at": { "type": "integer" },"reachability": { "type": "string" },"services": { "type": "integer" },"services_names": { "type": "string" },"local_addrs": { "type": "array", "items": { "type": "string" } },"protocols": { "type": "array", "items": { "type": "string" } },"clock_offset": { "type": "number" },"connection_info": { "type": "object","required": ["connections","inbound_connections","outbound_connections"], "properties": {"connections": { "type": "integer" },"inbound_connections": { "type": "integer" },"outbound_connections": { "type": "integer" }} },"zmq_publishers": { "type": "array", "items": { "type": "object","required": ["topic","address","hwm"], "properties": {"topic": { "type": "string" },"address": { "type": "string" },"hwm": { "type": "integer" }} } },"current_time": { "type": "integer" },"network_name": { "type": "string" }} } } },{ "name": "pactus.network.ping", "description": "Ping provides a simple connectivity test and latency measurement.", "tags": [{ "name": "network"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": [], "properties": {} } } },{ "name": "pactus.utils.sign_message_with_private_key", "description": "SignMessageWithPrivateKey signs a message with the provided private key.", "tags": [{ "name": "utils"}], "paramStructure": "by-name", "params": [{ "name": "private_key", "description": "The private key to sign the message.", "schema": { "type": "string" } },{ "name": "message", "description": "The message content to be signed.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["signature"], "properties": {"signature": { "type": "string" }} } } },{ "name": "pactus.utils.verify_message", "description": "VerifyMessage verifies a signature against the public key and message.", "tags": [{ "name": "utils"}], "paramStructure": "by-name", "params": [{ "name": "message", "description": "The original message content that was signed.", "schema": { "type": "string" } },{ "name": "signature", "description": "The signature to verify in hexadecimal format.", "schema": { "type": "string" } },{ "name": "public_key", "description": "The public key of the signer.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["is_valid"], "properties": {"is_valid": { "type": "boolean" }} } } },{ "name": "pactus.utils.public_key_aggregation", "description": "PublicKeyAggregation aggregates multiple BLS public keys into a single key.", "tags": [{ "name": "utils"}], "paramStructure": "by-name", "params": [{ "name": "public_keys", "description": "List of BLS public keys to be aggregated.", "schema": { "type": "array", "items": { "type": "string" } } }], "result": { "name": "fields", "schema": { "type": "object","required": ["public_key","address"], "properties": {"public_key": { "type": "string" },"address": { "type": "string" }} } } },{ "name": "pactus.utils.signature_aggregation", "description": "SignatureAggregation aggregates multiple BLS signatures into a single signature.", "tags": [{ "name": "utils"}], "paramStructure": "by-name", "params": [{ "name": "signatures", "description": "List of BLS signatures to be aggregated.", "schema": { "type": "array", "items": { "type": "string" } } }], "result": { "name": "fields", "schema": { "type": "object","required": ["signature"], "properties": {"signature": { "type": "string" }} } } },{ "name": "pactus.wallet.create_wallet", "description": "CreateWallet creates a new wallet with the specified parameters.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name for the new wallet.", "schema": { "type": "string" } },{ "name": "password", "description": "Password to secure the new wallet.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","mnemonic"], "properties": {"wallet_name": { "type": "string" },"mnemonic": { "type": "string" }} } } },{ "name": "pactus.wallet.restore_wallet", "description": "RestoreWallet restores an existing wallet with the given mnemonic.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name for the restored wallet.", "schema": { "type": "string" } },{ "name": "mnemonic", "description": "The mnemonic (seed phrase) for wallet recovery.", "schema": { "type": "string" } },{ "name": "password", "description": "Password to secure the restored wallet.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name"], "properties": {"wallet_name": { "type": "string" }} } } },{ "name": "pactus.wallet.load_wallet", "description": "LoadWallet loads an existing wallet with the given name. deprecated: It will be removed in a future version.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to load.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name"], "properties": {"wallet_name": { "type": "string" }} } } },{ "name": "pactus.wallet.unload_wallet", "description": "UnloadWallet unloads a currently loaded wallet with the specified name. deprecated: It will be removed in a future version.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to unload.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name"], "properties": {"wallet_name": { "type": "string" }} } } },{ "name": "pactus.wallet.list_wallets", "description": "ListWallets returns a list of all available wallets.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [], "result": { "name": "fields", "schema": { "type": "object","required": ["wallets"], "properties": {"wallets": { "type": "array", "items": { "type": "string" } }} } } },{ "name": "pactus.wallet.get_wallet_info", "description": "GetWalletInfo returns detailed information about a specific wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to query.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","version","network","encrypted","uuid","created_at","default_fee","driver","path"], "properties": {"wallet_name": { "type": "string" },"version": { "type": "integer" },"network": { "type": "string" },"encrypted": { "type": "boolean" },"uuid": { "type": "string" },"created_at": { "type": "integer" },"default_fee": { "type": "integer" },"driver": { "type": "string" },"path": { "type": "string" }} } } },{ "name": "pactus.wallet.update_password", "description": "UpdatePassword updates the password of an existing wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet whose password will be updated.", "schema": { "type": "string" } },{ "name": "old_password", "description": "The current wallet password.", "schema": { "type": "string" } },{ "name": "new_password", "description": "The new wallet password.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name"], "properties": {"wallet_name": { "type": "string" }} } } },{ "name": "pactus.wallet.get_total_balance", "description": "GetTotalBalance returns the total available balance of the wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to get the total balance.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","total_balance"], "properties": {"wallet_name": { "type": "string" },"total_balance": { "type": "integer" }} } } },{ "name": "pactus.wallet.get_total_stake", "description": "GetTotalStake returns the total stake amount in the wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to get the total stake.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","total_stake"], "properties": {"wallet_name": { "type": "string" },"total_stake": { "type": "integer" }} } } },{ "name": "pactus.wallet.get_validator_address", "description": "GetValidatorAddress retrieves the validator address associated with a public key. Deprecated: Will move into utils.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "public_key", "description": "The public key of the validator.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["address"], "properties": {"address": { "type": "string" }} } } },{ "name": "pactus.wallet.get_address_info", "description": "GetAddressInfo returns detailed information about a specific address.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet containing the address.", "schema": { "type": "string" } },{ "name": "address", "description": "The address to query.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","addr"], "properties": {"wallet_name": { "type": "string" },"addr": { "type": "object","required": ["address","public_key","label","path"], "properties": {"address": { "type": "string" },"public_key": { "type": "string" },"label": { "type": "string" },"path": { "type": "string" }} }} } } },{ "name": "pactus.wallet.set_address_label", "description": "SetAddressLabel sets or updates the label for a given address.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet containing the address.", "schema": { "type": "string" } },{ "name": "password", "description": "Wallet password required for modification.", "schema": { "type": "string" } },{ "name": "address", "description": "The address to label.", "schema": { "type": "string" } },{ "name": "label", "description": "The new label for the address.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","address","label"], "properties": {"wallet_name": { "type": "string" },"address": { "type": "string" },"label": { "type": "string" }} } } },{ "name": "pactus.wallet.get_new_address", "description": "GetNewAddress generates a new address for the specified wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to generate a new address.", "schema": { "type": "string" } },{ "name": "address_type", "description": "The type of address to generate.", "schema": { "type": "integer" } },{ "name": "label", "description": "A label for the new address.", "schema": { "type": "string" } },{ "name": "password", "description": "Password for the new address. It's required when address_type is Ed25519 type.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","addr"], "properties": {"wallet_name": { "type": "string" },"addr": { "type": "object","required": ["address","public_key","label","path"], "properties": {"address": { "type": "string" },"public_key": { "type": "string" },"label": { "type": "string" },"path": { "type": "string" }} }} } } },{ "name": "pactus.wallet.list_addresses", "description": "ListAddresses returns all addresses in the specified wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the queried wallet.", "schema": { "type": "string" } },{ "name": "address_types", "description": "Filter addresses by their types. If empty, all address types are included.", "schema": { "type": "array", "items": { "type": "integer" } } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","addrs"], "properties": {"wallet_name": { "type": "string" },"addrs": { "type": "array", "items": { "type": "object","required": ["address","public_key","label","path"], "properties": {"address": { "type": "string" },"public_key": { "type": "string" },"label": { "type": "string" },"path": { "type": "string" }} } }} } } },{ "name": "pactus.wallet.sign_message", "description": "SignMessage signs an arbitrary message using a wallet's private key.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to sign with.", "schema": { "type": "string" } },{ "name": "password", "description": "Wallet password required for signing.", "schema": { "type": "string" } },{ "name": "address", "description": "The address whose private key should be used for signing the message.", "schema": { "type": "string" } },{ "name": "message", "description": "The arbitrary message to be signed.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["signature"], "properties": {"signature": { "type": "string" }} } } },{ "name": "pactus.wallet.sign_raw_transaction", "description": "SignRawTransaction signs a raw transaction for a specified wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet used for signing.", "schema": { "type": "string" } },{ "name": "raw_transaction", "description": "The raw transaction data to be signed.", "schema": { "type": "string" } },{ "name": "password", "description": "Wallet password required for signing.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["transaction_id","signed_raw_transaction"], "properties": {"transaction_id": { "type": "string" },"signed_raw_transaction": { "type": "string" }} } } },{ "name": "pactus.wallet.list_transactions", "description": "ListTransactions returns a list of transactions for a wallet, optionally filtered by a specific address, with pagination support.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to query transactions for.", "schema": { "type": "string" } },{ "name": "address", "description": "Optional: The address to filter transactions. If empty or set to '*', transactions for all addresses in the wallet are included.", "schema": { "type": "string" } },{ "name": "direction", "description": "Filter transactions by direction relative to the wallet. Defaults to any direction if not set.", "schema": { "type": "integer" } },{ "name": "count", "description": "Optional: The maximum number of transactions to return. Defaults to 10 if not set.", "schema": { "type": "integer" } },{ "name": "skip", "description": "Optional: The number of transactions to skip (for pagination). Defaults to 0 if not set.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name","txs"], "properties": {"wallet_name": { "type": "string" },"txs": { "type": "array", "items": { "type": "object","required": ["no","tx_id","sender","receiver","direction","amount","fee","memo","status","block_height","payload_type","data","comment","created_at","updated_at"], "properties": {"no": { "type": "integer" },"tx_id": { "type": "string" },"sender": { "type": "string" },"receiver": { "type": "string" },"direction": { "type": "integer" },"amount": { "type": "integer" },"fee": { "type": "integer" },"memo": { "type": "string" },"status": { "type": "integer" },"block_height": { "type": "integer" },"payload_type": { "type": "integer" },"data": { "type": "string" },"comment": { "type": "string" },"created_at": { "type": "integer" },"updated_at": { "type": "integer" }} } }} } } },{ "name": "pactus.wallet.set_default_fee", "description": "SetDefaultFee sets the default fee for the wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to set the default fee.", "schema": { "type": "string" } },{ "name": "amount", "description": "The default fee amount in NanoPAC.", "schema": { "type": "integer" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["wallet_name"], "properties": {"wallet_name": { "type": "string" }} } } },{ "name": "pactus.wallet.get_mnemonic", "description": "GetMnemonic returns the mnemonic (seed phrase) for the wallet.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet to get the mnemonic.", "schema": { "type": "string" } },{ "name": "password", "description": "Wallet password.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["mnemonic"], "properties": {"mnemonic": { "type": "string" }} } } },{ "name": "pactus.wallet.get_private_key", "description": "GetPrivateKey returns the private key for a given address.", "tags": [{ "name": "wallet"}], "paramStructure": "by-name", "params": [{ "name": "wallet_name", "description": "The name of the wallet containing the address.", "schema": { "type": "string" } },{ "name": "password", "description": "Wallet password.", "schema": { "type": "string" } },{ "name": "address", "description": "The address to get the private key.", "schema": { "type": "string" } }], "result": { "name": "fields", "schema": { "type": "object","required": ["private_key"], "properties": {"private_key": { "type": "string" }} } } }] } ================================================ FILE: www/grpc/gen/python/blockchain_pb2.py ================================================ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: blockchain.proto # Protobuf Python Version: 6.33.2 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import runtime_version as _runtime_version from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 6, 33, 2, '', 'blockchain.proto' ) # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() import transaction_pb2 as transaction__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10\x62lockchain.proto\x12\x06pactus\x1a\x11transaction.proto\"-\n\x11GetAccountRequest\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"C\n\x12GetAccountResponse\x12-\n\x07\x61\x63\x63ount\x18\x01 \x01(\x0b\x32\x13.pactus.AccountInfoR\x07\x61\x63\x63ount\"\x1e\n\x1cGetValidatorAddressesRequest\"=\n\x1dGetValidatorAddressesResponse\x12\x1c\n\taddresses\x18\x01 \x03(\tR\taddresses\"/\n\x13GetValidatorRequest\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"5\n\x1bGetValidatorByNumberRequest\x12\x16\n\x06number\x18\x01 \x01(\x05R\x06number\"K\n\x14GetValidatorResponse\x12\x33\n\tvalidator\x18\x01 \x01(\x0b\x32\x15.pactus.ValidatorInfoR\tvalidator\"/\n\x13GetPublicKeyRequest\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"5\n\x14GetPublicKeyResponse\x12\x1d\n\npublic_key\x18\x01 \x01(\tR\tpublicKey\"_\n\x0fGetBlockRequest\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\x12\x34\n\tverbosity\x18\x02 \x01(\x0e\x32\x16.pactus.BlockVerbosityR\tverbosity\"\x83\x02\n\x10GetBlockResponse\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\x12\x12\n\x04hash\x18\x02 \x01(\tR\x04hash\x12\x12\n\x04\x64\x61ta\x18\x03 \x01(\tR\x04\x64\x61ta\x12\x1d\n\nblock_time\x18\x04 \x01(\rR\tblockTime\x12/\n\x06header\x18\x05 \x01(\x0b\x32\x17.pactus.BlockHeaderInfoR\x06header\x12\x34\n\tprev_cert\x18\x06 \x01(\x0b\x32\x17.pactus.CertificateInfoR\x08prevCert\x12)\n\x03txs\x18\x07 \x03(\x0b\x32\x17.pactus.TransactionInfoR\x03txs\"-\n\x13GetBlockHashRequest\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\"*\n\x14GetBlockHashResponse\x12\x12\n\x04hash\x18\x01 \x01(\tR\x04hash\"+\n\x15GetBlockHeightRequest\x12\x12\n\x04hash\x18\x01 \x01(\tR\x04hash\"0\n\x16GetBlockHeightResponse\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\"\x1a\n\x18GetBlockchainInfoRequest\"\x93\x04\n\x19GetBlockchainInfoResponse\x12*\n\x11last_block_height\x18\x01 \x01(\rR\x0flastBlockHeight\x12&\n\x0flast_block_hash\x18\x02 \x01(\tR\rlastBlockHash\x12&\n\x0flast_block_time\x18\n \x01(\x03R\rlastBlockTime\x12%\n\x0etotal_accounts\x18\x03 \x01(\x05R\rtotalAccounts\x12)\n\x10total_validators\x18\x04 \x01(\x05R\x0ftotalValidators\x12+\n\x11\x61\x63tive_validators\x18\x0c \x01(\x05R\x10\x61\x63tiveValidators\x12\x1f\n\x0btotal_power\x18\x05 \x01(\x03R\ntotalPower\x12\'\n\x0f\x63ommittee_power\x18\x06 \x01(\x03R\x0e\x63ommitteePower\x12\x1b\n\tis_pruned\x18\x08 \x01(\x08R\x08isPruned\x12%\n\x0epruning_height\x18\t \x01(\rR\rpruningHeight\x12!\n\x0cin_committee\x18\r \x01(\x08R\x0binCommittee\x12%\n\x0e\x63ommittee_size\x18\x0e \x01(\x05R\rcommitteeSize\x12#\n\raverage_score\x18\x0f \x01(\x01R\x0c\x61verageScore\"\x19\n\x17GetCommitteeInfoRequest\"\xec\x02\n\x18GetCommitteeInfoResponse\x12%\n\x0e\x63ommittee_size\x18\x01 \x01(\x05R\rcommitteeSize\x12\'\n\x0f\x63ommittee_power\x18\x02 \x01(\x03R\x0e\x63ommitteePower\x12\x1f\n\x0btotal_power\x18\x03 \x01(\x03R\ntotalPower\x12\x35\n\nvalidators\x18\x04 \x03(\x0b\x32\x15.pactus.ValidatorInfoR\nvalidators\x12\x63\n\x11protocol_versions\x18\x05 \x03(\x0b\x32\x36.pactus.GetCommitteeInfoResponse.ProtocolVersionsEntryR\x10protocolVersions\x1a\x43\n\x15ProtocolVersionsEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x01R\x05value:\x02\x38\x01\"\x19\n\x17GetConsensusInfoRequest\"\x81\x01\n\x18GetConsensusInfoResponse\x12\x30\n\x08proposal\x18\x01 \x01(\x0b\x32\x14.pactus.ProposalInfoR\x08proposal\x12\x33\n\tinstances\x18\x02 \x03(\x0b\x32\x15.pactus.ConsensusInfoR\tinstances\"Q\n\x17GetTxPoolContentRequest\x12\x36\n\x0cpayload_type\x18\x01 \x01(\x0e\x32\x13.pactus.PayloadTypeR\x0bpayloadType\"E\n\x18GetTxPoolContentResponse\x12)\n\x03txs\x18\x01 \x03(\x0b\x32\x17.pactus.TransactionInfoR\x03txs\"\xa1\x04\n\rValidatorInfo\x12\x12\n\x04hash\x18\x01 \x01(\tR\x04hash\x12\x12\n\x04\x64\x61ta\x18\x02 \x01(\tR\x04\x64\x61ta\x12\x1d\n\npublic_key\x18\x03 \x01(\tR\tpublicKey\x12\x16\n\x06number\x18\x04 \x01(\x05R\x06number\x12\x14\n\x05stake\x18\x05 \x01(\x03R\x05stake\x12.\n\x13last_bonding_height\x18\x06 \x01(\rR\x11lastBondingHeight\x12\x32\n\x15last_sortition_height\x18\x07 \x01(\rR\x13lastSortitionHeight\x12)\n\x10unbonding_height\x18\x08 \x01(\rR\x0funbondingHeight\x12\x18\n\x07\x61\x64\x64ress\x18\t \x01(\tR\x07\x61\x64\x64ress\x12-\n\x12\x61vailability_score\x18\n \x01(\x01R\x11\x61vailabilityScore\x12)\n\x10protocol_version\x18\x0b \x01(\x05R\x0fprotocolVersion\x12!\n\x0cis_delegated\x18\x0c \x01(\x08R\x0bisDelegated\x12%\n\x0e\x64\x65legate_owner\x18\r \x01(\tR\rdelegateOwner\x12%\n\x0e\x64\x65legate_share\x18\x0e \x01(\x03R\rdelegateShare\x12\'\n\x0f\x64\x65legate_expiry\x18\x0f \x01(\rR\x0e\x64\x65legateExpiry\"\x81\x01\n\x0b\x41\x63\x63ountInfo\x12\x12\n\x04hash\x18\x01 \x01(\tR\x04hash\x12\x12\n\x04\x64\x61ta\x18\x02 \x01(\tR\x04\x64\x61ta\x12\x16\n\x06number\x18\x03 \x01(\x05R\x06number\x12\x18\n\x07\x62\x61lance\x18\x04 \x01(\x03R\x07\x62\x61lance\x12\x18\n\x07\x61\x64\x64ress\x18\x05 \x01(\tR\x07\x61\x64\x64ress\"\xc4\x01\n\x0f\x42lockHeaderInfo\x12\x18\n\x07version\x18\x01 \x01(\x05R\x07version\x12&\n\x0fprev_block_hash\x18\x02 \x01(\tR\rprevBlockHash\x12\x1d\n\nstate_root\x18\x03 \x01(\tR\tstateRoot\x12%\n\x0esortition_seed\x18\x04 \x01(\tR\rsortitionSeed\x12)\n\x10proposer_address\x18\x05 \x01(\tR\x0fproposerAddress\"\x97\x01\n\x0f\x43\x65rtificateInfo\x12\x12\n\x04hash\x18\x01 \x01(\tR\x04hash\x12\x14\n\x05round\x18\x02 \x01(\x05R\x05round\x12\x1e\n\ncommitters\x18\x03 \x03(\x05R\ncommitters\x12\x1c\n\tabsentees\x18\x04 \x03(\x05R\tabsentees\x12\x1c\n\tsignature\x18\x05 \x01(\tR\tsignature\"\xb1\x01\n\x08VoteInfo\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x10.pactus.VoteTypeR\x04type\x12\x14\n\x05voter\x18\x02 \x01(\tR\x05voter\x12\x1d\n\nblock_hash\x18\x03 \x01(\tR\tblockHash\x12\x14\n\x05round\x18\x04 \x01(\x05R\x05round\x12\x19\n\x08\x63p_round\x18\x05 \x01(\x05R\x07\x63pRound\x12\x19\n\x08\x63p_value\x18\x06 \x01(\x05R\x07\x63pValue\"\x97\x01\n\rConsensusInfo\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\x12\x16\n\x06\x61\x63tive\x18\x02 \x01(\x08R\x06\x61\x63tive\x12\x16\n\x06height\x18\x03 \x01(\rR\x06height\x12\x14\n\x05round\x18\x04 \x01(\x05R\x05round\x12&\n\x05votes\x18\x05 \x03(\x0b\x32\x10.pactus.VoteInfoR\x05votes\"y\n\x0cProposalInfo\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\x12\x14\n\x05round\x18\x02 \x01(\x05R\x05round\x12\x1d\n\nblock_data\x18\x03 \x01(\tR\tblockData\x12\x1c\n\tsignature\x18\x04 \x01(\tR\tsignature*f\n\x0e\x42lockVerbosity\x12\x18\n\x14\x42LOCK_VERBOSITY_DATA\x10\x00\x12\x18\n\x14\x42LOCK_VERBOSITY_INFO\x10\x01\x12 \n\x1c\x42LOCK_VERBOSITY_TRANSACTIONS\x10\x02*\xa6\x01\n\x08VoteType\x12\x19\n\x15VOTE_TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11VOTE_TYPE_PREPARE\x10\x01\x12\x17\n\x13VOTE_TYPE_PRECOMMIT\x10\x02\x12\x19\n\x15VOTE_TYPE_CP_PRE_VOTE\x10\x03\x12\x1a\n\x16VOTE_TYPE_CP_MAIN_VOTE\x10\x04\x12\x18\n\x14VOTE_TYPE_CP_DECIDED\x10\x05\x32\xe2\x07\n\nBlockchain\x12=\n\x08GetBlock\x12\x17.pactus.GetBlockRequest\x1a\x18.pactus.GetBlockResponse\x12I\n\x0cGetBlockHash\x12\x1b.pactus.GetBlockHashRequest\x1a\x1c.pactus.GetBlockHashResponse\x12O\n\x0eGetBlockHeight\x12\x1d.pactus.GetBlockHeightRequest\x1a\x1e.pactus.GetBlockHeightResponse\x12X\n\x11GetBlockchainInfo\x12 .pactus.GetBlockchainInfoRequest\x1a!.pactus.GetBlockchainInfoResponse\x12U\n\x10GetCommitteeInfo\x12\x1f.pactus.GetCommitteeInfoRequest\x1a .pactus.GetCommitteeInfoResponse\x12U\n\x10GetConsensusInfo\x12\x1f.pactus.GetConsensusInfoRequest\x1a .pactus.GetConsensusInfoResponse\x12\x43\n\nGetAccount\x12\x19.pactus.GetAccountRequest\x1a\x1a.pactus.GetAccountResponse\x12I\n\x0cGetValidator\x12\x1b.pactus.GetValidatorRequest\x1a\x1c.pactus.GetValidatorResponse\x12Y\n\x14GetValidatorByNumber\x12#.pactus.GetValidatorByNumberRequest\x1a\x1c.pactus.GetValidatorResponse\x12\x64\n\x15GetValidatorAddresses\x12$.pactus.GetValidatorAddressesRequest\x1a%.pactus.GetValidatorAddressesResponse\x12I\n\x0cGetPublicKey\x12\x1b.pactus.GetPublicKeyRequest\x1a\x1c.pactus.GetPublicKeyResponse\x12U\n\x10GetTxPoolContent\x12\x1f.pactus.GetTxPoolContentRequest\x1a .pactus.GetTxPoolContentResponseB:\n\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'blockchain_pb2', _globals) if not _descriptor._USE_C_DESCRIPTORS: _globals['DESCRIPTOR']._loaded_options = None _globals['DESCRIPTOR']._serialized_options = b'\n\006pactusZ0github.com/pactus-project/pactus/www/grpc/pactus' _globals['_GETCOMMITTEEINFORESPONSE_PROTOCOLVERSIONSENTRY']._loaded_options = None _globals['_GETCOMMITTEEINFORESPONSE_PROTOCOLVERSIONSENTRY']._serialized_options = b'8\001' _globals['_BLOCKVERBOSITY']._serialized_start=3847 _globals['_BLOCKVERBOSITY']._serialized_end=3949 _globals['_VOTETYPE']._serialized_start=3952 _globals['_VOTETYPE']._serialized_end=4118 _globals['_GETACCOUNTREQUEST']._serialized_start=47 _globals['_GETACCOUNTREQUEST']._serialized_end=92 _globals['_GETACCOUNTRESPONSE']._serialized_start=94 _globals['_GETACCOUNTRESPONSE']._serialized_end=161 _globals['_GETVALIDATORADDRESSESREQUEST']._serialized_start=163 _globals['_GETVALIDATORADDRESSESREQUEST']._serialized_end=193 _globals['_GETVALIDATORADDRESSESRESPONSE']._serialized_start=195 _globals['_GETVALIDATORADDRESSESRESPONSE']._serialized_end=256 _globals['_GETVALIDATORREQUEST']._serialized_start=258 _globals['_GETVALIDATORREQUEST']._serialized_end=305 _globals['_GETVALIDATORBYNUMBERREQUEST']._serialized_start=307 _globals['_GETVALIDATORBYNUMBERREQUEST']._serialized_end=360 _globals['_GETVALIDATORRESPONSE']._serialized_start=362 _globals['_GETVALIDATORRESPONSE']._serialized_end=437 _globals['_GETPUBLICKEYREQUEST']._serialized_start=439 _globals['_GETPUBLICKEYREQUEST']._serialized_end=486 _globals['_GETPUBLICKEYRESPONSE']._serialized_start=488 _globals['_GETPUBLICKEYRESPONSE']._serialized_end=541 _globals['_GETBLOCKREQUEST']._serialized_start=543 _globals['_GETBLOCKREQUEST']._serialized_end=638 _globals['_GETBLOCKRESPONSE']._serialized_start=641 _globals['_GETBLOCKRESPONSE']._serialized_end=900 _globals['_GETBLOCKHASHREQUEST']._serialized_start=902 _globals['_GETBLOCKHASHREQUEST']._serialized_end=947 _globals['_GETBLOCKHASHRESPONSE']._serialized_start=949 _globals['_GETBLOCKHASHRESPONSE']._serialized_end=991 _globals['_GETBLOCKHEIGHTREQUEST']._serialized_start=993 _globals['_GETBLOCKHEIGHTREQUEST']._serialized_end=1036 _globals['_GETBLOCKHEIGHTRESPONSE']._serialized_start=1038 _globals['_GETBLOCKHEIGHTRESPONSE']._serialized_end=1086 _globals['_GETBLOCKCHAININFOREQUEST']._serialized_start=1088 _globals['_GETBLOCKCHAININFOREQUEST']._serialized_end=1114 _globals['_GETBLOCKCHAININFORESPONSE']._serialized_start=1117 _globals['_GETBLOCKCHAININFORESPONSE']._serialized_end=1648 _globals['_GETCOMMITTEEINFOREQUEST']._serialized_start=1650 _globals['_GETCOMMITTEEINFOREQUEST']._serialized_end=1675 _globals['_GETCOMMITTEEINFORESPONSE']._serialized_start=1678 _globals['_GETCOMMITTEEINFORESPONSE']._serialized_end=2042 _globals['_GETCOMMITTEEINFORESPONSE_PROTOCOLVERSIONSENTRY']._serialized_start=1975 _globals['_GETCOMMITTEEINFORESPONSE_PROTOCOLVERSIONSENTRY']._serialized_end=2042 _globals['_GETCONSENSUSINFOREQUEST']._serialized_start=2044 _globals['_GETCONSENSUSINFOREQUEST']._serialized_end=2069 _globals['_GETCONSENSUSINFORESPONSE']._serialized_start=2072 _globals['_GETCONSENSUSINFORESPONSE']._serialized_end=2201 _globals['_GETTXPOOLCONTENTREQUEST']._serialized_start=2203 _globals['_GETTXPOOLCONTENTREQUEST']._serialized_end=2284 _globals['_GETTXPOOLCONTENTRESPONSE']._serialized_start=2286 _globals['_GETTXPOOLCONTENTRESPONSE']._serialized_end=2355 _globals['_VALIDATORINFO']._serialized_start=2358 _globals['_VALIDATORINFO']._serialized_end=2903 _globals['_ACCOUNTINFO']._serialized_start=2906 _globals['_ACCOUNTINFO']._serialized_end=3035 _globals['_BLOCKHEADERINFO']._serialized_start=3038 _globals['_BLOCKHEADERINFO']._serialized_end=3234 _globals['_CERTIFICATEINFO']._serialized_start=3237 _globals['_CERTIFICATEINFO']._serialized_end=3388 _globals['_VOTEINFO']._serialized_start=3391 _globals['_VOTEINFO']._serialized_end=3568 _globals['_CONSENSUSINFO']._serialized_start=3571 _globals['_CONSENSUSINFO']._serialized_end=3722 _globals['_PROPOSALINFO']._serialized_start=3724 _globals['_PROPOSALINFO']._serialized_end=3845 _globals['_BLOCKCHAIN']._serialized_start=4121 _globals['_BLOCKCHAIN']._serialized_end=5115 # @@protoc_insertion_point(module_scope) ================================================ FILE: www/grpc/gen/python/blockchain_pb2.pyi ================================================ import transaction_pb2 as _transaction_pb2 from google.protobuf.internal import containers as _containers from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from collections.abc import Iterable as _Iterable, Mapping as _Mapping from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union DESCRIPTOR: _descriptor.FileDescriptor class BlockVerbosity(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () BLOCK_VERBOSITY_DATA: _ClassVar[BlockVerbosity] BLOCK_VERBOSITY_INFO: _ClassVar[BlockVerbosity] BLOCK_VERBOSITY_TRANSACTIONS: _ClassVar[BlockVerbosity] class VoteType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () VOTE_TYPE_UNSPECIFIED: _ClassVar[VoteType] VOTE_TYPE_PREPARE: _ClassVar[VoteType] VOTE_TYPE_PRECOMMIT: _ClassVar[VoteType] VOTE_TYPE_CP_PRE_VOTE: _ClassVar[VoteType] VOTE_TYPE_CP_MAIN_VOTE: _ClassVar[VoteType] VOTE_TYPE_CP_DECIDED: _ClassVar[VoteType] BLOCK_VERBOSITY_DATA: BlockVerbosity BLOCK_VERBOSITY_INFO: BlockVerbosity BLOCK_VERBOSITY_TRANSACTIONS: BlockVerbosity VOTE_TYPE_UNSPECIFIED: VoteType VOTE_TYPE_PREPARE: VoteType VOTE_TYPE_PRECOMMIT: VoteType VOTE_TYPE_CP_PRE_VOTE: VoteType VOTE_TYPE_CP_MAIN_VOTE: VoteType VOTE_TYPE_CP_DECIDED: VoteType class GetAccountRequest(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] address: str def __init__(self, address: _Optional[str] = ...) -> None: ... class GetAccountResponse(_message.Message): __slots__ = () ACCOUNT_FIELD_NUMBER: _ClassVar[int] account: AccountInfo def __init__(self, account: _Optional[_Union[AccountInfo, _Mapping]] = ...) -> None: ... class GetValidatorAddressesRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class GetValidatorAddressesResponse(_message.Message): __slots__ = () ADDRESSES_FIELD_NUMBER: _ClassVar[int] addresses: _containers.RepeatedScalarFieldContainer[str] def __init__(self, addresses: _Optional[_Iterable[str]] = ...) -> None: ... class GetValidatorRequest(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] address: str def __init__(self, address: _Optional[str] = ...) -> None: ... class GetValidatorByNumberRequest(_message.Message): __slots__ = () NUMBER_FIELD_NUMBER: _ClassVar[int] number: int def __init__(self, number: _Optional[int] = ...) -> None: ... class GetValidatorResponse(_message.Message): __slots__ = () VALIDATOR_FIELD_NUMBER: _ClassVar[int] validator: ValidatorInfo def __init__(self, validator: _Optional[_Union[ValidatorInfo, _Mapping]] = ...) -> None: ... class GetPublicKeyRequest(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] address: str def __init__(self, address: _Optional[str] = ...) -> None: ... class GetPublicKeyResponse(_message.Message): __slots__ = () PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] public_key: str def __init__(self, public_key: _Optional[str] = ...) -> None: ... class GetBlockRequest(_message.Message): __slots__ = () HEIGHT_FIELD_NUMBER: _ClassVar[int] VERBOSITY_FIELD_NUMBER: _ClassVar[int] height: int verbosity: BlockVerbosity def __init__(self, height: _Optional[int] = ..., verbosity: _Optional[_Union[BlockVerbosity, str]] = ...) -> None: ... class GetBlockResponse(_message.Message): __slots__ = () HEIGHT_FIELD_NUMBER: _ClassVar[int] HASH_FIELD_NUMBER: _ClassVar[int] DATA_FIELD_NUMBER: _ClassVar[int] BLOCK_TIME_FIELD_NUMBER: _ClassVar[int] HEADER_FIELD_NUMBER: _ClassVar[int] PREV_CERT_FIELD_NUMBER: _ClassVar[int] TXS_FIELD_NUMBER: _ClassVar[int] height: int hash: str data: str block_time: int header: BlockHeaderInfo prev_cert: CertificateInfo txs: _containers.RepeatedCompositeFieldContainer[_transaction_pb2.TransactionInfo] def __init__(self, height: _Optional[int] = ..., hash: _Optional[str] = ..., data: _Optional[str] = ..., block_time: _Optional[int] = ..., header: _Optional[_Union[BlockHeaderInfo, _Mapping]] = ..., prev_cert: _Optional[_Union[CertificateInfo, _Mapping]] = ..., txs: _Optional[_Iterable[_Union[_transaction_pb2.TransactionInfo, _Mapping]]] = ...) -> None: ... class GetBlockHashRequest(_message.Message): __slots__ = () HEIGHT_FIELD_NUMBER: _ClassVar[int] height: int def __init__(self, height: _Optional[int] = ...) -> None: ... class GetBlockHashResponse(_message.Message): __slots__ = () HASH_FIELD_NUMBER: _ClassVar[int] hash: str def __init__(self, hash: _Optional[str] = ...) -> None: ... class GetBlockHeightRequest(_message.Message): __slots__ = () HASH_FIELD_NUMBER: _ClassVar[int] hash: str def __init__(self, hash: _Optional[str] = ...) -> None: ... class GetBlockHeightResponse(_message.Message): __slots__ = () HEIGHT_FIELD_NUMBER: _ClassVar[int] height: int def __init__(self, height: _Optional[int] = ...) -> None: ... class GetBlockchainInfoRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class GetBlockchainInfoResponse(_message.Message): __slots__ = () LAST_BLOCK_HEIGHT_FIELD_NUMBER: _ClassVar[int] LAST_BLOCK_HASH_FIELD_NUMBER: _ClassVar[int] LAST_BLOCK_TIME_FIELD_NUMBER: _ClassVar[int] TOTAL_ACCOUNTS_FIELD_NUMBER: _ClassVar[int] TOTAL_VALIDATORS_FIELD_NUMBER: _ClassVar[int] ACTIVE_VALIDATORS_FIELD_NUMBER: _ClassVar[int] TOTAL_POWER_FIELD_NUMBER: _ClassVar[int] COMMITTEE_POWER_FIELD_NUMBER: _ClassVar[int] IS_PRUNED_FIELD_NUMBER: _ClassVar[int] PRUNING_HEIGHT_FIELD_NUMBER: _ClassVar[int] IN_COMMITTEE_FIELD_NUMBER: _ClassVar[int] COMMITTEE_SIZE_FIELD_NUMBER: _ClassVar[int] AVERAGE_SCORE_FIELD_NUMBER: _ClassVar[int] last_block_height: int last_block_hash: str last_block_time: int total_accounts: int total_validators: int active_validators: int total_power: int committee_power: int is_pruned: bool pruning_height: int in_committee: bool committee_size: int average_score: float def __init__(self, last_block_height: _Optional[int] = ..., last_block_hash: _Optional[str] = ..., last_block_time: _Optional[int] = ..., total_accounts: _Optional[int] = ..., total_validators: _Optional[int] = ..., active_validators: _Optional[int] = ..., total_power: _Optional[int] = ..., committee_power: _Optional[int] = ..., is_pruned: _Optional[bool] = ..., pruning_height: _Optional[int] = ..., in_committee: _Optional[bool] = ..., committee_size: _Optional[int] = ..., average_score: _Optional[float] = ...) -> None: ... class GetCommitteeInfoRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class GetCommitteeInfoResponse(_message.Message): __slots__ = () class ProtocolVersionsEntry(_message.Message): __slots__ = () KEY_FIELD_NUMBER: _ClassVar[int] VALUE_FIELD_NUMBER: _ClassVar[int] key: int value: float def __init__(self, key: _Optional[int] = ..., value: _Optional[float] = ...) -> None: ... COMMITTEE_SIZE_FIELD_NUMBER: _ClassVar[int] COMMITTEE_POWER_FIELD_NUMBER: _ClassVar[int] TOTAL_POWER_FIELD_NUMBER: _ClassVar[int] VALIDATORS_FIELD_NUMBER: _ClassVar[int] PROTOCOL_VERSIONS_FIELD_NUMBER: _ClassVar[int] committee_size: int committee_power: int total_power: int validators: _containers.RepeatedCompositeFieldContainer[ValidatorInfo] protocol_versions: _containers.ScalarMap[int, float] def __init__(self, committee_size: _Optional[int] = ..., committee_power: _Optional[int] = ..., total_power: _Optional[int] = ..., validators: _Optional[_Iterable[_Union[ValidatorInfo, _Mapping]]] = ..., protocol_versions: _Optional[_Mapping[int, float]] = ...) -> None: ... class GetConsensusInfoRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class GetConsensusInfoResponse(_message.Message): __slots__ = () PROPOSAL_FIELD_NUMBER: _ClassVar[int] INSTANCES_FIELD_NUMBER: _ClassVar[int] proposal: ProposalInfo instances: _containers.RepeatedCompositeFieldContainer[ConsensusInfo] def __init__(self, proposal: _Optional[_Union[ProposalInfo, _Mapping]] = ..., instances: _Optional[_Iterable[_Union[ConsensusInfo, _Mapping]]] = ...) -> None: ... class GetTxPoolContentRequest(_message.Message): __slots__ = () PAYLOAD_TYPE_FIELD_NUMBER: _ClassVar[int] payload_type: _transaction_pb2.PayloadType def __init__(self, payload_type: _Optional[_Union[_transaction_pb2.PayloadType, str]] = ...) -> None: ... class GetTxPoolContentResponse(_message.Message): __slots__ = () TXS_FIELD_NUMBER: _ClassVar[int] txs: _containers.RepeatedCompositeFieldContainer[_transaction_pb2.TransactionInfo] def __init__(self, txs: _Optional[_Iterable[_Union[_transaction_pb2.TransactionInfo, _Mapping]]] = ...) -> None: ... class ValidatorInfo(_message.Message): __slots__ = () HASH_FIELD_NUMBER: _ClassVar[int] DATA_FIELD_NUMBER: _ClassVar[int] PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] NUMBER_FIELD_NUMBER: _ClassVar[int] STAKE_FIELD_NUMBER: _ClassVar[int] LAST_BONDING_HEIGHT_FIELD_NUMBER: _ClassVar[int] LAST_SORTITION_HEIGHT_FIELD_NUMBER: _ClassVar[int] UNBONDING_HEIGHT_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] AVAILABILITY_SCORE_FIELD_NUMBER: _ClassVar[int] PROTOCOL_VERSION_FIELD_NUMBER: _ClassVar[int] IS_DELEGATED_FIELD_NUMBER: _ClassVar[int] DELEGATE_OWNER_FIELD_NUMBER: _ClassVar[int] DELEGATE_SHARE_FIELD_NUMBER: _ClassVar[int] DELEGATE_EXPIRY_FIELD_NUMBER: _ClassVar[int] hash: str data: str public_key: str number: int stake: int last_bonding_height: int last_sortition_height: int unbonding_height: int address: str availability_score: float protocol_version: int is_delegated: bool delegate_owner: str delegate_share: int delegate_expiry: int def __init__(self, hash: _Optional[str] = ..., data: _Optional[str] = ..., public_key: _Optional[str] = ..., number: _Optional[int] = ..., stake: _Optional[int] = ..., last_bonding_height: _Optional[int] = ..., last_sortition_height: _Optional[int] = ..., unbonding_height: _Optional[int] = ..., address: _Optional[str] = ..., availability_score: _Optional[float] = ..., protocol_version: _Optional[int] = ..., is_delegated: _Optional[bool] = ..., delegate_owner: _Optional[str] = ..., delegate_share: _Optional[int] = ..., delegate_expiry: _Optional[int] = ...) -> None: ... class AccountInfo(_message.Message): __slots__ = () HASH_FIELD_NUMBER: _ClassVar[int] DATA_FIELD_NUMBER: _ClassVar[int] NUMBER_FIELD_NUMBER: _ClassVar[int] BALANCE_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] hash: str data: str number: int balance: int address: str def __init__(self, hash: _Optional[str] = ..., data: _Optional[str] = ..., number: _Optional[int] = ..., balance: _Optional[int] = ..., address: _Optional[str] = ...) -> None: ... class BlockHeaderInfo(_message.Message): __slots__ = () VERSION_FIELD_NUMBER: _ClassVar[int] PREV_BLOCK_HASH_FIELD_NUMBER: _ClassVar[int] STATE_ROOT_FIELD_NUMBER: _ClassVar[int] SORTITION_SEED_FIELD_NUMBER: _ClassVar[int] PROPOSER_ADDRESS_FIELD_NUMBER: _ClassVar[int] version: int prev_block_hash: str state_root: str sortition_seed: str proposer_address: str def __init__(self, version: _Optional[int] = ..., prev_block_hash: _Optional[str] = ..., state_root: _Optional[str] = ..., sortition_seed: _Optional[str] = ..., proposer_address: _Optional[str] = ...) -> None: ... class CertificateInfo(_message.Message): __slots__ = () HASH_FIELD_NUMBER: _ClassVar[int] ROUND_FIELD_NUMBER: _ClassVar[int] COMMITTERS_FIELD_NUMBER: _ClassVar[int] ABSENTEES_FIELD_NUMBER: _ClassVar[int] SIGNATURE_FIELD_NUMBER: _ClassVar[int] hash: str round: int committers: _containers.RepeatedScalarFieldContainer[int] absentees: _containers.RepeatedScalarFieldContainer[int] signature: str def __init__(self, hash: _Optional[str] = ..., round: _Optional[int] = ..., committers: _Optional[_Iterable[int]] = ..., absentees: _Optional[_Iterable[int]] = ..., signature: _Optional[str] = ...) -> None: ... class VoteInfo(_message.Message): __slots__ = () TYPE_FIELD_NUMBER: _ClassVar[int] VOTER_FIELD_NUMBER: _ClassVar[int] BLOCK_HASH_FIELD_NUMBER: _ClassVar[int] ROUND_FIELD_NUMBER: _ClassVar[int] CP_ROUND_FIELD_NUMBER: _ClassVar[int] CP_VALUE_FIELD_NUMBER: _ClassVar[int] type: VoteType voter: str block_hash: str round: int cp_round: int cp_value: int def __init__(self, type: _Optional[_Union[VoteType, str]] = ..., voter: _Optional[str] = ..., block_hash: _Optional[str] = ..., round: _Optional[int] = ..., cp_round: _Optional[int] = ..., cp_value: _Optional[int] = ...) -> None: ... class ConsensusInfo(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] ACTIVE_FIELD_NUMBER: _ClassVar[int] HEIGHT_FIELD_NUMBER: _ClassVar[int] ROUND_FIELD_NUMBER: _ClassVar[int] VOTES_FIELD_NUMBER: _ClassVar[int] address: str active: bool height: int round: int votes: _containers.RepeatedCompositeFieldContainer[VoteInfo] def __init__(self, address: _Optional[str] = ..., active: _Optional[bool] = ..., height: _Optional[int] = ..., round: _Optional[int] = ..., votes: _Optional[_Iterable[_Union[VoteInfo, _Mapping]]] = ...) -> None: ... class ProposalInfo(_message.Message): __slots__ = () HEIGHT_FIELD_NUMBER: _ClassVar[int] ROUND_FIELD_NUMBER: _ClassVar[int] BLOCK_DATA_FIELD_NUMBER: _ClassVar[int] SIGNATURE_FIELD_NUMBER: _ClassVar[int] height: int round: int block_data: str signature: str def __init__(self, height: _Optional[int] = ..., round: _Optional[int] = ..., block_data: _Optional[str] = ..., signature: _Optional[str] = ...) -> None: ... ================================================ FILE: www/grpc/gen/python/blockchain_pb2_grpc.py ================================================ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import blockchain_pb2 as blockchain__pb2 class BlockchainStub(object): """Blockchain service defines RPC methods for interacting with the blockchain. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetBlock = channel.unary_unary( '/pactus.Blockchain/GetBlock', request_serializer=blockchain__pb2.GetBlockRequest.SerializeToString, response_deserializer=blockchain__pb2.GetBlockResponse.FromString, _registered_method=True) self.GetBlockHash = channel.unary_unary( '/pactus.Blockchain/GetBlockHash', request_serializer=blockchain__pb2.GetBlockHashRequest.SerializeToString, response_deserializer=blockchain__pb2.GetBlockHashResponse.FromString, _registered_method=True) self.GetBlockHeight = channel.unary_unary( '/pactus.Blockchain/GetBlockHeight', request_serializer=blockchain__pb2.GetBlockHeightRequest.SerializeToString, response_deserializer=blockchain__pb2.GetBlockHeightResponse.FromString, _registered_method=True) self.GetBlockchainInfo = channel.unary_unary( '/pactus.Blockchain/GetBlockchainInfo', request_serializer=blockchain__pb2.GetBlockchainInfoRequest.SerializeToString, response_deserializer=blockchain__pb2.GetBlockchainInfoResponse.FromString, _registered_method=True) self.GetCommitteeInfo = channel.unary_unary( '/pactus.Blockchain/GetCommitteeInfo', request_serializer=blockchain__pb2.GetCommitteeInfoRequest.SerializeToString, response_deserializer=blockchain__pb2.GetCommitteeInfoResponse.FromString, _registered_method=True) self.GetConsensusInfo = channel.unary_unary( '/pactus.Blockchain/GetConsensusInfo', request_serializer=blockchain__pb2.GetConsensusInfoRequest.SerializeToString, response_deserializer=blockchain__pb2.GetConsensusInfoResponse.FromString, _registered_method=True) self.GetAccount = channel.unary_unary( '/pactus.Blockchain/GetAccount', request_serializer=blockchain__pb2.GetAccountRequest.SerializeToString, response_deserializer=blockchain__pb2.GetAccountResponse.FromString, _registered_method=True) self.GetValidator = channel.unary_unary( '/pactus.Blockchain/GetValidator', request_serializer=blockchain__pb2.GetValidatorRequest.SerializeToString, response_deserializer=blockchain__pb2.GetValidatorResponse.FromString, _registered_method=True) self.GetValidatorByNumber = channel.unary_unary( '/pactus.Blockchain/GetValidatorByNumber', request_serializer=blockchain__pb2.GetValidatorByNumberRequest.SerializeToString, response_deserializer=blockchain__pb2.GetValidatorResponse.FromString, _registered_method=True) self.GetValidatorAddresses = channel.unary_unary( '/pactus.Blockchain/GetValidatorAddresses', request_serializer=blockchain__pb2.GetValidatorAddressesRequest.SerializeToString, response_deserializer=blockchain__pb2.GetValidatorAddressesResponse.FromString, _registered_method=True) self.GetPublicKey = channel.unary_unary( '/pactus.Blockchain/GetPublicKey', request_serializer=blockchain__pb2.GetPublicKeyRequest.SerializeToString, response_deserializer=blockchain__pb2.GetPublicKeyResponse.FromString, _registered_method=True) self.GetTxPoolContent = channel.unary_unary( '/pactus.Blockchain/GetTxPoolContent', request_serializer=blockchain__pb2.GetTxPoolContentRequest.SerializeToString, response_deserializer=blockchain__pb2.GetTxPoolContentResponse.FromString, _registered_method=True) class BlockchainServicer(object): """Blockchain service defines RPC methods for interacting with the blockchain. """ def GetBlock(self, request, context): """GetBlock retrieves information about a block based on the provided request parameters. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetBlockHash(self, request, context): """GetBlockHash retrieves the hash of a block at the specified height. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetBlockHeight(self, request, context): """GetBlockHeight retrieves the height of a block with the specified hash. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetBlockchainInfo(self, request, context): """GetBlockchainInfo retrieves general information about the blockchain. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetCommitteeInfo(self, request, context): """GetCommitteeInfo retrieves information about the current committee. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetConsensusInfo(self, request, context): """GetConsensusInfo retrieves information about the consensus instances. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetAccount(self, request, context): """GetAccount retrieves information about an account based on the provided address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetValidator(self, request, context): """GetValidator retrieves information about a validator based on the provided address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetValidatorByNumber(self, request, context): """GetValidatorByNumber retrieves information about a validator based on the provided number. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetValidatorAddresses(self, request, context): """GetValidatorAddresses retrieves a list of all validator addresses. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetPublicKey(self, request, context): """GetPublicKey retrieves the public key of an account based on the provided address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetTxPoolContent(self, request, context): """GetTxPoolContent retrieves current transactions in the transaction pool. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_BlockchainServicer_to_server(servicer, server): rpc_method_handlers = { 'GetBlock': grpc.unary_unary_rpc_method_handler( servicer.GetBlock, request_deserializer=blockchain__pb2.GetBlockRequest.FromString, response_serializer=blockchain__pb2.GetBlockResponse.SerializeToString, ), 'GetBlockHash': grpc.unary_unary_rpc_method_handler( servicer.GetBlockHash, request_deserializer=blockchain__pb2.GetBlockHashRequest.FromString, response_serializer=blockchain__pb2.GetBlockHashResponse.SerializeToString, ), 'GetBlockHeight': grpc.unary_unary_rpc_method_handler( servicer.GetBlockHeight, request_deserializer=blockchain__pb2.GetBlockHeightRequest.FromString, response_serializer=blockchain__pb2.GetBlockHeightResponse.SerializeToString, ), 'GetBlockchainInfo': grpc.unary_unary_rpc_method_handler( servicer.GetBlockchainInfo, request_deserializer=blockchain__pb2.GetBlockchainInfoRequest.FromString, response_serializer=blockchain__pb2.GetBlockchainInfoResponse.SerializeToString, ), 'GetCommitteeInfo': grpc.unary_unary_rpc_method_handler( servicer.GetCommitteeInfo, request_deserializer=blockchain__pb2.GetCommitteeInfoRequest.FromString, response_serializer=blockchain__pb2.GetCommitteeInfoResponse.SerializeToString, ), 'GetConsensusInfo': grpc.unary_unary_rpc_method_handler( servicer.GetConsensusInfo, request_deserializer=blockchain__pb2.GetConsensusInfoRequest.FromString, response_serializer=blockchain__pb2.GetConsensusInfoResponse.SerializeToString, ), 'GetAccount': grpc.unary_unary_rpc_method_handler( servicer.GetAccount, request_deserializer=blockchain__pb2.GetAccountRequest.FromString, response_serializer=blockchain__pb2.GetAccountResponse.SerializeToString, ), 'GetValidator': grpc.unary_unary_rpc_method_handler( servicer.GetValidator, request_deserializer=blockchain__pb2.GetValidatorRequest.FromString, response_serializer=blockchain__pb2.GetValidatorResponse.SerializeToString, ), 'GetValidatorByNumber': grpc.unary_unary_rpc_method_handler( servicer.GetValidatorByNumber, request_deserializer=blockchain__pb2.GetValidatorByNumberRequest.FromString, response_serializer=blockchain__pb2.GetValidatorResponse.SerializeToString, ), 'GetValidatorAddresses': grpc.unary_unary_rpc_method_handler( servicer.GetValidatorAddresses, request_deserializer=blockchain__pb2.GetValidatorAddressesRequest.FromString, response_serializer=blockchain__pb2.GetValidatorAddressesResponse.SerializeToString, ), 'GetPublicKey': grpc.unary_unary_rpc_method_handler( servicer.GetPublicKey, request_deserializer=blockchain__pb2.GetPublicKeyRequest.FromString, response_serializer=blockchain__pb2.GetPublicKeyResponse.SerializeToString, ), 'GetTxPoolContent': grpc.unary_unary_rpc_method_handler( servicer.GetTxPoolContent, request_deserializer=blockchain__pb2.GetTxPoolContentRequest.FromString, response_serializer=blockchain__pb2.GetTxPoolContentResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'pactus.Blockchain', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) server.add_registered_method_handlers('pactus.Blockchain', rpc_method_handlers) # This class is part of an EXPERIMENTAL API. class Blockchain(object): """Blockchain service defines RPC methods for interacting with the blockchain. """ @staticmethod def GetBlock(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetBlock', blockchain__pb2.GetBlockRequest.SerializeToString, blockchain__pb2.GetBlockResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetBlockHash(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetBlockHash', blockchain__pb2.GetBlockHashRequest.SerializeToString, blockchain__pb2.GetBlockHashResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetBlockHeight(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetBlockHeight', blockchain__pb2.GetBlockHeightRequest.SerializeToString, blockchain__pb2.GetBlockHeightResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetBlockchainInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetBlockchainInfo', blockchain__pb2.GetBlockchainInfoRequest.SerializeToString, blockchain__pb2.GetBlockchainInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetCommitteeInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetCommitteeInfo', blockchain__pb2.GetCommitteeInfoRequest.SerializeToString, blockchain__pb2.GetCommitteeInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetConsensusInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetConsensusInfo', blockchain__pb2.GetConsensusInfoRequest.SerializeToString, blockchain__pb2.GetConsensusInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetAccount(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetAccount', blockchain__pb2.GetAccountRequest.SerializeToString, blockchain__pb2.GetAccountResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetValidator(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetValidator', blockchain__pb2.GetValidatorRequest.SerializeToString, blockchain__pb2.GetValidatorResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetValidatorByNumber(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetValidatorByNumber', blockchain__pb2.GetValidatorByNumberRequest.SerializeToString, blockchain__pb2.GetValidatorResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetValidatorAddresses(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetValidatorAddresses', blockchain__pb2.GetValidatorAddressesRequest.SerializeToString, blockchain__pb2.GetValidatorAddressesResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetPublicKey(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetPublicKey', blockchain__pb2.GetPublicKeyRequest.SerializeToString, blockchain__pb2.GetPublicKeyResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetTxPoolContent(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Blockchain/GetTxPoolContent', blockchain__pb2.GetTxPoolContentRequest.SerializeToString, blockchain__pb2.GetTxPoolContentResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) ================================================ FILE: www/grpc/gen/python/network_pb2.py ================================================ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: network.proto # Protobuf Python Version: 6.33.2 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import runtime_version as _runtime_version from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 6, 33, 2, '', 'network.proto' ) # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rnetwork.proto\x12\x06pactus\"\x17\n\x15GetNetworkInfoRequest\"\xa4\x01\n\x16GetNetworkInfoResponse\x12!\n\x0cnetwork_name\x18\x01 \x01(\tR\x0bnetworkName\x12\x32\n\x15\x63onnected_peers_count\x18\x02 \x01(\rR\x13\x63onnectedPeersCount\x12\x33\n\x0bmetric_info\x18\x04 \x01(\x0b\x32\x12.pactus.MetricInfoR\nmetricInfo\"E\n\x10ListPeersRequest\x12\x31\n\x14include_disconnected\x18\x01 \x01(\x08R\x13includeDisconnected\";\n\x11ListPeersResponse\x12&\n\x05peers\x18\x01 \x03(\x0b\x32\x10.pactus.PeerInfoR\x05peers\"\x14\n\x12GetNodeInfoRequest\"\x8e\x04\n\x13GetNodeInfoResponse\x12\x18\n\x07moniker\x18\x01 \x01(\tR\x07moniker\x12\x14\n\x05\x61gent\x18\x02 \x01(\tR\x05\x61gent\x12\x17\n\x07peer_id\x18\x03 \x01(\tR\x06peerId\x12\x1d\n\nstarted_at\x18\x04 \x01(\x04R\tstartedAt\x12\"\n\x0creachability\x18\x05 \x01(\tR\x0creachability\x12\x1a\n\x08services\x18\x06 \x01(\x05R\x08services\x12%\n\x0eservices_names\x18\x07 \x01(\tR\rservicesNames\x12\x1f\n\x0blocal_addrs\x18\x08 \x03(\tR\nlocalAddrs\x12\x1c\n\tprotocols\x18\t \x03(\tR\tprotocols\x12!\n\x0c\x63lock_offset\x18\r \x01(\x01R\x0b\x63lockOffset\x12?\n\x0f\x63onnection_info\x18\x0e \x01(\x0b\x32\x16.pactus.ConnectionInfoR\x0e\x63onnectionInfo\x12?\n\x0ezmq_publishers\x18\x0f \x03(\x0b\x32\x18.pactus.ZMQPublisherInfoR\rzmqPublishers\x12!\n\x0c\x63urrent_time\x18\x10 \x01(\x04R\x0b\x63urrentTime\x12!\n\x0cnetwork_name\x18\x11 \x01(\tR\x0bnetworkName\"T\n\x10ZMQPublisherInfo\x12\x14\n\x05topic\x18\x01 \x01(\tR\x05topic\x12\x18\n\x07\x61\x64\x64ress\x18\x02 \x01(\tR\x07\x61\x64\x64ress\x12\x10\n\x03hwm\x18\x03 \x01(\x05R\x03hwm\"\x85\x05\n\x08PeerInfo\x12\x16\n\x06status\x18\x01 \x01(\x05R\x06status\x12\x18\n\x07moniker\x18\x02 \x01(\tR\x07moniker\x12\x14\n\x05\x61gent\x18\x03 \x01(\tR\x05\x61gent\x12\x17\n\x07peer_id\x18\x04 \x01(\tR\x06peerId\x12%\n\x0e\x63onsensus_keys\x18\x05 \x03(\tR\rconsensusKeys\x12/\n\x13\x63onsensus_addresses\x18\x06 \x03(\tR\x12\x63onsensusAddresses\x12\x1a\n\x08services\x18\x07 \x01(\rR\x08services\x12&\n\x0flast_block_hash\x18\x08 \x01(\tR\rlastBlockHash\x12\x16\n\x06height\x18\t \x01(\rR\x06height\x12\x1b\n\tlast_sent\x18\n \x01(\x03R\x08lastSent\x12#\n\rlast_received\x18\x0b \x01(\x03R\x0clastReceived\x12\x18\n\x07\x61\x64\x64ress\x18\x0c \x01(\tR\x07\x61\x64\x64ress\x12/\n\tdirection\x18\r \x01(\x0e\x32\x11.pactus.DirectionR\tdirection\x12\x1c\n\tprotocols\x18\x0e \x03(\tR\tprotocols\x12%\n\x0etotal_sessions\x18\x0f \x01(\x05R\rtotalSessions\x12-\n\x12\x63ompleted_sessions\x18\x10 \x01(\x05R\x11\x63ompletedSessions\x12\x33\n\x0bmetric_info\x18\x11 \x01(\x0b\x32\x12.pactus.MetricInfoR\nmetricInfo\x12.\n\x13outbound_hello_sent\x18\x12 \x01(\x08R\x11outboundHelloSent\"\x96\x01\n\x0e\x43onnectionInfo\x12 \n\x0b\x63onnections\x18\x01 \x01(\x04R\x0b\x63onnections\x12/\n\x13inbound_connections\x18\x02 \x01(\x04R\x12inboundConnections\x12\x31\n\x14outbound_connections\x18\x03 \x01(\x04R\x13outboundConnections\"\x80\x04\n\nMetricInfo\x12\x38\n\rtotal_invalid\x18\x01 \x01(\x0b\x32\x13.pactus.CounterInfoR\x0ctotalInvalid\x12\x32\n\ntotal_sent\x18\x02 \x01(\x0b\x32\x13.pactus.CounterInfoR\ttotalSent\x12:\n\x0etotal_received\x18\x03 \x01(\x0b\x32\x13.pactus.CounterInfoR\rtotalReceived\x12\x46\n\x0cmessage_sent\x18\x04 \x03(\x0b\x32#.pactus.MetricInfo.MessageSentEntryR\x0bmessageSent\x12R\n\x10message_received\x18\x05 \x03(\x0b\x32\'.pactus.MetricInfo.MessageReceivedEntryR\x0fmessageReceived\x1aS\n\x10MessageSentEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12)\n\x05value\x18\x02 \x01(\x0b\x32\x13.pactus.CounterInfoR\x05value:\x02\x38\x01\x1aW\n\x14MessageReceivedEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12)\n\x05value\x18\x02 \x01(\x0b\x32\x13.pactus.CounterInfoR\x05value:\x02\x38\x01\"=\n\x0b\x43ounterInfo\x12\x14\n\x05\x62ytes\x18\x01 \x01(\x04R\x05\x62ytes\x12\x18\n\x07\x62undles\x18\x02 \x01(\x04R\x07\x62undles\"\r\n\x0bPingRequest\"\x0e\n\x0cPingResponse*Q\n\tDirection\x12\x15\n\x11\x44IRECTION_UNKNOWN\x10\x00\x12\x15\n\x11\x44IRECTION_INBOUND\x10\x01\x12\x16\n\x12\x44IRECTION_OUTBOUND\x10\x02\x32\x97\x02\n\x07Network\x12O\n\x0eGetNetworkInfo\x12\x1d.pactus.GetNetworkInfoRequest\x1a\x1e.pactus.GetNetworkInfoResponse\x12@\n\tListPeers\x12\x18.pactus.ListPeersRequest\x1a\x19.pactus.ListPeersResponse\x12\x46\n\x0bGetNodeInfo\x12\x1a.pactus.GetNodeInfoRequest\x1a\x1b.pactus.GetNodeInfoResponse\x12\x31\n\x04Ping\x12\x13.pactus.PingRequest\x1a\x14.pactus.PingResponseB:\n\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'network_pb2', _globals) if not _descriptor._USE_C_DESCRIPTORS: _globals['DESCRIPTOR']._loaded_options = None _globals['DESCRIPTOR']._serialized_options = b'\n\006pactusZ0github.com/pactus-project/pactus/www/grpc/pactus' _globals['_METRICINFO_MESSAGESENTENTRY']._loaded_options = None _globals['_METRICINFO_MESSAGESENTENTRY']._serialized_options = b'8\001' _globals['_METRICINFO_MESSAGERECEIVEDENTRY']._loaded_options = None _globals['_METRICINFO_MESSAGERECEIVEDENTRY']._serialized_options = b'8\001' _globals['_DIRECTION']._serialized_start=2396 _globals['_DIRECTION']._serialized_end=2477 _globals['_GETNETWORKINFOREQUEST']._serialized_start=25 _globals['_GETNETWORKINFOREQUEST']._serialized_end=48 _globals['_GETNETWORKINFORESPONSE']._serialized_start=51 _globals['_GETNETWORKINFORESPONSE']._serialized_end=215 _globals['_LISTPEERSREQUEST']._serialized_start=217 _globals['_LISTPEERSREQUEST']._serialized_end=286 _globals['_LISTPEERSRESPONSE']._serialized_start=288 _globals['_LISTPEERSRESPONSE']._serialized_end=347 _globals['_GETNODEINFOREQUEST']._serialized_start=349 _globals['_GETNODEINFOREQUEST']._serialized_end=369 _globals['_GETNODEINFORESPONSE']._serialized_start=372 _globals['_GETNODEINFORESPONSE']._serialized_end=898 _globals['_ZMQPUBLISHERINFO']._serialized_start=900 _globals['_ZMQPUBLISHERINFO']._serialized_end=984 _globals['_PEERINFO']._serialized_start=987 _globals['_PEERINFO']._serialized_end=1632 _globals['_CONNECTIONINFO']._serialized_start=1635 _globals['_CONNECTIONINFO']._serialized_end=1785 _globals['_METRICINFO']._serialized_start=1788 _globals['_METRICINFO']._serialized_end=2300 _globals['_METRICINFO_MESSAGESENTENTRY']._serialized_start=2128 _globals['_METRICINFO_MESSAGESENTENTRY']._serialized_end=2211 _globals['_METRICINFO_MESSAGERECEIVEDENTRY']._serialized_start=2213 _globals['_METRICINFO_MESSAGERECEIVEDENTRY']._serialized_end=2300 _globals['_COUNTERINFO']._serialized_start=2302 _globals['_COUNTERINFO']._serialized_end=2363 _globals['_PINGREQUEST']._serialized_start=2365 _globals['_PINGREQUEST']._serialized_end=2378 _globals['_PINGRESPONSE']._serialized_start=2380 _globals['_PINGRESPONSE']._serialized_end=2394 _globals['_NETWORK']._serialized_start=2480 _globals['_NETWORK']._serialized_end=2759 # @@protoc_insertion_point(module_scope) ================================================ FILE: www/grpc/gen/python/network_pb2.pyi ================================================ from google.protobuf.internal import containers as _containers from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from collections.abc import Iterable as _Iterable, Mapping as _Mapping from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union DESCRIPTOR: _descriptor.FileDescriptor class Direction(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () DIRECTION_UNKNOWN: _ClassVar[Direction] DIRECTION_INBOUND: _ClassVar[Direction] DIRECTION_OUTBOUND: _ClassVar[Direction] DIRECTION_UNKNOWN: Direction DIRECTION_INBOUND: Direction DIRECTION_OUTBOUND: Direction class GetNetworkInfoRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class GetNetworkInfoResponse(_message.Message): __slots__ = () NETWORK_NAME_FIELD_NUMBER: _ClassVar[int] CONNECTED_PEERS_COUNT_FIELD_NUMBER: _ClassVar[int] METRIC_INFO_FIELD_NUMBER: _ClassVar[int] network_name: str connected_peers_count: int metric_info: MetricInfo def __init__(self, network_name: _Optional[str] = ..., connected_peers_count: _Optional[int] = ..., metric_info: _Optional[_Union[MetricInfo, _Mapping]] = ...) -> None: ... class ListPeersRequest(_message.Message): __slots__ = () INCLUDE_DISCONNECTED_FIELD_NUMBER: _ClassVar[int] include_disconnected: bool def __init__(self, include_disconnected: _Optional[bool] = ...) -> None: ... class ListPeersResponse(_message.Message): __slots__ = () PEERS_FIELD_NUMBER: _ClassVar[int] peers: _containers.RepeatedCompositeFieldContainer[PeerInfo] def __init__(self, peers: _Optional[_Iterable[_Union[PeerInfo, _Mapping]]] = ...) -> None: ... class GetNodeInfoRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class GetNodeInfoResponse(_message.Message): __slots__ = () MONIKER_FIELD_NUMBER: _ClassVar[int] AGENT_FIELD_NUMBER: _ClassVar[int] PEER_ID_FIELD_NUMBER: _ClassVar[int] STARTED_AT_FIELD_NUMBER: _ClassVar[int] REACHABILITY_FIELD_NUMBER: _ClassVar[int] SERVICES_FIELD_NUMBER: _ClassVar[int] SERVICES_NAMES_FIELD_NUMBER: _ClassVar[int] LOCAL_ADDRS_FIELD_NUMBER: _ClassVar[int] PROTOCOLS_FIELD_NUMBER: _ClassVar[int] CLOCK_OFFSET_FIELD_NUMBER: _ClassVar[int] CONNECTION_INFO_FIELD_NUMBER: _ClassVar[int] ZMQ_PUBLISHERS_FIELD_NUMBER: _ClassVar[int] CURRENT_TIME_FIELD_NUMBER: _ClassVar[int] NETWORK_NAME_FIELD_NUMBER: _ClassVar[int] moniker: str agent: str peer_id: str started_at: int reachability: str services: int services_names: str local_addrs: _containers.RepeatedScalarFieldContainer[str] protocols: _containers.RepeatedScalarFieldContainer[str] clock_offset: float connection_info: ConnectionInfo zmq_publishers: _containers.RepeatedCompositeFieldContainer[ZMQPublisherInfo] current_time: int network_name: str def __init__(self, moniker: _Optional[str] = ..., agent: _Optional[str] = ..., peer_id: _Optional[str] = ..., started_at: _Optional[int] = ..., reachability: _Optional[str] = ..., services: _Optional[int] = ..., services_names: _Optional[str] = ..., local_addrs: _Optional[_Iterable[str]] = ..., protocols: _Optional[_Iterable[str]] = ..., clock_offset: _Optional[float] = ..., connection_info: _Optional[_Union[ConnectionInfo, _Mapping]] = ..., zmq_publishers: _Optional[_Iterable[_Union[ZMQPublisherInfo, _Mapping]]] = ..., current_time: _Optional[int] = ..., network_name: _Optional[str] = ...) -> None: ... class ZMQPublisherInfo(_message.Message): __slots__ = () TOPIC_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] HWM_FIELD_NUMBER: _ClassVar[int] topic: str address: str hwm: int def __init__(self, topic: _Optional[str] = ..., address: _Optional[str] = ..., hwm: _Optional[int] = ...) -> None: ... class PeerInfo(_message.Message): __slots__ = () STATUS_FIELD_NUMBER: _ClassVar[int] MONIKER_FIELD_NUMBER: _ClassVar[int] AGENT_FIELD_NUMBER: _ClassVar[int] PEER_ID_FIELD_NUMBER: _ClassVar[int] CONSENSUS_KEYS_FIELD_NUMBER: _ClassVar[int] CONSENSUS_ADDRESSES_FIELD_NUMBER: _ClassVar[int] SERVICES_FIELD_NUMBER: _ClassVar[int] LAST_BLOCK_HASH_FIELD_NUMBER: _ClassVar[int] HEIGHT_FIELD_NUMBER: _ClassVar[int] LAST_SENT_FIELD_NUMBER: _ClassVar[int] LAST_RECEIVED_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] DIRECTION_FIELD_NUMBER: _ClassVar[int] PROTOCOLS_FIELD_NUMBER: _ClassVar[int] TOTAL_SESSIONS_FIELD_NUMBER: _ClassVar[int] COMPLETED_SESSIONS_FIELD_NUMBER: _ClassVar[int] METRIC_INFO_FIELD_NUMBER: _ClassVar[int] OUTBOUND_HELLO_SENT_FIELD_NUMBER: _ClassVar[int] status: int moniker: str agent: str peer_id: str consensus_keys: _containers.RepeatedScalarFieldContainer[str] consensus_addresses: _containers.RepeatedScalarFieldContainer[str] services: int last_block_hash: str height: int last_sent: int last_received: int address: str direction: Direction protocols: _containers.RepeatedScalarFieldContainer[str] total_sessions: int completed_sessions: int metric_info: MetricInfo outbound_hello_sent: bool def __init__(self, status: _Optional[int] = ..., moniker: _Optional[str] = ..., agent: _Optional[str] = ..., peer_id: _Optional[str] = ..., consensus_keys: _Optional[_Iterable[str]] = ..., consensus_addresses: _Optional[_Iterable[str]] = ..., services: _Optional[int] = ..., last_block_hash: _Optional[str] = ..., height: _Optional[int] = ..., last_sent: _Optional[int] = ..., last_received: _Optional[int] = ..., address: _Optional[str] = ..., direction: _Optional[_Union[Direction, str]] = ..., protocols: _Optional[_Iterable[str]] = ..., total_sessions: _Optional[int] = ..., completed_sessions: _Optional[int] = ..., metric_info: _Optional[_Union[MetricInfo, _Mapping]] = ..., outbound_hello_sent: _Optional[bool] = ...) -> None: ... class ConnectionInfo(_message.Message): __slots__ = () CONNECTIONS_FIELD_NUMBER: _ClassVar[int] INBOUND_CONNECTIONS_FIELD_NUMBER: _ClassVar[int] OUTBOUND_CONNECTIONS_FIELD_NUMBER: _ClassVar[int] connections: int inbound_connections: int outbound_connections: int def __init__(self, connections: _Optional[int] = ..., inbound_connections: _Optional[int] = ..., outbound_connections: _Optional[int] = ...) -> None: ... class MetricInfo(_message.Message): __slots__ = () class MessageSentEntry(_message.Message): __slots__ = () KEY_FIELD_NUMBER: _ClassVar[int] VALUE_FIELD_NUMBER: _ClassVar[int] key: int value: CounterInfo def __init__(self, key: _Optional[int] = ..., value: _Optional[_Union[CounterInfo, _Mapping]] = ...) -> None: ... class MessageReceivedEntry(_message.Message): __slots__ = () KEY_FIELD_NUMBER: _ClassVar[int] VALUE_FIELD_NUMBER: _ClassVar[int] key: int value: CounterInfo def __init__(self, key: _Optional[int] = ..., value: _Optional[_Union[CounterInfo, _Mapping]] = ...) -> None: ... TOTAL_INVALID_FIELD_NUMBER: _ClassVar[int] TOTAL_SENT_FIELD_NUMBER: _ClassVar[int] TOTAL_RECEIVED_FIELD_NUMBER: _ClassVar[int] MESSAGE_SENT_FIELD_NUMBER: _ClassVar[int] MESSAGE_RECEIVED_FIELD_NUMBER: _ClassVar[int] total_invalid: CounterInfo total_sent: CounterInfo total_received: CounterInfo message_sent: _containers.MessageMap[int, CounterInfo] message_received: _containers.MessageMap[int, CounterInfo] def __init__(self, total_invalid: _Optional[_Union[CounterInfo, _Mapping]] = ..., total_sent: _Optional[_Union[CounterInfo, _Mapping]] = ..., total_received: _Optional[_Union[CounterInfo, _Mapping]] = ..., message_sent: _Optional[_Mapping[int, CounterInfo]] = ..., message_received: _Optional[_Mapping[int, CounterInfo]] = ...) -> None: ... class CounterInfo(_message.Message): __slots__ = () BYTES_FIELD_NUMBER: _ClassVar[int] BUNDLES_FIELD_NUMBER: _ClassVar[int] bytes: int bundles: int def __init__(self, bytes: _Optional[int] = ..., bundles: _Optional[int] = ...) -> None: ... class PingRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class PingResponse(_message.Message): __slots__ = () def __init__(self) -> None: ... ================================================ FILE: www/grpc/gen/python/network_pb2_grpc.py ================================================ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import network_pb2 as network__pb2 class NetworkStub(object): """Network service provides RPCs for retrieving information about the network. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetNetworkInfo = channel.unary_unary( '/pactus.Network/GetNetworkInfo', request_serializer=network__pb2.GetNetworkInfoRequest.SerializeToString, response_deserializer=network__pb2.GetNetworkInfoResponse.FromString, _registered_method=True) self.ListPeers = channel.unary_unary( '/pactus.Network/ListPeers', request_serializer=network__pb2.ListPeersRequest.SerializeToString, response_deserializer=network__pb2.ListPeersResponse.FromString, _registered_method=True) self.GetNodeInfo = channel.unary_unary( '/pactus.Network/GetNodeInfo', request_serializer=network__pb2.GetNodeInfoRequest.SerializeToString, response_deserializer=network__pb2.GetNodeInfoResponse.FromString, _registered_method=True) self.Ping = channel.unary_unary( '/pactus.Network/Ping', request_serializer=network__pb2.PingRequest.SerializeToString, response_deserializer=network__pb2.PingResponse.FromString, _registered_method=True) class NetworkServicer(object): """Network service provides RPCs for retrieving information about the network. """ def GetNetworkInfo(self, request, context): """GetNetworkInfo retrieves information about the overall network. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListPeers(self, request, context): """ListPeers lists all peers in the network. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetNodeInfo(self, request, context): """GetNodeInfo retrieves information about a specific node in the network. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Ping(self, request, context): """Ping provides a simple connectivity test and latency measurement. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_NetworkServicer_to_server(servicer, server): rpc_method_handlers = { 'GetNetworkInfo': grpc.unary_unary_rpc_method_handler( servicer.GetNetworkInfo, request_deserializer=network__pb2.GetNetworkInfoRequest.FromString, response_serializer=network__pb2.GetNetworkInfoResponse.SerializeToString, ), 'ListPeers': grpc.unary_unary_rpc_method_handler( servicer.ListPeers, request_deserializer=network__pb2.ListPeersRequest.FromString, response_serializer=network__pb2.ListPeersResponse.SerializeToString, ), 'GetNodeInfo': grpc.unary_unary_rpc_method_handler( servicer.GetNodeInfo, request_deserializer=network__pb2.GetNodeInfoRequest.FromString, response_serializer=network__pb2.GetNodeInfoResponse.SerializeToString, ), 'Ping': grpc.unary_unary_rpc_method_handler( servicer.Ping, request_deserializer=network__pb2.PingRequest.FromString, response_serializer=network__pb2.PingResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'pactus.Network', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) server.add_registered_method_handlers('pactus.Network', rpc_method_handlers) # This class is part of an EXPERIMENTAL API. class Network(object): """Network service provides RPCs for retrieving information about the network. """ @staticmethod def GetNetworkInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Network/GetNetworkInfo', network__pb2.GetNetworkInfoRequest.SerializeToString, network__pb2.GetNetworkInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def ListPeers(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Network/ListPeers', network__pb2.ListPeersRequest.SerializeToString, network__pb2.ListPeersResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetNodeInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Network/GetNodeInfo', network__pb2.GetNodeInfoRequest.SerializeToString, network__pb2.GetNodeInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def Ping(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Network/Ping', network__pb2.PingRequest.SerializeToString, network__pb2.PingResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) ================================================ FILE: www/grpc/gen/python/transaction_pb2.py ================================================ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: transaction.proto # Protobuf Python Version: 6.33.2 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import runtime_version as _runtime_version from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 6, 33, 2, '', 'transaction.proto' ) # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11transaction.proto\x12\x06pactus\"c\n\x15GetTransactionRequest\x12\x0e\n\x02id\x18\x01 \x01(\tR\x02id\x12:\n\tverbosity\x18\x02 \x01(\x0e\x32\x1c.pactus.TransactionVerbosityR\tverbosity\"\x95\x01\n\x16GetTransactionResponse\x12!\n\x0c\x62lock_height\x18\x01 \x01(\rR\x0b\x62lockHeight\x12\x1d\n\nblock_time\x18\x02 \x01(\rR\tblockTime\x12\x39\n\x0btransaction\x18\x03 \x01(\x0b\x32\x17.pactus.TransactionInfoR\x0btransaction\"\x88\x01\n\x13\x43\x61lculateFeeRequest\x12\x16\n\x06\x61mount\x18\x01 \x01(\x03R\x06\x61mount\x12\x36\n\x0cpayload_type\x18\x02 \x01(\x0e\x32\x13.pactus.PayloadTypeR\x0bpayloadType\x12!\n\x0c\x66ixed_amount\x18\x03 \x01(\x08R\x0b\x66ixedAmount\"@\n\x14\x43\x61lculateFeeResponse\x12\x16\n\x06\x61mount\x18\x01 \x01(\x03R\x06\x61mount\x12\x10\n\x03\x66\x65\x65\x18\x02 \x01(\x03R\x03\x66\x65\x65\"S\n\x1b\x42roadcastTransactionRequest\x12\x34\n\x16signed_raw_transaction\x18\x01 \x01(\tR\x14signedRawTransaction\".\n\x1c\x42roadcastTransactionResponse\x12\x0e\n\x02id\x18\x01 \x01(\tR\x02id\"\xb1\x01\n GetRawTransferTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12\x16\n\x06sender\x18\x02 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x03 \x01(\tR\x08receiver\x12\x16\n\x06\x61mount\x18\x04 \x01(\x03R\x06\x61mount\x12\x10\n\x03\x66\x65\x65\x18\x05 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x06 \x01(\tR\x04memo\"\xc1\x02\n\x1cGetRawBondTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12\x16\n\x06sender\x18\x02 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x03 \x01(\tR\x08receiver\x12\x14\n\x05stake\x18\x04 \x01(\x03R\x05stake\x12\x1d\n\npublic_key\x18\x05 \x01(\tR\tpublicKey\x12\x10\n\x03\x66\x65\x65\x18\x06 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x07 \x01(\tR\x04memo\x12%\n\x0e\x64\x65legate_owner\x18\x08 \x01(\tR\rdelegateOwner\x12%\n\x0e\x64\x65legate_share\x18\t \x01(\x03R\rdelegateShare\x12\'\n\x0f\x64\x65legate_expiry\x18\n \x01(\rR\x0e\x64\x65legateExpiry\"\xa5\x01\n\x1eGetRawUnbondTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12+\n\x11validator_address\x18\x02 \x01(\tR\x10validatorAddress\x12\x12\n\x04memo\x18\x03 \x01(\tR\x04memo\x12%\n\x0e\x64\x65legate_owner\x18\x04 \x01(\tR\rdelegateOwner\"\xd3\x01\n GetRawWithdrawTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12+\n\x11validator_address\x18\x02 \x01(\tR\x10validatorAddress\x12\'\n\x0f\x61\x63\x63ount_address\x18\x03 \x01(\tR\x0e\x61\x63\x63ountAddress\x12\x16\n\x06\x61mount\x18\x04 \x01(\x03R\x06\x61mount\x12\x10\n\x03\x66\x65\x65\x18\x05 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x06 \x01(\tR\x04memo\"\xb5\x01\n%GetRawBatchTransferTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12\x16\n\x06sender\x18\x02 \x01(\tR\x06sender\x12\x31\n\nrecipients\x18\x03 \x03(\x0b\x32\x11.pactus.RecipientR\nrecipients\x12\x10\n\x03\x66\x65\x65\x18\x04 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x05 \x01(\tR\x04memo\"T\n\x19GetRawTransactionResponse\x12\'\n\x0fraw_transaction\x18\x01 \x01(\tR\x0erawTransaction\x12\x0e\n\x02id\x18\x02 \x01(\tR\x02id\"]\n\x0fPayloadTransfer\x12\x16\n\x06sender\x18\x01 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x02 \x01(\tR\x08receiver\x12\x16\n\x06\x61mount\x18\x03 \x01(\x03R\x06\x61mount\"\x90\x02\n\x0bPayloadBond\x12\x16\n\x06sender\x18\x01 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x02 \x01(\tR\x08receiver\x12\x14\n\x05stake\x18\x03 \x01(\x03R\x05stake\x12\x1d\n\npublic_key\x18\x04 \x01(\tR\tpublicKey\x12!\n\x0cis_delegated\x18\x05 \x01(\x08R\x0bisDelegated\x12%\n\x0e\x64\x65legate_owner\x18\x06 \x01(\tR\rdelegateOwner\x12%\n\x0e\x64\x65legate_share\x18\x07 \x01(\x03R\rdelegateShare\x12\'\n\x0f\x64\x65legate_expiry\x18\x08 \x01(\rR\x0e\x64\x65legateExpiry\"B\n\x10PayloadSortition\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\x12\x14\n\x05proof\x18\x02 \x01(\tR\x05proof\"T\n\rPayloadUnbond\x12\x1c\n\tvalidator\x18\x01 \x01(\tR\tvalidator\x12%\n\x0e\x64\x65legate_owner\x18\x02 \x01(\tR\rdelegateOwner\"\x7f\n\x0fPayloadWithdraw\x12+\n\x11validator_address\x18\x01 \x01(\tR\x10validatorAddress\x12\'\n\x0f\x61\x63\x63ount_address\x18\x02 \x01(\tR\x0e\x61\x63\x63ountAddress\x12\x16\n\x06\x61mount\x18\x03 \x01(\x03R\x06\x61mount\"a\n\x14PayloadBatchTransfer\x12\x16\n\x06sender\x18\x01 \x01(\tR\x06sender\x12\x31\n\nrecipients\x18\x02 \x03(\x0b\x32\x11.pactus.RecipientR\nrecipients\"?\n\tRecipient\x12\x1a\n\x08receiver\x18\x01 \x01(\tR\x08receiver\x12\x16\n\x06\x61mount\x18\x02 \x01(\x03R\x06\x61mount\"\xda\x05\n\x0fTransactionInfo\x12\x0e\n\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n\x04\x64\x61ta\x18\x02 \x01(\tR\x04\x64\x61ta\x12\x18\n\x07version\x18\x03 \x01(\x05R\x07version\x12\x1b\n\tlock_time\x18\x04 \x01(\rR\x08lockTime\x12\x14\n\x05value\x18\x05 \x01(\x03R\x05value\x12\x10\n\x03\x66\x65\x65\x18\x06 \x01(\x03R\x03\x66\x65\x65\x12\x36\n\x0cpayload_type\x18\x07 \x01(\x0e\x32\x13.pactus.PayloadTypeR\x0bpayloadType\x12\x35\n\x08transfer\x18\x1e \x01(\x0b\x32\x17.pactus.PayloadTransferH\x00R\x08transfer\x12)\n\x04\x62ond\x18\x1f \x01(\x0b\x32\x13.pactus.PayloadBondH\x00R\x04\x62ond\x12\x38\n\tsortition\x18 \x01(\x0b\x32\x18.pactus.PayloadSortitionH\x00R\tsortition\x12/\n\x06unbond\x18! \x01(\x0b\x32\x15.pactus.PayloadUnbondH\x00R\x06unbond\x12\x35\n\x08withdraw\x18\" \x01(\x0b\x32\x17.pactus.PayloadWithdrawH\x00R\x08withdraw\x12\x45\n\x0e\x62\x61tch_transfer\x18# \x01(\x0b\x32\x1c.pactus.PayloadBatchTransferH\x00R\rbatchTransfer\x12\x12\n\x04memo\x18\x08 \x01(\tR\x04memo\x12\x1d\n\npublic_key\x18\t \x01(\tR\tpublicKey\x12\x1c\n\tsignature\x18\n \x01(\tR\tsignature\x12!\n\x0c\x62lock_height\x18\x0b \x01(\rR\x0b\x62lockHeight\x12\x1c\n\tconfirmed\x18\x0c \x01(\x08R\tconfirmed\x12$\n\rconfirmations\x18\r \x01(\x05R\rconfirmationsB\t\n\x07payload\"F\n\x1b\x44\x65\x63odeRawTransactionRequest\x12\'\n\x0fraw_transaction\x18\x01 \x01(\tR\x0erawTransaction\"Y\n\x1c\x44\x65\x63odeRawTransactionResponse\x12\x39\n\x0btransaction\x18\x01 \x01(\x0b\x32\x17.pactus.TransactionInfoR\x0btransaction\"B\n\x17\x43heckTransactionRequest\x12\'\n\x0fraw_transaction\x18\x01 \x01(\tR\x0erawTransaction\"Z\n\x18\x43heckTransactionResponse\x12\x19\n\x08is_valid\x18\x01 \x01(\x08R\x07isValid\x12#\n\rerror_message\x18\x02 \x01(\tR\x0c\x65rrorMessage*\xce\x01\n\x0bPayloadType\x12\x1c\n\x18PAYLOAD_TYPE_UNSPECIFIED\x10\x00\x12\x19\n\x15PAYLOAD_TYPE_TRANSFER\x10\x01\x12\x15\n\x11PAYLOAD_TYPE_BOND\x10\x02\x12\x1a\n\x16PAYLOAD_TYPE_SORTITION\x10\x03\x12\x17\n\x13PAYLOAD_TYPE_UNBOND\x10\x04\x12\x19\n\x15PAYLOAD_TYPE_WITHDRAW\x10\x05\x12\x1f\n\x1bPAYLOAD_TYPE_BATCH_TRANSFER\x10\x06*V\n\x14TransactionVerbosity\x12\x1e\n\x1aTRANSACTION_VERBOSITY_DATA\x10\x00\x12\x1e\n\x1aTRANSACTION_VERBOSITY_INFO\x10\x01\x32\xd6\x07\n\x0bTransaction\x12O\n\x0eGetTransaction\x12\x1d.pactus.GetTransactionRequest\x1a\x1e.pactus.GetTransactionResponse\x12I\n\x0c\x43\x61lculateFee\x12\x1b.pactus.CalculateFeeRequest\x1a\x1c.pactus.CalculateFeeResponse\x12\x61\n\x14\x42roadcastTransaction\x12#.pactus.BroadcastTransactionRequest\x1a$.pactus.BroadcastTransactionResponse\x12h\n\x19GetRawTransferTransaction\x12(.pactus.GetRawTransferTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12`\n\x15GetRawBondTransaction\x12$.pactus.GetRawBondTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12\x64\n\x17GetRawUnbondTransaction\x12&.pactus.GetRawUnbondTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12h\n\x19GetRawWithdrawTransaction\x12(.pactus.GetRawWithdrawTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12r\n\x1eGetRawBatchTransferTransaction\x12-.pactus.GetRawBatchTransferTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12\x61\n\x14\x44\x65\x63odeRawTransaction\x12#.pactus.DecodeRawTransactionRequest\x1a$.pactus.DecodeRawTransactionResponse\x12U\n\x10\x43heckTransaction\x12\x1f.pactus.CheckTransactionRequest\x1a .pactus.CheckTransactionResponseB:\n\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'transaction_pb2', _globals) if not _descriptor._USE_C_DESCRIPTORS: _globals['DESCRIPTOR']._loaded_options = None _globals['DESCRIPTOR']._serialized_options = b'\n\006pactusZ0github.com/pactus-project/pactus/www/grpc/pactus' _globals['_PAYLOADTYPE']._serialized_start=3650 _globals['_PAYLOADTYPE']._serialized_end=3856 _globals['_TRANSACTIONVERBOSITY']._serialized_start=3858 _globals['_TRANSACTIONVERBOSITY']._serialized_end=3944 _globals['_GETTRANSACTIONREQUEST']._serialized_start=29 _globals['_GETTRANSACTIONREQUEST']._serialized_end=128 _globals['_GETTRANSACTIONRESPONSE']._serialized_start=131 _globals['_GETTRANSACTIONRESPONSE']._serialized_end=280 _globals['_CALCULATEFEEREQUEST']._serialized_start=283 _globals['_CALCULATEFEEREQUEST']._serialized_end=419 _globals['_CALCULATEFEERESPONSE']._serialized_start=421 _globals['_CALCULATEFEERESPONSE']._serialized_end=485 _globals['_BROADCASTTRANSACTIONREQUEST']._serialized_start=487 _globals['_BROADCASTTRANSACTIONREQUEST']._serialized_end=570 _globals['_BROADCASTTRANSACTIONRESPONSE']._serialized_start=572 _globals['_BROADCASTTRANSACTIONRESPONSE']._serialized_end=618 _globals['_GETRAWTRANSFERTRANSACTIONREQUEST']._serialized_start=621 _globals['_GETRAWTRANSFERTRANSACTIONREQUEST']._serialized_end=798 _globals['_GETRAWBONDTRANSACTIONREQUEST']._serialized_start=801 _globals['_GETRAWBONDTRANSACTIONREQUEST']._serialized_end=1122 _globals['_GETRAWUNBONDTRANSACTIONREQUEST']._serialized_start=1125 _globals['_GETRAWUNBONDTRANSACTIONREQUEST']._serialized_end=1290 _globals['_GETRAWWITHDRAWTRANSACTIONREQUEST']._serialized_start=1293 _globals['_GETRAWWITHDRAWTRANSACTIONREQUEST']._serialized_end=1504 _globals['_GETRAWBATCHTRANSFERTRANSACTIONREQUEST']._serialized_start=1507 _globals['_GETRAWBATCHTRANSFERTRANSACTIONREQUEST']._serialized_end=1688 _globals['_GETRAWTRANSACTIONRESPONSE']._serialized_start=1690 _globals['_GETRAWTRANSACTIONRESPONSE']._serialized_end=1774 _globals['_PAYLOADTRANSFER']._serialized_start=1776 _globals['_PAYLOADTRANSFER']._serialized_end=1869 _globals['_PAYLOADBOND']._serialized_start=1872 _globals['_PAYLOADBOND']._serialized_end=2144 _globals['_PAYLOADSORTITION']._serialized_start=2146 _globals['_PAYLOADSORTITION']._serialized_end=2212 _globals['_PAYLOADUNBOND']._serialized_start=2214 _globals['_PAYLOADUNBOND']._serialized_end=2298 _globals['_PAYLOADWITHDRAW']._serialized_start=2300 _globals['_PAYLOADWITHDRAW']._serialized_end=2427 _globals['_PAYLOADBATCHTRANSFER']._serialized_start=2429 _globals['_PAYLOADBATCHTRANSFER']._serialized_end=2526 _globals['_RECIPIENT']._serialized_start=2528 _globals['_RECIPIENT']._serialized_end=2591 _globals['_TRANSACTIONINFO']._serialized_start=2594 _globals['_TRANSACTIONINFO']._serialized_end=3324 _globals['_DECODERAWTRANSACTIONREQUEST']._serialized_start=3326 _globals['_DECODERAWTRANSACTIONREQUEST']._serialized_end=3396 _globals['_DECODERAWTRANSACTIONRESPONSE']._serialized_start=3398 _globals['_DECODERAWTRANSACTIONRESPONSE']._serialized_end=3487 _globals['_CHECKTRANSACTIONREQUEST']._serialized_start=3489 _globals['_CHECKTRANSACTIONREQUEST']._serialized_end=3555 _globals['_CHECKTRANSACTIONRESPONSE']._serialized_start=3557 _globals['_CHECKTRANSACTIONRESPONSE']._serialized_end=3647 _globals['_TRANSACTION']._serialized_start=3947 _globals['_TRANSACTION']._serialized_end=4929 # @@protoc_insertion_point(module_scope) ================================================ FILE: www/grpc/gen/python/transaction_pb2.pyi ================================================ from google.protobuf.internal import containers as _containers from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from collections.abc import Iterable as _Iterable, Mapping as _Mapping from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union DESCRIPTOR: _descriptor.FileDescriptor class PayloadType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () PAYLOAD_TYPE_UNSPECIFIED: _ClassVar[PayloadType] PAYLOAD_TYPE_TRANSFER: _ClassVar[PayloadType] PAYLOAD_TYPE_BOND: _ClassVar[PayloadType] PAYLOAD_TYPE_SORTITION: _ClassVar[PayloadType] PAYLOAD_TYPE_UNBOND: _ClassVar[PayloadType] PAYLOAD_TYPE_WITHDRAW: _ClassVar[PayloadType] PAYLOAD_TYPE_BATCH_TRANSFER: _ClassVar[PayloadType] class TransactionVerbosity(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () TRANSACTION_VERBOSITY_DATA: _ClassVar[TransactionVerbosity] TRANSACTION_VERBOSITY_INFO: _ClassVar[TransactionVerbosity] PAYLOAD_TYPE_UNSPECIFIED: PayloadType PAYLOAD_TYPE_TRANSFER: PayloadType PAYLOAD_TYPE_BOND: PayloadType PAYLOAD_TYPE_SORTITION: PayloadType PAYLOAD_TYPE_UNBOND: PayloadType PAYLOAD_TYPE_WITHDRAW: PayloadType PAYLOAD_TYPE_BATCH_TRANSFER: PayloadType TRANSACTION_VERBOSITY_DATA: TransactionVerbosity TRANSACTION_VERBOSITY_INFO: TransactionVerbosity class GetTransactionRequest(_message.Message): __slots__ = () ID_FIELD_NUMBER: _ClassVar[int] VERBOSITY_FIELD_NUMBER: _ClassVar[int] id: str verbosity: TransactionVerbosity def __init__(self, id: _Optional[str] = ..., verbosity: _Optional[_Union[TransactionVerbosity, str]] = ...) -> None: ... class GetTransactionResponse(_message.Message): __slots__ = () BLOCK_HEIGHT_FIELD_NUMBER: _ClassVar[int] BLOCK_TIME_FIELD_NUMBER: _ClassVar[int] TRANSACTION_FIELD_NUMBER: _ClassVar[int] block_height: int block_time: int transaction: TransactionInfo def __init__(self, block_height: _Optional[int] = ..., block_time: _Optional[int] = ..., transaction: _Optional[_Union[TransactionInfo, _Mapping]] = ...) -> None: ... class CalculateFeeRequest(_message.Message): __slots__ = () AMOUNT_FIELD_NUMBER: _ClassVar[int] PAYLOAD_TYPE_FIELD_NUMBER: _ClassVar[int] FIXED_AMOUNT_FIELD_NUMBER: _ClassVar[int] amount: int payload_type: PayloadType fixed_amount: bool def __init__(self, amount: _Optional[int] = ..., payload_type: _Optional[_Union[PayloadType, str]] = ..., fixed_amount: _Optional[bool] = ...) -> None: ... class CalculateFeeResponse(_message.Message): __slots__ = () AMOUNT_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] amount: int fee: int def __init__(self, amount: _Optional[int] = ..., fee: _Optional[int] = ...) -> None: ... class BroadcastTransactionRequest(_message.Message): __slots__ = () SIGNED_RAW_TRANSACTION_FIELD_NUMBER: _ClassVar[int] signed_raw_transaction: str def __init__(self, signed_raw_transaction: _Optional[str] = ...) -> None: ... class BroadcastTransactionResponse(_message.Message): __slots__ = () ID_FIELD_NUMBER: _ClassVar[int] id: str def __init__(self, id: _Optional[str] = ...) -> None: ... class GetRawTransferTransactionRequest(_message.Message): __slots__ = () LOCK_TIME_FIELD_NUMBER: _ClassVar[int] SENDER_FIELD_NUMBER: _ClassVar[int] RECEIVER_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] lock_time: int sender: str receiver: str amount: int fee: int memo: str def __init__(self, lock_time: _Optional[int] = ..., sender: _Optional[str] = ..., receiver: _Optional[str] = ..., amount: _Optional[int] = ..., fee: _Optional[int] = ..., memo: _Optional[str] = ...) -> None: ... class GetRawBondTransactionRequest(_message.Message): __slots__ = () LOCK_TIME_FIELD_NUMBER: _ClassVar[int] SENDER_FIELD_NUMBER: _ClassVar[int] RECEIVER_FIELD_NUMBER: _ClassVar[int] STAKE_FIELD_NUMBER: _ClassVar[int] PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] DELEGATE_OWNER_FIELD_NUMBER: _ClassVar[int] DELEGATE_SHARE_FIELD_NUMBER: _ClassVar[int] DELEGATE_EXPIRY_FIELD_NUMBER: _ClassVar[int] lock_time: int sender: str receiver: str stake: int public_key: str fee: int memo: str delegate_owner: str delegate_share: int delegate_expiry: int def __init__(self, lock_time: _Optional[int] = ..., sender: _Optional[str] = ..., receiver: _Optional[str] = ..., stake: _Optional[int] = ..., public_key: _Optional[str] = ..., fee: _Optional[int] = ..., memo: _Optional[str] = ..., delegate_owner: _Optional[str] = ..., delegate_share: _Optional[int] = ..., delegate_expiry: _Optional[int] = ...) -> None: ... class GetRawUnbondTransactionRequest(_message.Message): __slots__ = () LOCK_TIME_FIELD_NUMBER: _ClassVar[int] VALIDATOR_ADDRESS_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] DELEGATE_OWNER_FIELD_NUMBER: _ClassVar[int] lock_time: int validator_address: str memo: str delegate_owner: str def __init__(self, lock_time: _Optional[int] = ..., validator_address: _Optional[str] = ..., memo: _Optional[str] = ..., delegate_owner: _Optional[str] = ...) -> None: ... class GetRawWithdrawTransactionRequest(_message.Message): __slots__ = () LOCK_TIME_FIELD_NUMBER: _ClassVar[int] VALIDATOR_ADDRESS_FIELD_NUMBER: _ClassVar[int] ACCOUNT_ADDRESS_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] lock_time: int validator_address: str account_address: str amount: int fee: int memo: str def __init__(self, lock_time: _Optional[int] = ..., validator_address: _Optional[str] = ..., account_address: _Optional[str] = ..., amount: _Optional[int] = ..., fee: _Optional[int] = ..., memo: _Optional[str] = ...) -> None: ... class GetRawBatchTransferTransactionRequest(_message.Message): __slots__ = () LOCK_TIME_FIELD_NUMBER: _ClassVar[int] SENDER_FIELD_NUMBER: _ClassVar[int] RECIPIENTS_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] lock_time: int sender: str recipients: _containers.RepeatedCompositeFieldContainer[Recipient] fee: int memo: str def __init__(self, lock_time: _Optional[int] = ..., sender: _Optional[str] = ..., recipients: _Optional[_Iterable[_Union[Recipient, _Mapping]]] = ..., fee: _Optional[int] = ..., memo: _Optional[str] = ...) -> None: ... class GetRawTransactionResponse(_message.Message): __slots__ = () RAW_TRANSACTION_FIELD_NUMBER: _ClassVar[int] ID_FIELD_NUMBER: _ClassVar[int] raw_transaction: str id: str def __init__(self, raw_transaction: _Optional[str] = ..., id: _Optional[str] = ...) -> None: ... class PayloadTransfer(_message.Message): __slots__ = () SENDER_FIELD_NUMBER: _ClassVar[int] RECEIVER_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] sender: str receiver: str amount: int def __init__(self, sender: _Optional[str] = ..., receiver: _Optional[str] = ..., amount: _Optional[int] = ...) -> None: ... class PayloadBond(_message.Message): __slots__ = () SENDER_FIELD_NUMBER: _ClassVar[int] RECEIVER_FIELD_NUMBER: _ClassVar[int] STAKE_FIELD_NUMBER: _ClassVar[int] PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] IS_DELEGATED_FIELD_NUMBER: _ClassVar[int] DELEGATE_OWNER_FIELD_NUMBER: _ClassVar[int] DELEGATE_SHARE_FIELD_NUMBER: _ClassVar[int] DELEGATE_EXPIRY_FIELD_NUMBER: _ClassVar[int] sender: str receiver: str stake: int public_key: str is_delegated: bool delegate_owner: str delegate_share: int delegate_expiry: int def __init__(self, sender: _Optional[str] = ..., receiver: _Optional[str] = ..., stake: _Optional[int] = ..., public_key: _Optional[str] = ..., is_delegated: _Optional[bool] = ..., delegate_owner: _Optional[str] = ..., delegate_share: _Optional[int] = ..., delegate_expiry: _Optional[int] = ...) -> None: ... class PayloadSortition(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] PROOF_FIELD_NUMBER: _ClassVar[int] address: str proof: str def __init__(self, address: _Optional[str] = ..., proof: _Optional[str] = ...) -> None: ... class PayloadUnbond(_message.Message): __slots__ = () VALIDATOR_FIELD_NUMBER: _ClassVar[int] DELEGATE_OWNER_FIELD_NUMBER: _ClassVar[int] validator: str delegate_owner: str def __init__(self, validator: _Optional[str] = ..., delegate_owner: _Optional[str] = ...) -> None: ... class PayloadWithdraw(_message.Message): __slots__ = () VALIDATOR_ADDRESS_FIELD_NUMBER: _ClassVar[int] ACCOUNT_ADDRESS_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] validator_address: str account_address: str amount: int def __init__(self, validator_address: _Optional[str] = ..., account_address: _Optional[str] = ..., amount: _Optional[int] = ...) -> None: ... class PayloadBatchTransfer(_message.Message): __slots__ = () SENDER_FIELD_NUMBER: _ClassVar[int] RECIPIENTS_FIELD_NUMBER: _ClassVar[int] sender: str recipients: _containers.RepeatedCompositeFieldContainer[Recipient] def __init__(self, sender: _Optional[str] = ..., recipients: _Optional[_Iterable[_Union[Recipient, _Mapping]]] = ...) -> None: ... class Recipient(_message.Message): __slots__ = () RECEIVER_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] receiver: str amount: int def __init__(self, receiver: _Optional[str] = ..., amount: _Optional[int] = ...) -> None: ... class TransactionInfo(_message.Message): __slots__ = () ID_FIELD_NUMBER: _ClassVar[int] DATA_FIELD_NUMBER: _ClassVar[int] VERSION_FIELD_NUMBER: _ClassVar[int] LOCK_TIME_FIELD_NUMBER: _ClassVar[int] VALUE_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] PAYLOAD_TYPE_FIELD_NUMBER: _ClassVar[int] TRANSFER_FIELD_NUMBER: _ClassVar[int] BOND_FIELD_NUMBER: _ClassVar[int] SORTITION_FIELD_NUMBER: _ClassVar[int] UNBOND_FIELD_NUMBER: _ClassVar[int] WITHDRAW_FIELD_NUMBER: _ClassVar[int] BATCH_TRANSFER_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] SIGNATURE_FIELD_NUMBER: _ClassVar[int] BLOCK_HEIGHT_FIELD_NUMBER: _ClassVar[int] CONFIRMED_FIELD_NUMBER: _ClassVar[int] CONFIRMATIONS_FIELD_NUMBER: _ClassVar[int] id: str data: str version: int lock_time: int value: int fee: int payload_type: PayloadType transfer: PayloadTransfer bond: PayloadBond sortition: PayloadSortition unbond: PayloadUnbond withdraw: PayloadWithdraw batch_transfer: PayloadBatchTransfer memo: str public_key: str signature: str block_height: int confirmed: bool confirmations: int def __init__(self, id: _Optional[str] = ..., data: _Optional[str] = ..., version: _Optional[int] = ..., lock_time: _Optional[int] = ..., value: _Optional[int] = ..., fee: _Optional[int] = ..., payload_type: _Optional[_Union[PayloadType, str]] = ..., transfer: _Optional[_Union[PayloadTransfer, _Mapping]] = ..., bond: _Optional[_Union[PayloadBond, _Mapping]] = ..., sortition: _Optional[_Union[PayloadSortition, _Mapping]] = ..., unbond: _Optional[_Union[PayloadUnbond, _Mapping]] = ..., withdraw: _Optional[_Union[PayloadWithdraw, _Mapping]] = ..., batch_transfer: _Optional[_Union[PayloadBatchTransfer, _Mapping]] = ..., memo: _Optional[str] = ..., public_key: _Optional[str] = ..., signature: _Optional[str] = ..., block_height: _Optional[int] = ..., confirmed: _Optional[bool] = ..., confirmations: _Optional[int] = ...) -> None: ... class DecodeRawTransactionRequest(_message.Message): __slots__ = () RAW_TRANSACTION_FIELD_NUMBER: _ClassVar[int] raw_transaction: str def __init__(self, raw_transaction: _Optional[str] = ...) -> None: ... class DecodeRawTransactionResponse(_message.Message): __slots__ = () TRANSACTION_FIELD_NUMBER: _ClassVar[int] transaction: TransactionInfo def __init__(self, transaction: _Optional[_Union[TransactionInfo, _Mapping]] = ...) -> None: ... class CheckTransactionRequest(_message.Message): __slots__ = () RAW_TRANSACTION_FIELD_NUMBER: _ClassVar[int] raw_transaction: str def __init__(self, raw_transaction: _Optional[str] = ...) -> None: ... class CheckTransactionResponse(_message.Message): __slots__ = () IS_VALID_FIELD_NUMBER: _ClassVar[int] ERROR_MESSAGE_FIELD_NUMBER: _ClassVar[int] is_valid: bool error_message: str def __init__(self, is_valid: _Optional[bool] = ..., error_message: _Optional[str] = ...) -> None: ... ================================================ FILE: www/grpc/gen/python/transaction_pb2_grpc.py ================================================ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import transaction_pb2 as transaction__pb2 class TransactionStub(object): """Transaction service defines various RPC methods for interacting with transactions. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetTransaction = channel.unary_unary( '/pactus.Transaction/GetTransaction', request_serializer=transaction__pb2.GetTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.GetTransactionResponse.FromString, _registered_method=True) self.CalculateFee = channel.unary_unary( '/pactus.Transaction/CalculateFee', request_serializer=transaction__pb2.CalculateFeeRequest.SerializeToString, response_deserializer=transaction__pb2.CalculateFeeResponse.FromString, _registered_method=True) self.BroadcastTransaction = channel.unary_unary( '/pactus.Transaction/BroadcastTransaction', request_serializer=transaction__pb2.BroadcastTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.BroadcastTransactionResponse.FromString, _registered_method=True) self.GetRawTransferTransaction = channel.unary_unary( '/pactus.Transaction/GetRawTransferTransaction', request_serializer=transaction__pb2.GetRawTransferTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, _registered_method=True) self.GetRawBondTransaction = channel.unary_unary( '/pactus.Transaction/GetRawBondTransaction', request_serializer=transaction__pb2.GetRawBondTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, _registered_method=True) self.GetRawUnbondTransaction = channel.unary_unary( '/pactus.Transaction/GetRawUnbondTransaction', request_serializer=transaction__pb2.GetRawUnbondTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, _registered_method=True) self.GetRawWithdrawTransaction = channel.unary_unary( '/pactus.Transaction/GetRawWithdrawTransaction', request_serializer=transaction__pb2.GetRawWithdrawTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, _registered_method=True) self.GetRawBatchTransferTransaction = channel.unary_unary( '/pactus.Transaction/GetRawBatchTransferTransaction', request_serializer=transaction__pb2.GetRawBatchTransferTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, _registered_method=True) self.DecodeRawTransaction = channel.unary_unary( '/pactus.Transaction/DecodeRawTransaction', request_serializer=transaction__pb2.DecodeRawTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.DecodeRawTransactionResponse.FromString, _registered_method=True) self.CheckTransaction = channel.unary_unary( '/pactus.Transaction/CheckTransaction', request_serializer=transaction__pb2.CheckTransactionRequest.SerializeToString, response_deserializer=transaction__pb2.CheckTransactionResponse.FromString, _registered_method=True) class TransactionServicer(object): """Transaction service defines various RPC methods for interacting with transactions. """ def GetTransaction(self, request, context): """GetTransaction retrieves transaction details based on the provided request parameters. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CalculateFee(self, request, context): """CalculateFee calculates the transaction fee based on the specified amount and payload type. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def BroadcastTransaction(self, request, context): """BroadcastTransaction broadcasts a signed transaction to the network. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetRawTransferTransaction(self, request, context): """GetRawTransferTransaction retrieves raw details of a transfer transaction. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetRawBondTransaction(self, request, context): """GetRawBondTransaction retrieves raw details of a bond transaction. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetRawUnbondTransaction(self, request, context): """GetRawUnbondTransaction retrieves raw details of an unbond transaction. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetRawWithdrawTransaction(self, request, context): """GetRawWithdrawTransaction retrieves raw details of a withdraw transaction. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetRawBatchTransferTransaction(self, request, context): """GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DecodeRawTransaction(self, request, context): """DecodeRawTransaction accepts raw transaction and returns decoded transaction. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CheckTransaction(self, request, context): """CheckTransaction checks if the transaction is valid and can be included in the blockchain. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_TransactionServicer_to_server(servicer, server): rpc_method_handlers = { 'GetTransaction': grpc.unary_unary_rpc_method_handler( servicer.GetTransaction, request_deserializer=transaction__pb2.GetTransactionRequest.FromString, response_serializer=transaction__pb2.GetTransactionResponse.SerializeToString, ), 'CalculateFee': grpc.unary_unary_rpc_method_handler( servicer.CalculateFee, request_deserializer=transaction__pb2.CalculateFeeRequest.FromString, response_serializer=transaction__pb2.CalculateFeeResponse.SerializeToString, ), 'BroadcastTransaction': grpc.unary_unary_rpc_method_handler( servicer.BroadcastTransaction, request_deserializer=transaction__pb2.BroadcastTransactionRequest.FromString, response_serializer=transaction__pb2.BroadcastTransactionResponse.SerializeToString, ), 'GetRawTransferTransaction': grpc.unary_unary_rpc_method_handler( servicer.GetRawTransferTransaction, request_deserializer=transaction__pb2.GetRawTransferTransactionRequest.FromString, response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, ), 'GetRawBondTransaction': grpc.unary_unary_rpc_method_handler( servicer.GetRawBondTransaction, request_deserializer=transaction__pb2.GetRawBondTransactionRequest.FromString, response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, ), 'GetRawUnbondTransaction': grpc.unary_unary_rpc_method_handler( servicer.GetRawUnbondTransaction, request_deserializer=transaction__pb2.GetRawUnbondTransactionRequest.FromString, response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, ), 'GetRawWithdrawTransaction': grpc.unary_unary_rpc_method_handler( servicer.GetRawWithdrawTransaction, request_deserializer=transaction__pb2.GetRawWithdrawTransactionRequest.FromString, response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, ), 'GetRawBatchTransferTransaction': grpc.unary_unary_rpc_method_handler( servicer.GetRawBatchTransferTransaction, request_deserializer=transaction__pb2.GetRawBatchTransferTransactionRequest.FromString, response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, ), 'DecodeRawTransaction': grpc.unary_unary_rpc_method_handler( servicer.DecodeRawTransaction, request_deserializer=transaction__pb2.DecodeRawTransactionRequest.FromString, response_serializer=transaction__pb2.DecodeRawTransactionResponse.SerializeToString, ), 'CheckTransaction': grpc.unary_unary_rpc_method_handler( servicer.CheckTransaction, request_deserializer=transaction__pb2.CheckTransactionRequest.FromString, response_serializer=transaction__pb2.CheckTransactionResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'pactus.Transaction', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) server.add_registered_method_handlers('pactus.Transaction', rpc_method_handlers) # This class is part of an EXPERIMENTAL API. class Transaction(object): """Transaction service defines various RPC methods for interacting with transactions. """ @staticmethod def GetTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/GetTransaction', transaction__pb2.GetTransactionRequest.SerializeToString, transaction__pb2.GetTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def CalculateFee(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/CalculateFee', transaction__pb2.CalculateFeeRequest.SerializeToString, transaction__pb2.CalculateFeeResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def BroadcastTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/BroadcastTransaction', transaction__pb2.BroadcastTransactionRequest.SerializeToString, transaction__pb2.BroadcastTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetRawTransferTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/GetRawTransferTransaction', transaction__pb2.GetRawTransferTransactionRequest.SerializeToString, transaction__pb2.GetRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetRawBondTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/GetRawBondTransaction', transaction__pb2.GetRawBondTransactionRequest.SerializeToString, transaction__pb2.GetRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetRawUnbondTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/GetRawUnbondTransaction', transaction__pb2.GetRawUnbondTransactionRequest.SerializeToString, transaction__pb2.GetRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetRawWithdrawTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/GetRawWithdrawTransaction', transaction__pb2.GetRawWithdrawTransactionRequest.SerializeToString, transaction__pb2.GetRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetRawBatchTransferTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/GetRawBatchTransferTransaction', transaction__pb2.GetRawBatchTransferTransactionRequest.SerializeToString, transaction__pb2.GetRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def DecodeRawTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/DecodeRawTransaction', transaction__pb2.DecodeRawTransactionRequest.SerializeToString, transaction__pb2.DecodeRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def CheckTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Transaction/CheckTransaction', transaction__pb2.CheckTransactionRequest.SerializeToString, transaction__pb2.CheckTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) ================================================ FILE: www/grpc/gen/python/utils_pb2.py ================================================ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: utils.proto # Protobuf Python Version: 6.33.2 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import runtime_version as _runtime_version from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 6, 33, 2, '', 'utils.proto' ) # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0butils.proto\x12\x06pactus\"]\n SignMessageWithPrivateKeyRequest\x12\x1f\n\x0bprivate_key\x18\x01 \x01(\tR\nprivateKey\x12\x18\n\x07message\x18\x02 \x01(\tR\x07message\"A\n!SignMessageWithPrivateKeyResponse\x12\x1c\n\tsignature\x18\x01 \x01(\tR\tsignature\"m\n\x14VerifyMessageRequest\x12\x18\n\x07message\x18\x01 \x01(\tR\x07message\x12\x1c\n\tsignature\x18\x02 \x01(\tR\tsignature\x12\x1d\n\npublic_key\x18\x03 \x01(\tR\tpublicKey\"2\n\x15VerifyMessageResponse\x12\x19\n\x08is_valid\x18\x01 \x01(\x08R\x07isValid\">\n\x1bPublicKeyAggregationRequest\x12\x1f\n\x0bpublic_keys\x18\x01 \x03(\tR\npublicKeys\"W\n\x1cPublicKeyAggregationResponse\x12\x1d\n\npublic_key\x18\x01 \x01(\tR\tpublicKey\x12\x18\n\x07\x61\x64\x64ress\x18\x02 \x01(\tR\x07\x61\x64\x64ress\"=\n\x1bSignatureAggregationRequest\x12\x1e\n\nsignatures\x18\x01 \x03(\tR\nsignatures\"<\n\x1cSignatureAggregationResponse\x12\x1c\n\tsignature\x18\x01 \x01(\tR\tsignature2\x8d\x03\n\x05Utils\x12p\n\x19SignMessageWithPrivateKey\x12(.pactus.SignMessageWithPrivateKeyRequest\x1a).pactus.SignMessageWithPrivateKeyResponse\x12L\n\rVerifyMessage\x12\x1c.pactus.VerifyMessageRequest\x1a\x1d.pactus.VerifyMessageResponse\x12\x61\n\x14PublicKeyAggregation\x12#.pactus.PublicKeyAggregationRequest\x1a$.pactus.PublicKeyAggregationResponse\x12\x61\n\x14SignatureAggregation\x12#.pactus.SignatureAggregationRequest\x1a$.pactus.SignatureAggregationResponseB:\n\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'utils_pb2', _globals) if not _descriptor._USE_C_DESCRIPTORS: _globals['DESCRIPTOR']._loaded_options = None _globals['DESCRIPTOR']._serialized_options = b'\n\006pactusZ0github.com/pactus-project/pactus/www/grpc/pactus' _globals['_SIGNMESSAGEWITHPRIVATEKEYREQUEST']._serialized_start=23 _globals['_SIGNMESSAGEWITHPRIVATEKEYREQUEST']._serialized_end=116 _globals['_SIGNMESSAGEWITHPRIVATEKEYRESPONSE']._serialized_start=118 _globals['_SIGNMESSAGEWITHPRIVATEKEYRESPONSE']._serialized_end=183 _globals['_VERIFYMESSAGEREQUEST']._serialized_start=185 _globals['_VERIFYMESSAGEREQUEST']._serialized_end=294 _globals['_VERIFYMESSAGERESPONSE']._serialized_start=296 _globals['_VERIFYMESSAGERESPONSE']._serialized_end=346 _globals['_PUBLICKEYAGGREGATIONREQUEST']._serialized_start=348 _globals['_PUBLICKEYAGGREGATIONREQUEST']._serialized_end=410 _globals['_PUBLICKEYAGGREGATIONRESPONSE']._serialized_start=412 _globals['_PUBLICKEYAGGREGATIONRESPONSE']._serialized_end=499 _globals['_SIGNATUREAGGREGATIONREQUEST']._serialized_start=501 _globals['_SIGNATUREAGGREGATIONREQUEST']._serialized_end=562 _globals['_SIGNATUREAGGREGATIONRESPONSE']._serialized_start=564 _globals['_SIGNATUREAGGREGATIONRESPONSE']._serialized_end=624 _globals['_UTILS']._serialized_start=627 _globals['_UTILS']._serialized_end=1024 # @@protoc_insertion_point(module_scope) ================================================ FILE: www/grpc/gen/python/utils_pb2.pyi ================================================ from google.protobuf.internal import containers as _containers from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from collections.abc import Iterable as _Iterable from typing import ClassVar as _ClassVar, Optional as _Optional DESCRIPTOR: _descriptor.FileDescriptor class SignMessageWithPrivateKeyRequest(_message.Message): __slots__ = () PRIVATE_KEY_FIELD_NUMBER: _ClassVar[int] MESSAGE_FIELD_NUMBER: _ClassVar[int] private_key: str message: str def __init__(self, private_key: _Optional[str] = ..., message: _Optional[str] = ...) -> None: ... class SignMessageWithPrivateKeyResponse(_message.Message): __slots__ = () SIGNATURE_FIELD_NUMBER: _ClassVar[int] signature: str def __init__(self, signature: _Optional[str] = ...) -> None: ... class VerifyMessageRequest(_message.Message): __slots__ = () MESSAGE_FIELD_NUMBER: _ClassVar[int] SIGNATURE_FIELD_NUMBER: _ClassVar[int] PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] message: str signature: str public_key: str def __init__(self, message: _Optional[str] = ..., signature: _Optional[str] = ..., public_key: _Optional[str] = ...) -> None: ... class VerifyMessageResponse(_message.Message): __slots__ = () IS_VALID_FIELD_NUMBER: _ClassVar[int] is_valid: bool def __init__(self, is_valid: _Optional[bool] = ...) -> None: ... class PublicKeyAggregationRequest(_message.Message): __slots__ = () PUBLIC_KEYS_FIELD_NUMBER: _ClassVar[int] public_keys: _containers.RepeatedScalarFieldContainer[str] def __init__(self, public_keys: _Optional[_Iterable[str]] = ...) -> None: ... class PublicKeyAggregationResponse(_message.Message): __slots__ = () PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] public_key: str address: str def __init__(self, public_key: _Optional[str] = ..., address: _Optional[str] = ...) -> None: ... class SignatureAggregationRequest(_message.Message): __slots__ = () SIGNATURES_FIELD_NUMBER: _ClassVar[int] signatures: _containers.RepeatedScalarFieldContainer[str] def __init__(self, signatures: _Optional[_Iterable[str]] = ...) -> None: ... class SignatureAggregationResponse(_message.Message): __slots__ = () SIGNATURE_FIELD_NUMBER: _ClassVar[int] signature: str def __init__(self, signature: _Optional[str] = ...) -> None: ... ================================================ FILE: www/grpc/gen/python/utils_pb2_grpc.py ================================================ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import utils_pb2 as utils__pb2 class UtilsStub(object): """Utils service defines RPC methods for utility functions such as message signing, verification, and other cryptographic operations. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SignMessageWithPrivateKey = channel.unary_unary( '/pactus.Utils/SignMessageWithPrivateKey', request_serializer=utils__pb2.SignMessageWithPrivateKeyRequest.SerializeToString, response_deserializer=utils__pb2.SignMessageWithPrivateKeyResponse.FromString, _registered_method=True) self.VerifyMessage = channel.unary_unary( '/pactus.Utils/VerifyMessage', request_serializer=utils__pb2.VerifyMessageRequest.SerializeToString, response_deserializer=utils__pb2.VerifyMessageResponse.FromString, _registered_method=True) self.PublicKeyAggregation = channel.unary_unary( '/pactus.Utils/PublicKeyAggregation', request_serializer=utils__pb2.PublicKeyAggregationRequest.SerializeToString, response_deserializer=utils__pb2.PublicKeyAggregationResponse.FromString, _registered_method=True) self.SignatureAggregation = channel.unary_unary( '/pactus.Utils/SignatureAggregation', request_serializer=utils__pb2.SignatureAggregationRequest.SerializeToString, response_deserializer=utils__pb2.SignatureAggregationResponse.FromString, _registered_method=True) class UtilsServicer(object): """Utils service defines RPC methods for utility functions such as message signing, verification, and other cryptographic operations. """ def SignMessageWithPrivateKey(self, request, context): """SignMessageWithPrivateKey signs a message with the provided private key. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def VerifyMessage(self, request, context): """VerifyMessage verifies a signature against the public key and message. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def PublicKeyAggregation(self, request, context): """PublicKeyAggregation aggregates multiple BLS public keys into a single key. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def SignatureAggregation(self, request, context): """SignatureAggregation aggregates multiple BLS signatures into a single signature. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_UtilsServicer_to_server(servicer, server): rpc_method_handlers = { 'SignMessageWithPrivateKey': grpc.unary_unary_rpc_method_handler( servicer.SignMessageWithPrivateKey, request_deserializer=utils__pb2.SignMessageWithPrivateKeyRequest.FromString, response_serializer=utils__pb2.SignMessageWithPrivateKeyResponse.SerializeToString, ), 'VerifyMessage': grpc.unary_unary_rpc_method_handler( servicer.VerifyMessage, request_deserializer=utils__pb2.VerifyMessageRequest.FromString, response_serializer=utils__pb2.VerifyMessageResponse.SerializeToString, ), 'PublicKeyAggregation': grpc.unary_unary_rpc_method_handler( servicer.PublicKeyAggregation, request_deserializer=utils__pb2.PublicKeyAggregationRequest.FromString, response_serializer=utils__pb2.PublicKeyAggregationResponse.SerializeToString, ), 'SignatureAggregation': grpc.unary_unary_rpc_method_handler( servicer.SignatureAggregation, request_deserializer=utils__pb2.SignatureAggregationRequest.FromString, response_serializer=utils__pb2.SignatureAggregationResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'pactus.Utils', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) server.add_registered_method_handlers('pactus.Utils', rpc_method_handlers) # This class is part of an EXPERIMENTAL API. class Utils(object): """Utils service defines RPC methods for utility functions such as message signing, verification, and other cryptographic operations. """ @staticmethod def SignMessageWithPrivateKey(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Utils/SignMessageWithPrivateKey', utils__pb2.SignMessageWithPrivateKeyRequest.SerializeToString, utils__pb2.SignMessageWithPrivateKeyResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def VerifyMessage(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Utils/VerifyMessage', utils__pb2.VerifyMessageRequest.SerializeToString, utils__pb2.VerifyMessageResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def PublicKeyAggregation(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Utils/PublicKeyAggregation', utils__pb2.PublicKeyAggregationRequest.SerializeToString, utils__pb2.PublicKeyAggregationResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def SignatureAggregation(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Utils/SignatureAggregation', utils__pb2.SignatureAggregationRequest.SerializeToString, utils__pb2.SignatureAggregationResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) ================================================ FILE: www/grpc/gen/python/wallet_pb2.py ================================================ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: wallet.proto # Protobuf Python Version: 6.33.2 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import runtime_version as _runtime_version from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 6, 33, 2, '', 'wallet.proto' ) # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() import transaction_pb2 as transaction__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cwallet.proto\x12\x06pactus\x1a\x11transaction.proto\"p\n\x0b\x41\x64\x64ressInfo\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\x12\x1d\n\npublic_key\x18\x02 \x01(\tR\tpublicKey\x12\x14\n\x05label\x18\x03 \x01(\tR\x05label\x12\x12\n\x04path\x18\x04 \x01(\tR\x04path\"\xa1\x01\n\x14GetNewAddressRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x36\n\x0c\x61\x64\x64ress_type\x18\x02 \x01(\x0e\x32\x13.pactus.AddressTypeR\x0b\x61\x64\x64ressType\x12\x14\n\x05label\x18\x03 \x01(\tR\x05label\x12\x1a\n\x08password\x18\x04 \x01(\tR\x08password\"a\n\x15GetNewAddressResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\'\n\x04\x61\x64\x64r\x18\x02 \x01(\x0b\x32\x13.pactus.AddressInfoR\x04\x61\x64\x64r\"o\n\x14RestoreWalletRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08mnemonic\x18\x02 \x01(\tR\x08mnemonic\x12\x1a\n\x08password\x18\x03 \x01(\tR\x08password\"8\n\x15RestoreWalletResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"R\n\x13\x43reateWalletRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08password\x18\x02 \x01(\tR\x08password\"S\n\x14\x43reateWalletResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08mnemonic\x18\x02 \x01(\tR\x08mnemonic\"4\n\x11LoadWalletRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"5\n\x12LoadWalletResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"6\n\x13UnloadWalletRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"7\n\x14UnloadWalletResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\";\n\x1aGetValidatorAddressRequest\x12\x1d\n\npublic_key\x18\x01 \x01(\tR\tpublicKey\"7\n\x1bGetValidatorAddressResponse\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"\x81\x01\n\x19SignRawTransactionRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\'\n\x0fraw_transaction\x18\x02 \x01(\tR\x0erawTransaction\x12\x1a\n\x08password\x18\x03 \x01(\tR\x08password\"y\n\x1aSignRawTransactionResponse\x12%\n\x0etransaction_id\x18\x01 \x01(\tR\rtransactionId\x12\x34\n\x16signed_raw_transaction\x18\x02 \x01(\tR\x14signedRawTransaction\"9\n\x16GetTotalBalanceRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"_\n\x17GetTotalBalanceResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12#\n\rtotal_balance\x18\x02 \x01(\x03R\x0ctotalBalance\"\x85\x01\n\x12SignMessageRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08password\x18\x02 \x01(\tR\x08password\x12\x18\n\x07\x61\x64\x64ress\x18\x03 \x01(\tR\x07\x61\x64\x64ress\x12\x18\n\x07message\x18\x04 \x01(\tR\x07message\"3\n\x13SignMessageResponse\x12\x1c\n\tsignature\x18\x01 \x01(\tR\tsignature\"7\n\x14GetTotalStakeRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"Y\n\x15GetTotalStakeResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1f\n\x0btotal_stake\x18\x02 \x01(\x03R\ntotalStake\"R\n\x15GetAddressInfoRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x18\n\x07\x61\x64\x64ress\x18\x02 \x01(\tR\x07\x61\x64\x64ress\"b\n\x16GetAddressInfoResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\'\n\x04\x61\x64\x64r\x18\x02 \x01(\x0b\x32\x13.pactus.AddressInfoR\x04\x61\x64\x64r\"\x85\x01\n\x16SetAddressLabelRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08password\x18\x02 \x01(\tR\x08password\x12\x18\n\x07\x61\x64\x64ress\x18\x03 \x01(\tR\x07\x61\x64\x64ress\x12\x14\n\x05label\x18\x04 \x01(\tR\x05label\"j\n\x17SetAddressLabelResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x18\n\x07\x61\x64\x64ress\x18\x02 \x01(\tR\x07\x61\x64\x64ress\x12\x14\n\x05label\x18\x03 \x01(\tR\x05label\"\x14\n\x12ListWalletsRequest\"/\n\x13ListWalletsResponse\x12\x18\n\x07wallets\x18\x01 \x03(\tR\x07wallets\"7\n\x14GetWalletInfoRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"\x8a\x02\n\x15GetWalletInfoResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x18\n\x07version\x18\x02 \x01(\x05R\x07version\x12\x18\n\x07network\x18\x03 \x01(\tR\x07network\x12\x1c\n\tencrypted\x18\x04 \x01(\x08R\tencrypted\x12\x12\n\x04uuid\x18\x05 \x01(\tR\x04uuid\x12\x1d\n\ncreated_at\x18\x06 \x01(\x03R\tcreatedAt\x12\x1f\n\x0b\x64\x65\x66\x61ult_fee\x18\x07 \x01(\x03R\ndefaultFee\x12\x16\n\x06\x64river\x18\x08 \x01(\tR\x06\x64river\x12\x12\n\x04path\x18\t \x01(\tR\x04path\"q\n\x14ListAddressesRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x38\n\raddress_types\x18\x02 \x03(\x0e\x32\x13.pactus.AddressTypeR\x0c\x61\x64\x64ressTypes\"c\n\x15ListAddressesResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12)\n\x05\x61\x64\x64rs\x18\x02 \x03(\x0b\x32\x13.pactus.AddressInfoR\x05\x61\x64\x64rs\"~\n\x15UpdatePasswordRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12!\n\x0cold_password\x18\x02 \x01(\tR\x0boldPassword\x12!\n\x0cnew_password\x18\x03 \x01(\tR\x0bnewPassword\"9\n\x16UpdatePasswordResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"\xdb\x03\n\x15WalletTransactionInfo\x12\x0e\n\x02no\x18\x01 \x01(\x03R\x02no\x12\x13\n\x05tx_id\x18\x02 \x01(\tR\x04txId\x12\x16\n\x06sender\x18\x03 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x04 \x01(\tR\x08receiver\x12\x31\n\tdirection\x18\x05 \x01(\x0e\x32\x13.pactus.TxDirectionR\tdirection\x12\x16\n\x06\x61mount\x18\x06 \x01(\x03R\x06\x61mount\x12\x10\n\x03\x66\x65\x65\x18\x07 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x08 \x01(\tR\x04memo\x12\x31\n\x06status\x18\t \x01(\x0e\x32\x19.pactus.TransactionStatusR\x06status\x12!\n\x0c\x62lock_height\x18\n \x01(\rR\x0b\x62lockHeight\x12\x36\n\x0cpayload_type\x18\x0b \x01(\x0e\x32\x13.pactus.PayloadTypeR\x0bpayloadType\x12\x12\n\x04\x64\x61ta\x18\x0c \x01(\x0cR\x04\x64\x61ta\x12\x18\n\x07\x63omment\x18\r \x01(\tR\x07\x63omment\x12\x1d\n\ncreated_at\x18\x0e \x01(\x03R\tcreatedAt\x12\x1d\n\nupdated_at\x18\x0f \x01(\x03R\tupdatedAt\"\xb1\x01\n\x17ListTransactionsRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x18\n\x07\x61\x64\x64ress\x18\x02 \x01(\tR\x07\x61\x64\x64ress\x12\x31\n\tdirection\x18\x03 \x01(\x0e\x32\x13.pactus.TxDirectionR\tdirection\x12\x14\n\x05\x63ount\x18\x04 \x01(\x05R\x05\x63ount\x12\x12\n\x04skip\x18\x05 \x01(\x05R\x04skip\"l\n\x18ListTransactionsResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12/\n\x03txs\x18\x02 \x03(\x0b\x32\x1d.pactus.WalletTransactionInfoR\x03txs\"O\n\x14SetDefaultFeeRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x16\n\x06\x61mount\x18\x02 \x01(\x03R\x06\x61mount\"8\n\x15SetDefaultFeeResponse\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\"Q\n\x12GetMnemonicRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08password\x18\x02 \x01(\tR\x08password\"1\n\x13GetMnemonicResponse\x12\x1a\n\x08mnemonic\x18\x01 \x01(\tR\x08mnemonic\"m\n\x14GetPrivateKeyRequest\x12\x1f\n\x0bwallet_name\x18\x01 \x01(\tR\nwalletName\x12\x1a\n\x08password\x18\x02 \x01(\tR\x08password\x12\x18\n\x07\x61\x64\x64ress\x18\x03 \x01(\tR\x07\x61\x64\x64ress\"8\n\x15GetPrivateKeyResponse\x12\x1f\n\x0bprivate_key\x18\x01 \x01(\tR\nprivateKey*\x84\x01\n\x0b\x41\x64\x64ressType\x12\x19\n\x15\x41\x44\x44RESS_TYPE_TREASURY\x10\x00\x12\x1a\n\x16\x41\x44\x44RESS_TYPE_VALIDATOR\x10\x01\x12\x1c\n\x18\x41\x44\x44RESS_TYPE_BLS_ACCOUNT\x10\x02\x12 \n\x1c\x41\x44\x44RESS_TYPE_ED25519_ACCOUNT\x10\x03*Y\n\x0bTxDirection\x12\x14\n\x10TX_DIRECTION_ANY\x10\x00\x12\x19\n\x15TX_DIRECTION_INCOMING\x10\x01\x12\x19\n\x15TX_DIRECTION_OUTGOING\x10\x02*}\n\x11TransactionStatus\x12\x1e\n\x1aTRANSACTION_STATUS_PENDING\x10\x00\x12 \n\x1cTRANSACTION_STATUS_CONFIRMED\x10\x01\x12&\n\x19TRANSACTION_STATUS_FAILED\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x32\xbb\x0c\n\x06Wallet\x12I\n\x0c\x43reateWallet\x12\x1b.pactus.CreateWalletRequest\x1a\x1c.pactus.CreateWalletResponse\x12L\n\rRestoreWallet\x12\x1c.pactus.RestoreWalletRequest\x1a\x1d.pactus.RestoreWalletResponse\x12\x43\n\nLoadWallet\x12\x19.pactus.LoadWalletRequest\x1a\x1a.pactus.LoadWalletResponse\x12I\n\x0cUnloadWallet\x12\x1b.pactus.UnloadWalletRequest\x1a\x1c.pactus.UnloadWalletResponse\x12\x46\n\x0bListWallets\x12\x1a.pactus.ListWalletsRequest\x1a\x1b.pactus.ListWalletsResponse\x12L\n\rGetWalletInfo\x12\x1c.pactus.GetWalletInfoRequest\x1a\x1d.pactus.GetWalletInfoResponse\x12O\n\x0eUpdatePassword\x12\x1d.pactus.UpdatePasswordRequest\x1a\x1e.pactus.UpdatePasswordResponse\x12R\n\x0fGetTotalBalance\x12\x1e.pactus.GetTotalBalanceRequest\x1a\x1f.pactus.GetTotalBalanceResponse\x12L\n\rGetTotalStake\x12\x1c.pactus.GetTotalStakeRequest\x1a\x1d.pactus.GetTotalStakeResponse\x12^\n\x13GetValidatorAddress\x12\".pactus.GetValidatorAddressRequest\x1a#.pactus.GetValidatorAddressResponse\x12O\n\x0eGetAddressInfo\x12\x1d.pactus.GetAddressInfoRequest\x1a\x1e.pactus.GetAddressInfoResponse\x12R\n\x0fSetAddressLabel\x12\x1e.pactus.SetAddressLabelRequest\x1a\x1f.pactus.SetAddressLabelResponse\x12L\n\rGetNewAddress\x12\x1c.pactus.GetNewAddressRequest\x1a\x1d.pactus.GetNewAddressResponse\x12L\n\rListAddresses\x12\x1c.pactus.ListAddressesRequest\x1a\x1d.pactus.ListAddressesResponse\x12\x46\n\x0bSignMessage\x12\x1a.pactus.SignMessageRequest\x1a\x1b.pactus.SignMessageResponse\x12[\n\x12SignRawTransaction\x12!.pactus.SignRawTransactionRequest\x1a\".pactus.SignRawTransactionResponse\x12U\n\x10ListTransactions\x12\x1f.pactus.ListTransactionsRequest\x1a .pactus.ListTransactionsResponse\x12L\n\rSetDefaultFee\x12\x1c.pactus.SetDefaultFeeRequest\x1a\x1d.pactus.SetDefaultFeeResponse\x12\x46\n\x0bGetMnemonic\x12\x1a.pactus.GetMnemonicRequest\x1a\x1b.pactus.GetMnemonicResponse\x12L\n\rGetPrivateKey\x12\x1c.pactus.GetPrivateKeyRequest\x1a\x1d.pactus.GetPrivateKeyResponseB:\n\x06pactusZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wallet_pb2', _globals) if not _descriptor._USE_C_DESCRIPTORS: _globals['DESCRIPTOR']._loaded_options = None _globals['DESCRIPTOR']._serialized_options = b'\n\006pactusZ0github.com/pactus-project/pactus/www/grpc/pactus' _globals['_ADDRESSTYPE']._serialized_start=4287 _globals['_ADDRESSTYPE']._serialized_end=4419 _globals['_TXDIRECTION']._serialized_start=4421 _globals['_TXDIRECTION']._serialized_end=4510 _globals['_TRANSACTIONSTATUS']._serialized_start=4512 _globals['_TRANSACTIONSTATUS']._serialized_end=4637 _globals['_ADDRESSINFO']._serialized_start=43 _globals['_ADDRESSINFO']._serialized_end=155 _globals['_GETNEWADDRESSREQUEST']._serialized_start=158 _globals['_GETNEWADDRESSREQUEST']._serialized_end=319 _globals['_GETNEWADDRESSRESPONSE']._serialized_start=321 _globals['_GETNEWADDRESSRESPONSE']._serialized_end=418 _globals['_RESTOREWALLETREQUEST']._serialized_start=420 _globals['_RESTOREWALLETREQUEST']._serialized_end=531 _globals['_RESTOREWALLETRESPONSE']._serialized_start=533 _globals['_RESTOREWALLETRESPONSE']._serialized_end=589 _globals['_CREATEWALLETREQUEST']._serialized_start=591 _globals['_CREATEWALLETREQUEST']._serialized_end=673 _globals['_CREATEWALLETRESPONSE']._serialized_start=675 _globals['_CREATEWALLETRESPONSE']._serialized_end=758 _globals['_LOADWALLETREQUEST']._serialized_start=760 _globals['_LOADWALLETREQUEST']._serialized_end=812 _globals['_LOADWALLETRESPONSE']._serialized_start=814 _globals['_LOADWALLETRESPONSE']._serialized_end=867 _globals['_UNLOADWALLETREQUEST']._serialized_start=869 _globals['_UNLOADWALLETREQUEST']._serialized_end=923 _globals['_UNLOADWALLETRESPONSE']._serialized_start=925 _globals['_UNLOADWALLETRESPONSE']._serialized_end=980 _globals['_GETVALIDATORADDRESSREQUEST']._serialized_start=982 _globals['_GETVALIDATORADDRESSREQUEST']._serialized_end=1041 _globals['_GETVALIDATORADDRESSRESPONSE']._serialized_start=1043 _globals['_GETVALIDATORADDRESSRESPONSE']._serialized_end=1098 _globals['_SIGNRAWTRANSACTIONREQUEST']._serialized_start=1101 _globals['_SIGNRAWTRANSACTIONREQUEST']._serialized_end=1230 _globals['_SIGNRAWTRANSACTIONRESPONSE']._serialized_start=1232 _globals['_SIGNRAWTRANSACTIONRESPONSE']._serialized_end=1353 _globals['_GETTOTALBALANCEREQUEST']._serialized_start=1355 _globals['_GETTOTALBALANCEREQUEST']._serialized_end=1412 _globals['_GETTOTALBALANCERESPONSE']._serialized_start=1414 _globals['_GETTOTALBALANCERESPONSE']._serialized_end=1509 _globals['_SIGNMESSAGEREQUEST']._serialized_start=1512 _globals['_SIGNMESSAGEREQUEST']._serialized_end=1645 _globals['_SIGNMESSAGERESPONSE']._serialized_start=1647 _globals['_SIGNMESSAGERESPONSE']._serialized_end=1698 _globals['_GETTOTALSTAKEREQUEST']._serialized_start=1700 _globals['_GETTOTALSTAKEREQUEST']._serialized_end=1755 _globals['_GETTOTALSTAKERESPONSE']._serialized_start=1757 _globals['_GETTOTALSTAKERESPONSE']._serialized_end=1846 _globals['_GETADDRESSINFOREQUEST']._serialized_start=1848 _globals['_GETADDRESSINFOREQUEST']._serialized_end=1930 _globals['_GETADDRESSINFORESPONSE']._serialized_start=1932 _globals['_GETADDRESSINFORESPONSE']._serialized_end=2030 _globals['_SETADDRESSLABELREQUEST']._serialized_start=2033 _globals['_SETADDRESSLABELREQUEST']._serialized_end=2166 _globals['_SETADDRESSLABELRESPONSE']._serialized_start=2168 _globals['_SETADDRESSLABELRESPONSE']._serialized_end=2274 _globals['_LISTWALLETSREQUEST']._serialized_start=2276 _globals['_LISTWALLETSREQUEST']._serialized_end=2296 _globals['_LISTWALLETSRESPONSE']._serialized_start=2298 _globals['_LISTWALLETSRESPONSE']._serialized_end=2345 _globals['_GETWALLETINFOREQUEST']._serialized_start=2347 _globals['_GETWALLETINFOREQUEST']._serialized_end=2402 _globals['_GETWALLETINFORESPONSE']._serialized_start=2405 _globals['_GETWALLETINFORESPONSE']._serialized_end=2671 _globals['_LISTADDRESSESREQUEST']._serialized_start=2673 _globals['_LISTADDRESSESREQUEST']._serialized_end=2786 _globals['_LISTADDRESSESRESPONSE']._serialized_start=2788 _globals['_LISTADDRESSESRESPONSE']._serialized_end=2887 _globals['_UPDATEPASSWORDREQUEST']._serialized_start=2889 _globals['_UPDATEPASSWORDREQUEST']._serialized_end=3015 _globals['_UPDATEPASSWORDRESPONSE']._serialized_start=3017 _globals['_UPDATEPASSWORDRESPONSE']._serialized_end=3074 _globals['_WALLETTRANSACTIONINFO']._serialized_start=3077 _globals['_WALLETTRANSACTIONINFO']._serialized_end=3552 _globals['_LISTTRANSACTIONSREQUEST']._serialized_start=3555 _globals['_LISTTRANSACTIONSREQUEST']._serialized_end=3732 _globals['_LISTTRANSACTIONSRESPONSE']._serialized_start=3734 _globals['_LISTTRANSACTIONSRESPONSE']._serialized_end=3842 _globals['_SETDEFAULTFEEREQUEST']._serialized_start=3844 _globals['_SETDEFAULTFEEREQUEST']._serialized_end=3923 _globals['_SETDEFAULTFEERESPONSE']._serialized_start=3925 _globals['_SETDEFAULTFEERESPONSE']._serialized_end=3981 _globals['_GETMNEMONICREQUEST']._serialized_start=3983 _globals['_GETMNEMONICREQUEST']._serialized_end=4064 _globals['_GETMNEMONICRESPONSE']._serialized_start=4066 _globals['_GETMNEMONICRESPONSE']._serialized_end=4115 _globals['_GETPRIVATEKEYREQUEST']._serialized_start=4117 _globals['_GETPRIVATEKEYREQUEST']._serialized_end=4226 _globals['_GETPRIVATEKEYRESPONSE']._serialized_start=4228 _globals['_GETPRIVATEKEYRESPONSE']._serialized_end=4284 _globals['_WALLET']._serialized_start=4640 _globals['_WALLET']._serialized_end=6235 # @@protoc_insertion_point(module_scope) ================================================ FILE: www/grpc/gen/python/wallet_pb2.pyi ================================================ import transaction_pb2 as _transaction_pb2 from google.protobuf.internal import containers as _containers from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from collections.abc import Iterable as _Iterable, Mapping as _Mapping from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union DESCRIPTOR: _descriptor.FileDescriptor class AddressType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () ADDRESS_TYPE_TREASURY: _ClassVar[AddressType] ADDRESS_TYPE_VALIDATOR: _ClassVar[AddressType] ADDRESS_TYPE_BLS_ACCOUNT: _ClassVar[AddressType] ADDRESS_TYPE_ED25519_ACCOUNT: _ClassVar[AddressType] class TxDirection(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () TX_DIRECTION_ANY: _ClassVar[TxDirection] TX_DIRECTION_INCOMING: _ClassVar[TxDirection] TX_DIRECTION_OUTGOING: _ClassVar[TxDirection] class TransactionStatus(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): __slots__ = () TRANSACTION_STATUS_PENDING: _ClassVar[TransactionStatus] TRANSACTION_STATUS_CONFIRMED: _ClassVar[TransactionStatus] TRANSACTION_STATUS_FAILED: _ClassVar[TransactionStatus] ADDRESS_TYPE_TREASURY: AddressType ADDRESS_TYPE_VALIDATOR: AddressType ADDRESS_TYPE_BLS_ACCOUNT: AddressType ADDRESS_TYPE_ED25519_ACCOUNT: AddressType TX_DIRECTION_ANY: TxDirection TX_DIRECTION_INCOMING: TxDirection TX_DIRECTION_OUTGOING: TxDirection TRANSACTION_STATUS_PENDING: TransactionStatus TRANSACTION_STATUS_CONFIRMED: TransactionStatus TRANSACTION_STATUS_FAILED: TransactionStatus class AddressInfo(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] LABEL_FIELD_NUMBER: _ClassVar[int] PATH_FIELD_NUMBER: _ClassVar[int] address: str public_key: str label: str path: str def __init__(self, address: _Optional[str] = ..., public_key: _Optional[str] = ..., label: _Optional[str] = ..., path: _Optional[str] = ...) -> None: ... class GetNewAddressRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDRESS_TYPE_FIELD_NUMBER: _ClassVar[int] LABEL_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] wallet_name: str address_type: AddressType label: str password: str def __init__(self, wallet_name: _Optional[str] = ..., address_type: _Optional[_Union[AddressType, str]] = ..., label: _Optional[str] = ..., password: _Optional[str] = ...) -> None: ... class GetNewAddressResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDR_FIELD_NUMBER: _ClassVar[int] wallet_name: str addr: AddressInfo def __init__(self, wallet_name: _Optional[str] = ..., addr: _Optional[_Union[AddressInfo, _Mapping]] = ...) -> None: ... class RestoreWalletRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] MNEMONIC_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] wallet_name: str mnemonic: str password: str def __init__(self, wallet_name: _Optional[str] = ..., mnemonic: _Optional[str] = ..., password: _Optional[str] = ...) -> None: ... class RestoreWalletResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class CreateWalletRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] wallet_name: str password: str def __init__(self, wallet_name: _Optional[str] = ..., password: _Optional[str] = ...) -> None: ... class CreateWalletResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] MNEMONIC_FIELD_NUMBER: _ClassVar[int] wallet_name: str mnemonic: str def __init__(self, wallet_name: _Optional[str] = ..., mnemonic: _Optional[str] = ...) -> None: ... class LoadWalletRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class LoadWalletResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class UnloadWalletRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class UnloadWalletResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class GetValidatorAddressRequest(_message.Message): __slots__ = () PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int] public_key: str def __init__(self, public_key: _Optional[str] = ...) -> None: ... class GetValidatorAddressResponse(_message.Message): __slots__ = () ADDRESS_FIELD_NUMBER: _ClassVar[int] address: str def __init__(self, address: _Optional[str] = ...) -> None: ... class SignRawTransactionRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] RAW_TRANSACTION_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] wallet_name: str raw_transaction: str password: str def __init__(self, wallet_name: _Optional[str] = ..., raw_transaction: _Optional[str] = ..., password: _Optional[str] = ...) -> None: ... class SignRawTransactionResponse(_message.Message): __slots__ = () TRANSACTION_ID_FIELD_NUMBER: _ClassVar[int] SIGNED_RAW_TRANSACTION_FIELD_NUMBER: _ClassVar[int] transaction_id: str signed_raw_transaction: str def __init__(self, transaction_id: _Optional[str] = ..., signed_raw_transaction: _Optional[str] = ...) -> None: ... class GetTotalBalanceRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class GetTotalBalanceResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] TOTAL_BALANCE_FIELD_NUMBER: _ClassVar[int] wallet_name: str total_balance: int def __init__(self, wallet_name: _Optional[str] = ..., total_balance: _Optional[int] = ...) -> None: ... class SignMessageRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] MESSAGE_FIELD_NUMBER: _ClassVar[int] wallet_name: str password: str address: str message: str def __init__(self, wallet_name: _Optional[str] = ..., password: _Optional[str] = ..., address: _Optional[str] = ..., message: _Optional[str] = ...) -> None: ... class SignMessageResponse(_message.Message): __slots__ = () SIGNATURE_FIELD_NUMBER: _ClassVar[int] signature: str def __init__(self, signature: _Optional[str] = ...) -> None: ... class GetTotalStakeRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class GetTotalStakeResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] TOTAL_STAKE_FIELD_NUMBER: _ClassVar[int] wallet_name: str total_stake: int def __init__(self, wallet_name: _Optional[str] = ..., total_stake: _Optional[int] = ...) -> None: ... class GetAddressInfoRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] wallet_name: str address: str def __init__(self, wallet_name: _Optional[str] = ..., address: _Optional[str] = ...) -> None: ... class GetAddressInfoResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDR_FIELD_NUMBER: _ClassVar[int] wallet_name: str addr: AddressInfo def __init__(self, wallet_name: _Optional[str] = ..., addr: _Optional[_Union[AddressInfo, _Mapping]] = ...) -> None: ... class SetAddressLabelRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] LABEL_FIELD_NUMBER: _ClassVar[int] wallet_name: str password: str address: str label: str def __init__(self, wallet_name: _Optional[str] = ..., password: _Optional[str] = ..., address: _Optional[str] = ..., label: _Optional[str] = ...) -> None: ... class SetAddressLabelResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] LABEL_FIELD_NUMBER: _ClassVar[int] wallet_name: str address: str label: str def __init__(self, wallet_name: _Optional[str] = ..., address: _Optional[str] = ..., label: _Optional[str] = ...) -> None: ... class ListWalletsRequest(_message.Message): __slots__ = () def __init__(self) -> None: ... class ListWalletsResponse(_message.Message): __slots__ = () WALLETS_FIELD_NUMBER: _ClassVar[int] wallets: _containers.RepeatedScalarFieldContainer[str] def __init__(self, wallets: _Optional[_Iterable[str]] = ...) -> None: ... class GetWalletInfoRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class GetWalletInfoResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] VERSION_FIELD_NUMBER: _ClassVar[int] NETWORK_FIELD_NUMBER: _ClassVar[int] ENCRYPTED_FIELD_NUMBER: _ClassVar[int] UUID_FIELD_NUMBER: _ClassVar[int] CREATED_AT_FIELD_NUMBER: _ClassVar[int] DEFAULT_FEE_FIELD_NUMBER: _ClassVar[int] DRIVER_FIELD_NUMBER: _ClassVar[int] PATH_FIELD_NUMBER: _ClassVar[int] wallet_name: str version: int network: str encrypted: bool uuid: str created_at: int default_fee: int driver: str path: str def __init__(self, wallet_name: _Optional[str] = ..., version: _Optional[int] = ..., network: _Optional[str] = ..., encrypted: _Optional[bool] = ..., uuid: _Optional[str] = ..., created_at: _Optional[int] = ..., default_fee: _Optional[int] = ..., driver: _Optional[str] = ..., path: _Optional[str] = ...) -> None: ... class ListAddressesRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDRESS_TYPES_FIELD_NUMBER: _ClassVar[int] wallet_name: str address_types: _containers.RepeatedScalarFieldContainer[AddressType] def __init__(self, wallet_name: _Optional[str] = ..., address_types: _Optional[_Iterable[_Union[AddressType, str]]] = ...) -> None: ... class ListAddressesResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDRS_FIELD_NUMBER: _ClassVar[int] wallet_name: str addrs: _containers.RepeatedCompositeFieldContainer[AddressInfo] def __init__(self, wallet_name: _Optional[str] = ..., addrs: _Optional[_Iterable[_Union[AddressInfo, _Mapping]]] = ...) -> None: ... class UpdatePasswordRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] OLD_PASSWORD_FIELD_NUMBER: _ClassVar[int] NEW_PASSWORD_FIELD_NUMBER: _ClassVar[int] wallet_name: str old_password: str new_password: str def __init__(self, wallet_name: _Optional[str] = ..., old_password: _Optional[str] = ..., new_password: _Optional[str] = ...) -> None: ... class UpdatePasswordResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class WalletTransactionInfo(_message.Message): __slots__ = () NO_FIELD_NUMBER: _ClassVar[int] TX_ID_FIELD_NUMBER: _ClassVar[int] SENDER_FIELD_NUMBER: _ClassVar[int] RECEIVER_FIELD_NUMBER: _ClassVar[int] DIRECTION_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] FEE_FIELD_NUMBER: _ClassVar[int] MEMO_FIELD_NUMBER: _ClassVar[int] STATUS_FIELD_NUMBER: _ClassVar[int] BLOCK_HEIGHT_FIELD_NUMBER: _ClassVar[int] PAYLOAD_TYPE_FIELD_NUMBER: _ClassVar[int] DATA_FIELD_NUMBER: _ClassVar[int] COMMENT_FIELD_NUMBER: _ClassVar[int] CREATED_AT_FIELD_NUMBER: _ClassVar[int] UPDATED_AT_FIELD_NUMBER: _ClassVar[int] no: int tx_id: str sender: str receiver: str direction: TxDirection amount: int fee: int memo: str status: TransactionStatus block_height: int payload_type: _transaction_pb2.PayloadType data: bytes comment: str created_at: int updated_at: int def __init__(self, no: _Optional[int] = ..., tx_id: _Optional[str] = ..., sender: _Optional[str] = ..., receiver: _Optional[str] = ..., direction: _Optional[_Union[TxDirection, str]] = ..., amount: _Optional[int] = ..., fee: _Optional[int] = ..., memo: _Optional[str] = ..., status: _Optional[_Union[TransactionStatus, str]] = ..., block_height: _Optional[int] = ..., payload_type: _Optional[_Union[_transaction_pb2.PayloadType, str]] = ..., data: _Optional[bytes] = ..., comment: _Optional[str] = ..., created_at: _Optional[int] = ..., updated_at: _Optional[int] = ...) -> None: ... class ListTransactionsRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] DIRECTION_FIELD_NUMBER: _ClassVar[int] COUNT_FIELD_NUMBER: _ClassVar[int] SKIP_FIELD_NUMBER: _ClassVar[int] wallet_name: str address: str direction: TxDirection count: int skip: int def __init__(self, wallet_name: _Optional[str] = ..., address: _Optional[str] = ..., direction: _Optional[_Union[TxDirection, str]] = ..., count: _Optional[int] = ..., skip: _Optional[int] = ...) -> None: ... class ListTransactionsResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] TXS_FIELD_NUMBER: _ClassVar[int] wallet_name: str txs: _containers.RepeatedCompositeFieldContainer[WalletTransactionInfo] def __init__(self, wallet_name: _Optional[str] = ..., txs: _Optional[_Iterable[_Union[WalletTransactionInfo, _Mapping]]] = ...) -> None: ... class SetDefaultFeeRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] AMOUNT_FIELD_NUMBER: _ClassVar[int] wallet_name: str amount: int def __init__(self, wallet_name: _Optional[str] = ..., amount: _Optional[int] = ...) -> None: ... class SetDefaultFeeResponse(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] wallet_name: str def __init__(self, wallet_name: _Optional[str] = ...) -> None: ... class GetMnemonicRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] wallet_name: str password: str def __init__(self, wallet_name: _Optional[str] = ..., password: _Optional[str] = ...) -> None: ... class GetMnemonicResponse(_message.Message): __slots__ = () MNEMONIC_FIELD_NUMBER: _ClassVar[int] mnemonic: str def __init__(self, mnemonic: _Optional[str] = ...) -> None: ... class GetPrivateKeyRequest(_message.Message): __slots__ = () WALLET_NAME_FIELD_NUMBER: _ClassVar[int] PASSWORD_FIELD_NUMBER: _ClassVar[int] ADDRESS_FIELD_NUMBER: _ClassVar[int] wallet_name: str password: str address: str def __init__(self, wallet_name: _Optional[str] = ..., password: _Optional[str] = ..., address: _Optional[str] = ...) -> None: ... class GetPrivateKeyResponse(_message.Message): __slots__ = () PRIVATE_KEY_FIELD_NUMBER: _ClassVar[int] private_key: str def __init__(self, private_key: _Optional[str] = ...) -> None: ... ================================================ FILE: www/grpc/gen/python/wallet_pb2_grpc.py ================================================ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import wallet_pb2 as wallet__pb2 class WalletStub(object): """Wallet service provides RPC methods for wallet management operations. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.CreateWallet = channel.unary_unary( '/pactus.Wallet/CreateWallet', request_serializer=wallet__pb2.CreateWalletRequest.SerializeToString, response_deserializer=wallet__pb2.CreateWalletResponse.FromString, _registered_method=True) self.RestoreWallet = channel.unary_unary( '/pactus.Wallet/RestoreWallet', request_serializer=wallet__pb2.RestoreWalletRequest.SerializeToString, response_deserializer=wallet__pb2.RestoreWalletResponse.FromString, _registered_method=True) self.LoadWallet = channel.unary_unary( '/pactus.Wallet/LoadWallet', request_serializer=wallet__pb2.LoadWalletRequest.SerializeToString, response_deserializer=wallet__pb2.LoadWalletResponse.FromString, _registered_method=True) self.UnloadWallet = channel.unary_unary( '/pactus.Wallet/UnloadWallet', request_serializer=wallet__pb2.UnloadWalletRequest.SerializeToString, response_deserializer=wallet__pb2.UnloadWalletResponse.FromString, _registered_method=True) self.ListWallets = channel.unary_unary( '/pactus.Wallet/ListWallets', request_serializer=wallet__pb2.ListWalletsRequest.SerializeToString, response_deserializer=wallet__pb2.ListWalletsResponse.FromString, _registered_method=True) self.GetWalletInfo = channel.unary_unary( '/pactus.Wallet/GetWalletInfo', request_serializer=wallet__pb2.GetWalletInfoRequest.SerializeToString, response_deserializer=wallet__pb2.GetWalletInfoResponse.FromString, _registered_method=True) self.UpdatePassword = channel.unary_unary( '/pactus.Wallet/UpdatePassword', request_serializer=wallet__pb2.UpdatePasswordRequest.SerializeToString, response_deserializer=wallet__pb2.UpdatePasswordResponse.FromString, _registered_method=True) self.GetTotalBalance = channel.unary_unary( '/pactus.Wallet/GetTotalBalance', request_serializer=wallet__pb2.GetTotalBalanceRequest.SerializeToString, response_deserializer=wallet__pb2.GetTotalBalanceResponse.FromString, _registered_method=True) self.GetTotalStake = channel.unary_unary( '/pactus.Wallet/GetTotalStake', request_serializer=wallet__pb2.GetTotalStakeRequest.SerializeToString, response_deserializer=wallet__pb2.GetTotalStakeResponse.FromString, _registered_method=True) self.GetValidatorAddress = channel.unary_unary( '/pactus.Wallet/GetValidatorAddress', request_serializer=wallet__pb2.GetValidatorAddressRequest.SerializeToString, response_deserializer=wallet__pb2.GetValidatorAddressResponse.FromString, _registered_method=True) self.GetAddressInfo = channel.unary_unary( '/pactus.Wallet/GetAddressInfo', request_serializer=wallet__pb2.GetAddressInfoRequest.SerializeToString, response_deserializer=wallet__pb2.GetAddressInfoResponse.FromString, _registered_method=True) self.SetAddressLabel = channel.unary_unary( '/pactus.Wallet/SetAddressLabel', request_serializer=wallet__pb2.SetAddressLabelRequest.SerializeToString, response_deserializer=wallet__pb2.SetAddressLabelResponse.FromString, _registered_method=True) self.GetNewAddress = channel.unary_unary( '/pactus.Wallet/GetNewAddress', request_serializer=wallet__pb2.GetNewAddressRequest.SerializeToString, response_deserializer=wallet__pb2.GetNewAddressResponse.FromString, _registered_method=True) self.ListAddresses = channel.unary_unary( '/pactus.Wallet/ListAddresses', request_serializer=wallet__pb2.ListAddressesRequest.SerializeToString, response_deserializer=wallet__pb2.ListAddressesResponse.FromString, _registered_method=True) self.SignMessage = channel.unary_unary( '/pactus.Wallet/SignMessage', request_serializer=wallet__pb2.SignMessageRequest.SerializeToString, response_deserializer=wallet__pb2.SignMessageResponse.FromString, _registered_method=True) self.SignRawTransaction = channel.unary_unary( '/pactus.Wallet/SignRawTransaction', request_serializer=wallet__pb2.SignRawTransactionRequest.SerializeToString, response_deserializer=wallet__pb2.SignRawTransactionResponse.FromString, _registered_method=True) self.ListTransactions = channel.unary_unary( '/pactus.Wallet/ListTransactions', request_serializer=wallet__pb2.ListTransactionsRequest.SerializeToString, response_deserializer=wallet__pb2.ListTransactionsResponse.FromString, _registered_method=True) self.SetDefaultFee = channel.unary_unary( '/pactus.Wallet/SetDefaultFee', request_serializer=wallet__pb2.SetDefaultFeeRequest.SerializeToString, response_deserializer=wallet__pb2.SetDefaultFeeResponse.FromString, _registered_method=True) self.GetMnemonic = channel.unary_unary( '/pactus.Wallet/GetMnemonic', request_serializer=wallet__pb2.GetMnemonicRequest.SerializeToString, response_deserializer=wallet__pb2.GetMnemonicResponse.FromString, _registered_method=True) self.GetPrivateKey = channel.unary_unary( '/pactus.Wallet/GetPrivateKey', request_serializer=wallet__pb2.GetPrivateKeyRequest.SerializeToString, response_deserializer=wallet__pb2.GetPrivateKeyResponse.FromString, _registered_method=True) class WalletServicer(object): """Wallet service provides RPC methods for wallet management operations. """ def CreateWallet(self, request, context): """CreateWallet creates a new wallet with the specified parameters. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def RestoreWallet(self, request, context): """RestoreWallet restores an existing wallet with the given mnemonic. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def LoadWallet(self, request, context): """LoadWallet loads an existing wallet with the given name. deprecated: It will be removed in a future version. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UnloadWallet(self, request, context): """UnloadWallet unloads a currently loaded wallet with the specified name. deprecated: It will be removed in a future version. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListWallets(self, request, context): """ListWallets returns a list of all available wallets. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetWalletInfo(self, request, context): """GetWalletInfo returns detailed information about a specific wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UpdatePassword(self, request, context): """UpdatePassword updates the password of an existing wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetTotalBalance(self, request, context): """GetTotalBalance returns the total available balance of the wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetTotalStake(self, request, context): """GetTotalStake returns the total stake amount in the wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetValidatorAddress(self, request, context): """GetValidatorAddress retrieves the validator address associated with a public key. Deprecated: Will move into utils. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetAddressInfo(self, request, context): """GetAddressInfo returns detailed information about a specific address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def SetAddressLabel(self, request, context): """SetAddressLabel sets or updates the label for a given address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetNewAddress(self, request, context): """GetNewAddress generates a new address for the specified wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListAddresses(self, request, context): """ListAddresses returns all addresses in the specified wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def SignMessage(self, request, context): """SignMessage signs an arbitrary message using a wallet's private key. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def SignRawTransaction(self, request, context): """SignRawTransaction signs a raw transaction for a specified wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListTransactions(self, request, context): """ListTransactions returns a list of transactions for a wallet, optionally filtered by a specific address, with pagination support. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def SetDefaultFee(self, request, context): """SetDefaultFee sets the default fee for the wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetMnemonic(self, request, context): """GetMnemonic returns the mnemonic (seed phrase) for the wallet. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetPrivateKey(self, request, context): """GetPrivateKey returns the private key for a given address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_WalletServicer_to_server(servicer, server): rpc_method_handlers = { 'CreateWallet': grpc.unary_unary_rpc_method_handler( servicer.CreateWallet, request_deserializer=wallet__pb2.CreateWalletRequest.FromString, response_serializer=wallet__pb2.CreateWalletResponse.SerializeToString, ), 'RestoreWallet': grpc.unary_unary_rpc_method_handler( servicer.RestoreWallet, request_deserializer=wallet__pb2.RestoreWalletRequest.FromString, response_serializer=wallet__pb2.RestoreWalletResponse.SerializeToString, ), 'LoadWallet': grpc.unary_unary_rpc_method_handler( servicer.LoadWallet, request_deserializer=wallet__pb2.LoadWalletRequest.FromString, response_serializer=wallet__pb2.LoadWalletResponse.SerializeToString, ), 'UnloadWallet': grpc.unary_unary_rpc_method_handler( servicer.UnloadWallet, request_deserializer=wallet__pb2.UnloadWalletRequest.FromString, response_serializer=wallet__pb2.UnloadWalletResponse.SerializeToString, ), 'ListWallets': grpc.unary_unary_rpc_method_handler( servicer.ListWallets, request_deserializer=wallet__pb2.ListWalletsRequest.FromString, response_serializer=wallet__pb2.ListWalletsResponse.SerializeToString, ), 'GetWalletInfo': grpc.unary_unary_rpc_method_handler( servicer.GetWalletInfo, request_deserializer=wallet__pb2.GetWalletInfoRequest.FromString, response_serializer=wallet__pb2.GetWalletInfoResponse.SerializeToString, ), 'UpdatePassword': grpc.unary_unary_rpc_method_handler( servicer.UpdatePassword, request_deserializer=wallet__pb2.UpdatePasswordRequest.FromString, response_serializer=wallet__pb2.UpdatePasswordResponse.SerializeToString, ), 'GetTotalBalance': grpc.unary_unary_rpc_method_handler( servicer.GetTotalBalance, request_deserializer=wallet__pb2.GetTotalBalanceRequest.FromString, response_serializer=wallet__pb2.GetTotalBalanceResponse.SerializeToString, ), 'GetTotalStake': grpc.unary_unary_rpc_method_handler( servicer.GetTotalStake, request_deserializer=wallet__pb2.GetTotalStakeRequest.FromString, response_serializer=wallet__pb2.GetTotalStakeResponse.SerializeToString, ), 'GetValidatorAddress': grpc.unary_unary_rpc_method_handler( servicer.GetValidatorAddress, request_deserializer=wallet__pb2.GetValidatorAddressRequest.FromString, response_serializer=wallet__pb2.GetValidatorAddressResponse.SerializeToString, ), 'GetAddressInfo': grpc.unary_unary_rpc_method_handler( servicer.GetAddressInfo, request_deserializer=wallet__pb2.GetAddressInfoRequest.FromString, response_serializer=wallet__pb2.GetAddressInfoResponse.SerializeToString, ), 'SetAddressLabel': grpc.unary_unary_rpc_method_handler( servicer.SetAddressLabel, request_deserializer=wallet__pb2.SetAddressLabelRequest.FromString, response_serializer=wallet__pb2.SetAddressLabelResponse.SerializeToString, ), 'GetNewAddress': grpc.unary_unary_rpc_method_handler( servicer.GetNewAddress, request_deserializer=wallet__pb2.GetNewAddressRequest.FromString, response_serializer=wallet__pb2.GetNewAddressResponse.SerializeToString, ), 'ListAddresses': grpc.unary_unary_rpc_method_handler( servicer.ListAddresses, request_deserializer=wallet__pb2.ListAddressesRequest.FromString, response_serializer=wallet__pb2.ListAddressesResponse.SerializeToString, ), 'SignMessage': grpc.unary_unary_rpc_method_handler( servicer.SignMessage, request_deserializer=wallet__pb2.SignMessageRequest.FromString, response_serializer=wallet__pb2.SignMessageResponse.SerializeToString, ), 'SignRawTransaction': grpc.unary_unary_rpc_method_handler( servicer.SignRawTransaction, request_deserializer=wallet__pb2.SignRawTransactionRequest.FromString, response_serializer=wallet__pb2.SignRawTransactionResponse.SerializeToString, ), 'ListTransactions': grpc.unary_unary_rpc_method_handler( servicer.ListTransactions, request_deserializer=wallet__pb2.ListTransactionsRequest.FromString, response_serializer=wallet__pb2.ListTransactionsResponse.SerializeToString, ), 'SetDefaultFee': grpc.unary_unary_rpc_method_handler( servicer.SetDefaultFee, request_deserializer=wallet__pb2.SetDefaultFeeRequest.FromString, response_serializer=wallet__pb2.SetDefaultFeeResponse.SerializeToString, ), 'GetMnemonic': grpc.unary_unary_rpc_method_handler( servicer.GetMnemonic, request_deserializer=wallet__pb2.GetMnemonicRequest.FromString, response_serializer=wallet__pb2.GetMnemonicResponse.SerializeToString, ), 'GetPrivateKey': grpc.unary_unary_rpc_method_handler( servicer.GetPrivateKey, request_deserializer=wallet__pb2.GetPrivateKeyRequest.FromString, response_serializer=wallet__pb2.GetPrivateKeyResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'pactus.Wallet', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) server.add_registered_method_handlers('pactus.Wallet', rpc_method_handlers) # This class is part of an EXPERIMENTAL API. class Wallet(object): """Wallet service provides RPC methods for wallet management operations. """ @staticmethod def CreateWallet(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/CreateWallet', wallet__pb2.CreateWalletRequest.SerializeToString, wallet__pb2.CreateWalletResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def RestoreWallet(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/RestoreWallet', wallet__pb2.RestoreWalletRequest.SerializeToString, wallet__pb2.RestoreWalletResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def LoadWallet(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/LoadWallet', wallet__pb2.LoadWalletRequest.SerializeToString, wallet__pb2.LoadWalletResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def UnloadWallet(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/UnloadWallet', wallet__pb2.UnloadWalletRequest.SerializeToString, wallet__pb2.UnloadWalletResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def ListWallets(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/ListWallets', wallet__pb2.ListWalletsRequest.SerializeToString, wallet__pb2.ListWalletsResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetWalletInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetWalletInfo', wallet__pb2.GetWalletInfoRequest.SerializeToString, wallet__pb2.GetWalletInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def UpdatePassword(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/UpdatePassword', wallet__pb2.UpdatePasswordRequest.SerializeToString, wallet__pb2.UpdatePasswordResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetTotalBalance(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetTotalBalance', wallet__pb2.GetTotalBalanceRequest.SerializeToString, wallet__pb2.GetTotalBalanceResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetTotalStake(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetTotalStake', wallet__pb2.GetTotalStakeRequest.SerializeToString, wallet__pb2.GetTotalStakeResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetValidatorAddress(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetValidatorAddress', wallet__pb2.GetValidatorAddressRequest.SerializeToString, wallet__pb2.GetValidatorAddressResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetAddressInfo(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetAddressInfo', wallet__pb2.GetAddressInfoRequest.SerializeToString, wallet__pb2.GetAddressInfoResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def SetAddressLabel(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/SetAddressLabel', wallet__pb2.SetAddressLabelRequest.SerializeToString, wallet__pb2.SetAddressLabelResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetNewAddress(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetNewAddress', wallet__pb2.GetNewAddressRequest.SerializeToString, wallet__pb2.GetNewAddressResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def ListAddresses(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/ListAddresses', wallet__pb2.ListAddressesRequest.SerializeToString, wallet__pb2.ListAddressesResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def SignMessage(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/SignMessage', wallet__pb2.SignMessageRequest.SerializeToString, wallet__pb2.SignMessageResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def SignRawTransaction(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/SignRawTransaction', wallet__pb2.SignRawTransactionRequest.SerializeToString, wallet__pb2.SignRawTransactionResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def ListTransactions(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/ListTransactions', wallet__pb2.ListTransactionsRequest.SerializeToString, wallet__pb2.ListTransactionsResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def SetDefaultFee(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/SetDefaultFee', wallet__pb2.SetDefaultFeeRequest.SerializeToString, wallet__pb2.SetDefaultFeeResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetMnemonic(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetMnemonic', wallet__pb2.GetMnemonicRequest.SerializeToString, wallet__pb2.GetMnemonicResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) @staticmethod def GetPrivateKey(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/pactus.Wallet/GetPrivateKey', wallet__pb2.GetPrivateKeyRequest.SerializeToString, wallet__pb2.GetPrivateKeyResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True) ================================================ FILE: www/grpc/gen/rust/pactus.rs ================================================ // @generated // This file is @generated by prost-build. /// Request message for retrieving transaction details. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetTransactionRequest { /// The unique ID of the transaction to retrieve. #[prost(string, tag="1")] pub id: ::prost::alloc::string::String, /// The verbosity level for transaction details. #[prost(enumeration="TransactionVerbosity", tag="2")] pub verbosity: i32, } /// Response message contains details of a transaction. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetTransactionResponse { /// The height of the block containing the transaction. #[prost(uint32, tag="1")] pub block_height: u32, /// The UNIX timestamp of the block containing the transaction. #[prost(uint32, tag="2")] pub block_time: u32, /// Detailed information about the transaction. #[prost(message, optional, tag="3")] pub transaction: ::core::option::Option, } /// Request message for calculating transaction fee. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct CalculateFeeRequest { /// The amount involved in the transaction, specified in NanoPAC. #[prost(int64, tag="1")] pub amount: i64, /// The type of transaction payload. #[prost(enumeration="PayloadType", tag="2")] pub payload_type: i32, /// Indicates if the amount should be fixed and include the fee. #[prost(bool, tag="3")] pub fixed_amount: bool, } /// Response message contains the calculated transaction fee. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct CalculateFeeResponse { /// The calculated amount in NanoPAC. #[prost(int64, tag="1")] pub amount: i64, /// The calculated transaction fee in NanoPAC. #[prost(int64, tag="2")] pub fee: i64, } /// Request message for broadcasting a signed transaction to the network. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct BroadcastTransactionRequest { /// The signed raw transaction data to be broadcasted. #[prost(string, tag="1")] pub signed_raw_transaction: ::prost::alloc::string::String, } /// Response message contains the ID of the broadcasted transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct BroadcastTransactionResponse { /// The unique ID of the broadcasted transaction. #[prost(string, tag="1")] pub id: ::prost::alloc::string::String, } /// Request message for retrieving raw details of a transfer transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetRawTransferTransactionRequest { /// The lock time for the transaction. If not set, defaults to the last block height. #[prost(uint32, tag="1")] pub lock_time: u32, /// The sender's account address. #[prost(string, tag="2")] pub sender: ::prost::alloc::string::String, /// The receiver's account address. #[prost(string, tag="3")] pub receiver: ::prost::alloc::string::String, /// The amount to be transferred, specified in NanoPAC. Must be greater than 0. #[prost(int64, tag="4")] pub amount: i64, /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. #[prost(int64, tag="5")] pub fee: i64, /// A memo string for the transaction. #[prost(string, tag="6")] pub memo: ::prost::alloc::string::String, } /// Request message for retrieving raw details of a bond transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetRawBondTransactionRequest { /// The lock time for the transaction. If not set, defaults to the last block height. #[prost(uint32, tag="1")] pub lock_time: u32, /// The sender's account address. #[prost(string, tag="2")] pub sender: ::prost::alloc::string::String, /// The receiver's validator address. #[prost(string, tag="3")] pub receiver: ::prost::alloc::string::String, /// The stake amount in NanoPAC. Must be greater than 0. #[prost(int64, tag="4")] pub stake: i64, /// The public key of the validator. /// Optional, but required when registering a new validator.; #[prost(string, tag="5")] pub public_key: ::prost::alloc::string::String, /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. #[prost(int64, tag="6")] pub fee: i64, /// A memo string for the transaction. #[prost(string, tag="7")] pub memo: ::prost::alloc::string::String, /// The address of the delegate owner. /// Optional, but required when registering a new validator with delegation.; #[prost(string, tag="8")] pub delegate_owner: ::prost::alloc::string::String, /// The share percentage for the delegate owner. /// Optional, but required when registering a new validator with delegation.; /// Must be between 0 and 0.7 PAC in nano PAC. #[prost(int64, tag="9")] pub delegate_share: i64, /// The expiry height for the delegate relationship. /// Optional, but required when registering a new validator with delegation.; #[prost(uint32, tag="10")] pub delegate_expiry: u32, } /// Request message for retrieving raw details of an unbond transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetRawUnbondTransactionRequest { /// The lock time for the transaction. If not set, defaults to the last block height. #[prost(uint32, tag="1")] pub lock_time: u32, /// The address of the validator to unbond from. #[prost(string, tag="2")] pub validator_address: ::prost::alloc::string::String, /// A memo string for the transaction. #[prost(string, tag="3")] pub memo: ::prost::alloc::string::String, /// The address of the delegate owner. /// Optional, but required when the validator is a delegated validator.; #[prost(string, tag="4")] pub delegate_owner: ::prost::alloc::string::String, } /// Request message for retrieving raw details of a withdraw transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetRawWithdrawTransactionRequest { /// The lock time for the transaction. If not set, defaults to the last block height. #[prost(uint32, tag="1")] pub lock_time: u32, /// The address of the validator to withdraw from. #[prost(string, tag="2")] pub validator_address: ::prost::alloc::string::String, /// The address of the account to withdraw to. #[prost(string, tag="3")] pub account_address: ::prost::alloc::string::String, /// The withdrawal amount in NanoPAC. Must be greater than 0. #[prost(int64, tag="4")] pub amount: i64, /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. #[prost(int64, tag="5")] pub fee: i64, /// A memo string for the transaction. #[prost(string, tag="6")] pub memo: ::prost::alloc::string::String, } /// Request message for retrieving raw details of a batch transfer transaction. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetRawBatchTransferTransactionRequest { /// The lock time for the transaction. If not set, defaults to the last block height. #[prost(uint32, tag="1")] pub lock_time: u32, /// The sender's account address. #[prost(string, tag="2")] pub sender: ::prost::alloc::string::String, /// The list of recipients with their amounts. Minimum 2 recipients required. #[prost(message, repeated, tag="3")] pub recipients: ::prost::alloc::vec::Vec, /// The transaction fee in NanoPAC. If not set, it is set to the estimated fee. #[prost(int64, tag="4")] pub fee: i64, /// A memo string for the transaction. #[prost(string, tag="5")] pub memo: ::prost::alloc::string::String, } /// Response message contains raw transaction data. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetRawTransactionResponse { /// The raw transaction data in hexadecimal format. #[prost(string, tag="1")] pub raw_transaction: ::prost::alloc::string::String, /// The unique ID of the transaction. #[prost(string, tag="2")] pub id: ::prost::alloc::string::String, } /// Payload for a transfer transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PayloadTransfer { /// The sender's address. #[prost(string, tag="1")] pub sender: ::prost::alloc::string::String, /// The receiver's address. #[prost(string, tag="2")] pub receiver: ::prost::alloc::string::String, /// The amount to be transferred in NanoPAC. #[prost(int64, tag="3")] pub amount: i64, } /// Payload for a bond transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PayloadBond { /// The sender's address. #[prost(string, tag="1")] pub sender: ::prost::alloc::string::String, /// The receiver's address. #[prost(string, tag="2")] pub receiver: ::prost::alloc::string::String, /// The stake amount in NanoPAC. #[prost(int64, tag="3")] pub stake: i64, /// The public key of the validator. #[prost(string, tag="4")] pub public_key: ::prost::alloc::string::String, /// Indicates whether the bond transaction is a delegation. #[prost(bool, tag="5")] pub is_delegated: bool, /// The address of the delegate owner. /// Optional, but required when registering a new validator with delegation.; #[prost(string, tag="6")] pub delegate_owner: ::prost::alloc::string::String, /// The share percentage for the delegate owner. /// Optional, but required when registering a new validator with delegation.; /// Must be between 0 and 0.7 PAC in nano PAC. #[prost(int64, tag="7")] pub delegate_share: i64, /// The expiry height for the delegate relationship. /// Optional, but required when registering a new validator with delegation.; #[prost(uint32, tag="8")] pub delegate_expiry: u32, } /// Payload for a sortition transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PayloadSortition { /// The validator address associated with the sortition proof. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, /// The proof for the sortition. #[prost(string, tag="2")] pub proof: ::prost::alloc::string::String, } /// Payload for an unbond transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PayloadUnbond { /// The address of the validator to unbond from. #[prost(string, tag="1")] pub validator: ::prost::alloc::string::String, /// The address of the delegate owner. /// Optional, but required when the validator is a delegated validator.; #[prost(string, tag="2")] pub delegate_owner: ::prost::alloc::string::String, } /// Payload for a withdraw transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PayloadWithdraw { /// The address of the validator to withdraw from. #[prost(string, tag="1")] pub validator_address: ::prost::alloc::string::String, /// The address of the account to withdraw to. #[prost(string, tag="2")] pub account_address: ::prost::alloc::string::String, /// The withdrawal amount in NanoPAC. #[prost(int64, tag="3")] pub amount: i64, } /// Payload for a batch transfer transaction. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PayloadBatchTransfer { /// The sender's address. #[prost(string, tag="1")] pub sender: ::prost::alloc::string::String, /// The list of recipients with their amounts. #[prost(message, repeated, tag="2")] pub recipients: ::prost::alloc::vec::Vec, } /// Recipient is receiver with amount. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct Recipient { /// The receiver's address. #[prost(string, tag="1")] pub receiver: ::prost::alloc::string::String, /// The amount in NanoPAC. #[prost(int64, tag="2")] pub amount: i64, } /// Information about a transaction. #[derive(Clone, PartialEq, ::prost::Message)] pub struct TransactionInfo { /// The unique ID of the transaction. #[prost(string, tag="1")] pub id: ::prost::alloc::string::String, /// The raw transaction data in hexadecimal format. #[prost(string, tag="2")] pub data: ::prost::alloc::string::String, /// The version of the transaction. #[prost(int32, tag="3")] pub version: i32, /// The lock time for the transaction. #[prost(uint32, tag="4")] pub lock_time: u32, /// The value of the transaction in NanoPAC. #[prost(int64, tag="5")] pub value: i64, /// The fee for the transaction in NanoPAC. #[prost(int64, tag="6")] pub fee: i64, /// The type of transaction payload. #[prost(enumeration="PayloadType", tag="7")] pub payload_type: i32, /// A memo string for the transaction. #[prost(string, tag="8")] pub memo: ::prost::alloc::string::String, /// The public key associated with the transaction. #[prost(string, tag="9")] pub public_key: ::prost::alloc::string::String, /// The signature for the transaction. #[prost(string, tag="10")] pub signature: ::prost::alloc::string::String, /// The block height containing the transaction. /// A value of zero means the transaction is unconfirmed and may still in the transaction pool. #[prost(uint32, tag="11")] pub block_height: u32, /// Indicates whether the transaction is confirmed. #[prost(bool, tag="12")] pub confirmed: bool, /// The number of blocks that have been added to the chain after this transaction was included in a block. /// A value of zero means the transaction is unconfirmed and may still in the transaction pool. #[prost(int32, tag="13")] pub confirmations: i32, /// Transaction payload. #[prost(oneof="transaction_info::Payload", tags="30, 31, 32, 33, 34, 35")] pub payload: ::core::option::Option, } /// Nested message and enum types in `TransactionInfo`. pub mod transaction_info { /// Transaction payload. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Payload { /// Transfer transaction payload. #[prost(message, tag="30")] Transfer(super::PayloadTransfer), /// Bond transaction payload. #[prost(message, tag="31")] Bond(super::PayloadBond), /// Sortition transaction payload. #[prost(message, tag="32")] Sortition(super::PayloadSortition), /// Unbond transaction payload. #[prost(message, tag="33")] Unbond(super::PayloadUnbond), /// Withdraw transaction payload. #[prost(message, tag="34")] Withdraw(super::PayloadWithdraw), /// Batch Transfer transaction payload. #[prost(message, tag="35")] BatchTransfer(super::PayloadBatchTransfer), } } /// Request message for decoding a raw transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct DecodeRawTransactionRequest { /// The raw transaction data in hexadecimal format. #[prost(string, tag="1")] pub raw_transaction: ::prost::alloc::string::String, } /// Response message contains the decoded transaction. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DecodeRawTransactionResponse { /// The decoded transaction information. #[prost(message, optional, tag="1")] pub transaction: ::core::option::Option, } /// Request message for checking a transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct CheckTransactionRequest { /// The raw transaction data to be checked. #[prost(string, tag="1")] pub raw_transaction: ::prost::alloc::string::String, } /// Response message contains the result of the transaction check. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct CheckTransactionResponse { /// Indicates whether the transaction is valid. #[prost(bool, tag="1")] pub is_valid: bool, /// An error message if the transaction is invalid. /// Empty if the transaction is valid. #[prost(string, tag="2")] pub error_message: ::prost::alloc::string::String, } /// Enumeration for different types of transaction payloads. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum PayloadType { /// Unspecified payload type. Unspecified = 0, /// Transfer payload type. Transfer = 1, /// Bond payload type. Bond = 2, /// Sortition payload type. Sortition = 3, /// Unbond payload type. Unbond = 4, /// Withdraw payload type. Withdraw = 5, /// Batch transfer payload type. BatchTransfer = 6, } impl PayloadType { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Unspecified => "PAYLOAD_TYPE_UNSPECIFIED", Self::Transfer => "PAYLOAD_TYPE_TRANSFER", Self::Bond => "PAYLOAD_TYPE_BOND", Self::Sortition => "PAYLOAD_TYPE_SORTITION", Self::Unbond => "PAYLOAD_TYPE_UNBOND", Self::Withdraw => "PAYLOAD_TYPE_WITHDRAW", Self::BatchTransfer => "PAYLOAD_TYPE_BATCH_TRANSFER", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "PAYLOAD_TYPE_UNSPECIFIED" => Some(Self::Unspecified), "PAYLOAD_TYPE_TRANSFER" => Some(Self::Transfer), "PAYLOAD_TYPE_BOND" => Some(Self::Bond), "PAYLOAD_TYPE_SORTITION" => Some(Self::Sortition), "PAYLOAD_TYPE_UNBOND" => Some(Self::Unbond), "PAYLOAD_TYPE_WITHDRAW" => Some(Self::Withdraw), "PAYLOAD_TYPE_BATCH_TRANSFER" => Some(Self::BatchTransfer), _ => None, } } } /// Enumeration for verbosity levels when requesting transaction details. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum TransactionVerbosity { /// Request transaction data only. Data = 0, /// Request detailed transaction information. Info = 1, } impl TransactionVerbosity { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Data => "TRANSACTION_VERBOSITY_DATA", Self::Info => "TRANSACTION_VERBOSITY_INFO", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "TRANSACTION_VERBOSITY_DATA" => Some(Self::Data), "TRANSACTION_VERBOSITY_INFO" => Some(Self::Info), _ => None, } } } /// Request message for retrieving account information. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetAccountRequest { /// The address of the account to retrieve information for. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, } /// Response message contains account information. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetAccountResponse { /// Detailed information about the account. #[prost(message, optional, tag="1")] pub account: ::core::option::Option, } /// Request message for retrieving validator addresses. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetValidatorAddressesRequest { } /// Response message contains list of validator addresses. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetValidatorAddressesResponse { /// List of validator addresses. #[prost(string, repeated, tag="1")] pub addresses: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Request message for retrieving validator information by address. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetValidatorRequest { /// The address of the validator to retrieve information for. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, } /// Request message for retrieving validator information by number. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetValidatorByNumberRequest { /// The unique number of the validator to retrieve information for. #[prost(int32, tag="1")] pub number: i32, } /// Response message contains validator information. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetValidatorResponse { /// Detailed information about the validator. #[prost(message, optional, tag="1")] pub validator: ::core::option::Option, } /// Request message for retrieving public key by address. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetPublicKeyRequest { /// The address for which to retrieve the public key. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, } /// Response message contains public key information. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetPublicKeyResponse { /// The public key associated with the provided address. #[prost(string, tag="1")] pub public_key: ::prost::alloc::string::String, } /// Request message for retrieving block information based on height and verbosity level. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetBlockRequest { /// The height of the block to retrieve. #[prost(uint32, tag="1")] pub height: u32, /// The verbosity level for block information. #[prost(enumeration="BlockVerbosity", tag="2")] pub verbosity: i32, } /// Response message contains block information. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetBlockResponse { /// The height of the block. #[prost(uint32, tag="1")] pub height: u32, /// The hash of the block. #[prost(string, tag="2")] pub hash: ::prost::alloc::string::String, /// Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA. #[prost(string, tag="3")] pub data: ::prost::alloc::string::String, /// The timestamp of the block. #[prost(uint32, tag="4")] pub block_time: u32, /// Header information of the block. #[prost(message, optional, tag="5")] pub header: ::core::option::Option, /// Certificate information of the previous block. #[prost(message, optional, tag="6")] pub prev_cert: ::core::option::Option, /// List of transactions in the block, available when verbosity level is set to /// BLOCK_VERBOSITY_TRANSACTIONS. #[prost(message, repeated, tag="7")] pub txs: ::prost::alloc::vec::Vec, } /// Request message for retrieving block hash by height. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetBlockHashRequest { /// The height of the block to retrieve the hash for. #[prost(uint32, tag="1")] pub height: u32, } /// Response message contains block hash. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetBlockHashResponse { /// The hash of the block. #[prost(string, tag="1")] pub hash: ::prost::alloc::string::String, } /// Request message for retrieving block height by hash. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetBlockHeightRequest { /// The hash of the block to retrieve the height for. #[prost(string, tag="1")] pub hash: ::prost::alloc::string::String, } /// Response message contains block height. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetBlockHeightResponse { /// The height of the block. #[prost(uint32, tag="1")] pub height: u32, } /// Request message for retrieving blockchain information. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetBlockchainInfoRequest { } /// Response message contains general blockchain information. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetBlockchainInfoResponse { /// The height of the last block in the blockchain. #[prost(uint32, tag="1")] pub last_block_height: u32, /// The hash of the last block in the blockchain. #[prost(string, tag="2")] pub last_block_hash: ::prost::alloc::string::String, /// The timestamp of the last block in Unix format. #[prost(int64, tag="10")] pub last_block_time: i64, /// The total number of accounts in the blockchain. #[prost(int32, tag="3")] pub total_accounts: i32, /// The total number of validators in the blockchain. #[prost(int32, tag="4")] pub total_validators: i32, /// The number of active (not unbonded) validators in the blockchain. #[prost(int32, tag="12")] pub active_validators: i32, /// The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. #[prost(int64, tag="5")] pub total_power: i64, /// The power of the committee. #[prost(int64, tag="6")] pub committee_power: i64, /// If the blocks are subject to pruning. #[prost(bool, tag="8")] pub is_pruned: bool, /// Lowest-height block stored (only present if pruning is enabled) #[prost(uint32, tag="9")] pub pruning_height: u32, /// Indicates whether this node participates in consensus: true if at least one /// of its running validators is a member of the current committee. #[prost(bool, tag="13")] pub in_committee: bool, /// The number of validators in the current committee. #[prost(int32, tag="14")] pub committee_size: i32, /// Average availability score of validators with stake, in percentage (0-100). #[prost(double, tag="15")] pub average_score: f64, } /// Request message for retrieving committee information. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetCommitteeInfoRequest { } /// Response message contains committee information. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetCommitteeInfoResponse { /// The number of validators in the committee. #[prost(int32, tag="1")] pub committee_size: i32, /// The power of the committee. #[prost(int64, tag="2")] pub committee_power: i64, /// The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. #[prost(int64, tag="3")] pub total_power: i64, /// List of committee validators. #[prost(message, repeated, tag="4")] pub validators: ::prost::alloc::vec::Vec, /// Map of protocol versions and their percentages in the committee. #[prost(map="int32, double", tag="5")] pub protocol_versions: ::std::collections::HashMap, } /// Request message for retrieving consensus information. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetConsensusInfoRequest { } /// Response message contains consensus information. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetConsensusInfoResponse { /// The proposal of the consensus info. #[prost(message, optional, tag="1")] pub proposal: ::core::option::Option, /// List of consensus instances. #[prost(message, repeated, tag="2")] pub instances: ::prost::alloc::vec::Vec, } /// Request message for retrieving transactions in the transaction pool. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetTxPoolContentRequest { /// The type of transactions to retrieve from the transaction pool. 0 means all types. #[prost(enumeration="PayloadType", tag="1")] pub payload_type: i32, } /// Response message contains transactions in the transaction pool. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetTxPoolContentResponse { /// List of transactions currently in the pool. #[prost(message, repeated, tag="1")] pub txs: ::prost::alloc::vec::Vec, } /// Message contains information about a validator. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ValidatorInfo { /// The hash of the validator. #[prost(string, tag="1")] pub hash: ::prost::alloc::string::String, /// The serialized data of the validator. #[prost(string, tag="2")] pub data: ::prost::alloc::string::String, /// The public key of the validator. #[prost(string, tag="3")] pub public_key: ::prost::alloc::string::String, /// The unique number assigned to the validator. #[prost(int32, tag="4")] pub number: i32, /// The stake of the validator in NanoPAC. #[prost(int64, tag="5")] pub stake: i64, /// The height at which the validator last bonded. #[prost(uint32, tag="6")] pub last_bonding_height: u32, /// The height at which the validator last participated in sortition. #[prost(uint32, tag="7")] pub last_sortition_height: u32, /// The height at which the validator will unbond. #[prost(uint32, tag="8")] pub unbonding_height: u32, /// The address of the validator. #[prost(string, tag="9")] pub address: ::prost::alloc::string::String, /// The availability score of the validator. #[prost(double, tag="10")] pub availability_score: f64, /// The protocol version of the validator. #[prost(int32, tag="11")] pub protocol_version: i32, /// Whether the validator is delegated. #[prost(bool, tag="12")] pub is_delegated: bool, /// The address of the stake owner of the validator. #[prost(string, tag="13")] pub delegate_owner: ::prost::alloc::string::String, /// The share of the stake owner of the validator. #[prost(int64, tag="14")] pub delegate_share: i64, /// The expiry of the stake owner of the validator. #[prost(uint32, tag="15")] pub delegate_expiry: u32, } /// Message contains information about an account. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct AccountInfo { /// The hash of the account. #[prost(string, tag="1")] pub hash: ::prost::alloc::string::String, /// The serialized data of the account. #[prost(string, tag="2")] pub data: ::prost::alloc::string::String, /// The unique number assigned to the account. #[prost(int32, tag="3")] pub number: i32, /// The balance of the account in NanoPAC. #[prost(int64, tag="4")] pub balance: i64, /// The address of the account. #[prost(string, tag="5")] pub address: ::prost::alloc::string::String, } /// Message contains information about the header of a block. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct BlockHeaderInfo { /// The version of the block. #[prost(int32, tag="1")] pub version: i32, /// The hash of the previous block. #[prost(string, tag="2")] pub prev_block_hash: ::prost::alloc::string::String, /// The state root hash of the blockchain. #[prost(string, tag="3")] pub state_root: ::prost::alloc::string::String, /// The sortition seed of the block. #[prost(string, tag="4")] pub sortition_seed: ::prost::alloc::string::String, /// The address of the proposer of the block. #[prost(string, tag="5")] pub proposer_address: ::prost::alloc::string::String, } /// Message contains information about a certificate. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct CertificateInfo { /// The hash of the certificate. #[prost(string, tag="1")] pub hash: ::prost::alloc::string::String, /// The round of the certificate. #[prost(int32, tag="2")] pub round: i32, /// List of committers in the certificate. #[prost(int32, repeated, tag="3")] pub committers: ::prost::alloc::vec::Vec, /// List of absentees in the certificate. #[prost(int32, repeated, tag="4")] pub absentees: ::prost::alloc::vec::Vec, /// The signature of the certificate. #[prost(string, tag="5")] pub signature: ::prost::alloc::string::String, } /// Message contains information about a vote. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct VoteInfo { /// The type of the vote. #[prost(enumeration="VoteType", tag="1")] pub r#type: i32, /// The address of the voter. #[prost(string, tag="2")] pub voter: ::prost::alloc::string::String, /// The hash of the block being voted on. #[prost(string, tag="3")] pub block_hash: ::prost::alloc::string::String, /// The consensus round of the vote. #[prost(int32, tag="4")] pub round: i32, /// The change-proposer round of the vote. #[prost(int32, tag="5")] pub cp_round: i32, /// The change-proposer value of the vote. #[prost(int32, tag="6")] pub cp_value: i32, } /// Message contains information about a consensus instance. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ConsensusInfo { /// The address of the consensus instance. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, /// Indicates whether the consensus instance is active and part of the committee. #[prost(bool, tag="2")] pub active: bool, /// The height of the consensus instance. #[prost(uint32, tag="3")] pub height: u32, /// The round of the consensus instance. #[prost(int32, tag="4")] pub round: i32, /// List of votes in the consensus instance. #[prost(message, repeated, tag="5")] pub votes: ::prost::alloc::vec::Vec, } /// Message contains information about a proposal. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct ProposalInfo { /// The height of the proposal. #[prost(uint32, tag="1")] pub height: u32, /// The round of the proposal. #[prost(int32, tag="2")] pub round: i32, /// The block data of the proposal. #[prost(string, tag="3")] pub block_data: ::prost::alloc::string::String, /// The signature of the proposal, signed by the proposer. #[prost(string, tag="4")] pub signature: ::prost::alloc::string::String, } /// Enumeration for verbosity levels when requesting block information. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum BlockVerbosity { /// Request only block data. Data = 0, /// Request block information and transaction IDs. Info = 1, /// Request block information and detailed transaction data. Transactions = 2, } impl BlockVerbosity { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Data => "BLOCK_VERBOSITY_DATA", Self::Info => "BLOCK_VERBOSITY_INFO", Self::Transactions => "BLOCK_VERBOSITY_TRANSACTIONS", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "BLOCK_VERBOSITY_DATA" => Some(Self::Data), "BLOCK_VERBOSITY_INFO" => Some(Self::Info), "BLOCK_VERBOSITY_TRANSACTIONS" => Some(Self::Transactions), _ => None, } } } /// Enumeration for types of votes. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum VoteType { /// Unspecified vote type. Unspecified = 0, /// Prepare vote type. Prepare = 1, /// Precommit vote type. Precommit = 2, /// Change-proposer:pre-vote vote type. CpPreVote = 3, /// Change-proposer:main-vote vote type. CpMainVote = 4, /// Change-proposer:decided vote type. CpDecided = 5, } impl VoteType { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Unspecified => "VOTE_TYPE_UNSPECIFIED", Self::Prepare => "VOTE_TYPE_PREPARE", Self::Precommit => "VOTE_TYPE_PRECOMMIT", Self::CpPreVote => "VOTE_TYPE_CP_PRE_VOTE", Self::CpMainVote => "VOTE_TYPE_CP_MAIN_VOTE", Self::CpDecided => "VOTE_TYPE_CP_DECIDED", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "VOTE_TYPE_UNSPECIFIED" => Some(Self::Unspecified), "VOTE_TYPE_PREPARE" => Some(Self::Prepare), "VOTE_TYPE_PRECOMMIT" => Some(Self::Precommit), "VOTE_TYPE_CP_PRE_VOTE" => Some(Self::CpPreVote), "VOTE_TYPE_CP_MAIN_VOTE" => Some(Self::CpMainVote), "VOTE_TYPE_CP_DECIDED" => Some(Self::CpDecided), _ => None, } } } /// Request message for retrieving overall network information. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetNetworkInfoRequest { } /// Response message contains information about the overall network. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetNetworkInfoResponse { /// Name of the P2P network. #[prost(string, tag="1")] pub network_name: ::prost::alloc::string::String, /// Number of connected peers. #[prost(uint32, tag="2")] pub connected_peers_count: u32, /// Metrics related to node activity. #[prost(message, optional, tag="4")] pub metric_info: ::core::option::Option, } /// Request message for listing peers. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct ListPeersRequest { /// If true, includes disconnected peers (default: connected peers only). #[prost(bool, tag="1")] pub include_disconnected: bool, } /// Response message for listing peers. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListPeersResponse { /// List of peers. #[prost(message, repeated, tag="1")] pub peers: ::prost::alloc::vec::Vec, } /// Request message for retrieving information of the node. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetNodeInfoRequest { } /// Response message contains information about a specific node in the network. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetNodeInfoResponse { /// Moniker or Human-readable name identifying this node in the network. #[prost(string, tag="1")] pub moniker: ::prost::alloc::string::String, /// Version and agent details of the node. #[prost(string, tag="2")] pub agent: ::prost::alloc::string::String, /// Peer ID of the node. #[prost(string, tag="3")] pub peer_id: ::prost::alloc::string::String, /// Unix timestamp when the node was started (UTC). #[prost(uint64, tag="4")] pub started_at: u64, /// Reachability status of the node. #[prost(string, tag="5")] pub reachability: ::prost::alloc::string::String, /// Bitfield representing the services provided by the node. #[prost(int32, tag="6")] pub services: i32, /// Names of services provided by the node. #[prost(string, tag="7")] pub services_names: ::prost::alloc::string::String, /// List of addresses associated with the node. #[prost(string, repeated, tag="8")] pub local_addrs: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// List of protocols supported by the node. #[prost(string, repeated, tag="9")] pub protocols: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Offset between the node's clock and the network's clock (in seconds). #[prost(double, tag="13")] pub clock_offset: f64, /// Information about the node's connections. #[prost(message, optional, tag="14")] pub connection_info: ::core::option::Option, /// List of active ZeroMQ publishers. #[prost(message, repeated, tag="15")] pub zmq_publishers: ::prost::alloc::vec::Vec, /// Current Unix timestamp of the node (UTC). #[prost(uint64, tag="16")] pub current_time: u64, /// Name of the P2P network. #[prost(string, tag="17")] pub network_name: ::prost::alloc::string::String, } /// ZMQPublisherInfo contains information about a ZeroMQ publisher. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct ZmqPublisherInfo { /// The topic associated with the publisher. #[prost(string, tag="1")] pub topic: ::prost::alloc::string::String, /// The address of the publisher. #[prost(string, tag="2")] pub address: ::prost::alloc::string::String, /// The high-water mark (HWM) for the publisher, indicating the /// maximum number of messages to queue before dropping older ones. #[prost(int32, tag="3")] pub hwm: i32, } /// PeerInfo contains information about a peer in the network. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PeerInfo { /// Current status of the peer (e.g., connected, disconnected). #[prost(int32, tag="1")] pub status: i32, /// Moniker or Human-Readable name of the peer. #[prost(string, tag="2")] pub moniker: ::prost::alloc::string::String, /// Version and agent details of the peer. #[prost(string, tag="3")] pub agent: ::prost::alloc::string::String, /// Peer ID of the peer in P2P network. #[prost(string, tag="4")] pub peer_id: ::prost::alloc::string::String, /// List of consensus keys used by the peer. #[prost(string, repeated, tag="5")] pub consensus_keys: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// List of consensus addresses used by the peer. #[prost(string, repeated, tag="6")] pub consensus_addresses: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Bitfield representing the services provided by the peer. #[prost(uint32, tag="7")] pub services: u32, /// Hash of the last block the peer knows. #[prost(string, tag="8")] pub last_block_hash: ::prost::alloc::string::String, /// Blockchain height of the peer. #[prost(uint32, tag="9")] pub height: u32, /// Unix timestamp of the last bundle sent to the peer (UTC). #[prost(int64, tag="10")] pub last_sent: i64, /// Unix timestamp of the last bundle received from the peer (UTC). #[prost(int64, tag="11")] pub last_received: i64, /// Network address of the peer. #[prost(string, tag="12")] pub address: ::prost::alloc::string::String, /// Connection direction (e.g., inbound, outbound). #[prost(enumeration="Direction", tag="13")] pub direction: i32, /// List of protocols supported by the peer. #[prost(string, repeated, tag="14")] pub protocols: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Total download sessions with the peer. #[prost(int32, tag="15")] pub total_sessions: i32, /// Completed download sessions with the peer. #[prost(int32, tag="16")] pub completed_sessions: i32, /// Metrics related to peer activity. #[prost(message, optional, tag="17")] pub metric_info: ::core::option::Option, /// Whether the hello message was sent from the outbound connection. #[prost(bool, tag="18")] pub outbound_hello_sent: bool, } /// ConnectionInfo contains information about the node's connections. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct ConnectionInfo { /// Total number of connections. #[prost(uint64, tag="1")] pub connections: u64, /// Number of inbound connections. #[prost(uint64, tag="2")] pub inbound_connections: u64, /// Number of outbound connections. #[prost(uint64, tag="3")] pub outbound_connections: u64, } /// MetricInfo contains metrics data regarding network activity. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MetricInfo { /// Total number of invalid bundles. #[prost(message, optional, tag="1")] pub total_invalid: ::core::option::Option, /// Total number of bundles sent. #[prost(message, optional, tag="2")] pub total_sent: ::core::option::Option, /// Total number of bundles received. #[prost(message, optional, tag="3")] pub total_received: ::core::option::Option, /// Number of sent bundles categorized by message type. #[prost(map="int32, message", tag="4")] pub message_sent: ::std::collections::HashMap, /// Number of received bundles categorized by message type. #[prost(map="int32, message", tag="5")] pub message_received: ::std::collections::HashMap, } /// CounterInfo holds counter data regarding byte and bundle counts. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct CounterInfo { /// Total number of bytes. #[prost(uint64, tag="1")] pub bytes: u64, /// Total number of bundles. #[prost(uint64, tag="2")] pub bundles: u64, } /// Request message for ping - intentionally empty for measuring round-trip time. /// /// Empty request payload for measuring round-trip time #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct PingRequest { } /// Response message for ping - intentionally empty for measuring round-trip time. /// /// Empty response payload for measuring round-trip time #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct PingResponse { } /// Direction represents the connection direction between peers. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum Direction { /// Unknown direction (default value). Unknown = 0, /// Inbound connection - peer connected to us. Inbound = 1, /// Outbound connection - we connected to peer. Outbound = 2, } impl Direction { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Unknown => "DIRECTION_UNKNOWN", Self::Inbound => "DIRECTION_INBOUND", Self::Outbound => "DIRECTION_OUTBOUND", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "DIRECTION_UNKNOWN" => Some(Self::Unknown), "DIRECTION_INBOUND" => Some(Self::Inbound), "DIRECTION_OUTBOUND" => Some(Self::Outbound), _ => None, } } } /// Request message for signing a message with a private key. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignMessageWithPrivateKeyRequest { /// The private key to sign the message. #[prost(string, tag="1")] pub private_key: ::prost::alloc::string::String, /// The message content to be signed. #[prost(string, tag="2")] pub message: ::prost::alloc::string::String, } /// Response message contains the signature generated from the message. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignMessageWithPrivateKeyResponse { /// The resulting signature in hexadecimal format. #[prost(string, tag="1")] pub signature: ::prost::alloc::string::String, } /// Request message for verifying a message signature. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct VerifyMessageRequest { /// The original message content that was signed. #[prost(string, tag="1")] pub message: ::prost::alloc::string::String, /// The signature to verify in hexadecimal format. #[prost(string, tag="2")] pub signature: ::prost::alloc::string::String, /// The public key of the signer. #[prost(string, tag="3")] pub public_key: ::prost::alloc::string::String, } /// Response message contains the verification result. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct VerifyMessageResponse { /// Boolean indicating whether the signature is valid for the given message and public key. #[prost(bool, tag="1")] pub is_valid: bool, } /// Request message for aggregating multiple BLS public keys. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PublicKeyAggregationRequest { /// List of BLS public keys to be aggregated. #[prost(string, repeated, tag="1")] pub public_keys: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Response message contains the aggregated BLS public key result. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct PublicKeyAggregationResponse { /// The aggregated BLS public key. #[prost(string, tag="1")] pub public_key: ::prost::alloc::string::String, /// The blockchain address derived from the aggregated public key. #[prost(string, tag="2")] pub address: ::prost::alloc::string::String, } /// Request message for aggregating multiple BLS signatures. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignatureAggregationRequest { /// List of BLS signatures to be aggregated. #[prost(string, repeated, tag="1")] pub signatures: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Response message contains the aggregated BLS signature. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignatureAggregationResponse { /// The aggregated BLS signature in hexadecimal format. #[prost(string, tag="1")] pub signature: ::prost::alloc::string::String, } /// AddressInfo contains detailed information about a wallet address. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct AddressInfo { /// The address string. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, /// The public key associated with the address. #[prost(string, tag="2")] pub public_key: ::prost::alloc::string::String, /// A human-readable label associated with the address. #[prost(string, tag="3")] pub label: ::prost::alloc::string::String, /// The Hierarchical Deterministic (HD) path of the address within the wallet. #[prost(string, tag="4")] pub path: ::prost::alloc::string::String, } /// Request message for generating a new wallet address. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetNewAddressRequest { /// The name of the wallet to generate a new address. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The type of address to generate. #[prost(enumeration="AddressType", tag="2")] pub address_type: i32, /// A label for the new address. #[prost(string, tag="3")] pub label: ::prost::alloc::string::String, /// Password for the new address. It's required when address_type is Ed25519 type. #[prost(string, tag="4")] pub password: ::prost::alloc::string::String, } /// Response message contains newly generated address information. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetNewAddressResponse { /// The name of the wallet where address was generated. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Detailed information about the new address. #[prost(message, optional, tag="2")] pub addr: ::core::option::Option, } /// Request message for restoring a wallet from mnemonic (seed phrase). #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct RestoreWalletRequest { /// The name for the restored wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The mnemonic (seed phrase) for wallet recovery. #[prost(string, tag="2")] pub mnemonic: ::prost::alloc::string::String, /// Password to secure the restored wallet. #[prost(string, tag="3")] pub password: ::prost::alloc::string::String, } /// Response message confirming wallet restoration. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct RestoreWalletResponse { /// The name of the restored wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Request message for creating a new wallet. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct CreateWalletRequest { /// The name for the new wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Password to secure the new wallet. #[prost(string, tag="2")] pub password: ::prost::alloc::string::String, } /// Response message contains wallet recovery mnemonic (seed phrase). #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct CreateWalletResponse { /// The name for the new wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The mnemonic (seed phrase) for wallet recovery. #[prost(string, tag="2")] pub mnemonic: ::prost::alloc::string::String, } /// Request message for loading an existing wallet. /// Deprecated: It will be removed in a future version. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct LoadWalletRequest { /// The name of the wallet to load. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Response message confirming wallet loaded. /// Deprecated: It will be removed in a future version. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct LoadWalletResponse { /// The name of the loaded wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Request message for unloading a wallet. /// Deprecated: It will be removed in a future version. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct UnloadWalletRequest { /// The name of the wallet to unload. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Response message confirming wallet unloading. /// Deprecated: It will be removed in a future version. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct UnloadWalletResponse { /// The name of the unloaded wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Request message for obtaining the validator address associated with a public key. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetValidatorAddressRequest { /// The public key of the validator. #[prost(string, tag="1")] pub public_key: ::prost::alloc::string::String, } /// Response message containing the validator address corresponding to a public key. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetValidatorAddressResponse { /// The validator address associated with the public key. #[prost(string, tag="1")] pub address: ::prost::alloc::string::String, } /// Request message for signing a raw transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignRawTransactionRequest { /// The name of the wallet used for signing. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The raw transaction data to be signed. #[prost(string, tag="2")] pub raw_transaction: ::prost::alloc::string::String, /// Wallet password required for signing. #[prost(string, tag="3")] pub password: ::prost::alloc::string::String, } /// Response message contains the transaction ID and signed raw transaction. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignRawTransactionResponse { /// The ID of the signed transaction. #[prost(string, tag="1")] pub transaction_id: ::prost::alloc::string::String, /// The signed raw transaction data. #[prost(string, tag="2")] pub signed_raw_transaction: ::prost::alloc::string::String, } /// Request message for obtaining the total available balance of a wallet. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetTotalBalanceRequest { /// The name of the wallet to get the total balance. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Response message contains the total available balance of the wallet. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetTotalBalanceResponse { /// The name of the queried wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The total balance of the wallet in NanoPAC. #[prost(int64, tag="2")] pub total_balance: i64, } /// Request message to sign an arbitrary message. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignMessageRequest { /// The name of the wallet to sign with. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Wallet password required for signing. #[prost(string, tag="2")] pub password: ::prost::alloc::string::String, /// The address whose private key should be used for signing the message. #[prost(string, tag="3")] pub address: ::prost::alloc::string::String, /// The arbitrary message to be signed. #[prost(string, tag="4")] pub message: ::prost::alloc::string::String, } /// Response message contains message signature. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SignMessageResponse { /// The signature in hexadecimal format. #[prost(string, tag="1")] pub signature: ::prost::alloc::string::String, } /// Request message for obtaining the total stake of a wallet. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetTotalStakeRequest { /// The name of the wallet to get the total stake. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Response message contains the total stake of the wallet. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetTotalStakeResponse { /// The name of the queried wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The total stake amount in NanoPAC. #[prost(int64, tag="2")] pub total_stake: i64, } /// Request message for getting address information. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetAddressInfoRequest { /// The name of the wallet containing the address. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The address to query. #[prost(string, tag="2")] pub address: ::prost::alloc::string::String, } /// Response message contains address details. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetAddressInfoResponse { /// The name of the wallet containing the address. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Detailed information about the address. #[prost(message, optional, tag="2")] pub addr: ::core::option::Option, } /// Request message for setting address label. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SetAddressLabelRequest { /// The name of the wallet containing the address. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Wallet password required for modification. #[prost(string, tag="2")] pub password: ::prost::alloc::string::String, /// The address to label. #[prost(string, tag="3")] pub address: ::prost::alloc::string::String, /// The new label for the address. #[prost(string, tag="4")] pub label: ::prost::alloc::string::String, } /// Response message for updated address label. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SetAddressLabelResponse { /// The name of the wallet where the address label was updated. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The address where the label was updated. #[prost(string, tag="2")] pub address: ::prost::alloc::string::String, /// The new label for the address. #[prost(string, tag="3")] pub label: ::prost::alloc::string::String, } /// Request message for listing wallets. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct ListWalletsRequest { } /// Response message contains wallet names. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct ListWalletsResponse { /// Array of wallet names. #[prost(string, repeated, tag="1")] pub wallets: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Request message for getting wallet information. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetWalletInfoRequest { /// The name of the wallet to query. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Response message contains wallet details. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetWalletInfoResponse { /// The name of the wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The wallet format version. #[prost(int32, tag="2")] pub version: i32, /// The network the wallet is connected to (e.g., mainnet, testnet). #[prost(string, tag="3")] pub network: ::prost::alloc::string::String, /// Indicates if the wallet is encrypted. #[prost(bool, tag="4")] pub encrypted: bool, /// A unique identifier of the wallet. #[prost(string, tag="5")] pub uuid: ::prost::alloc::string::String, /// Unix timestamp of wallet creation. #[prost(int64, tag="6")] pub created_at: i64, /// The default fee of the wallet. #[prost(int64, tag="7")] pub default_fee: i64, /// The storage driver used by the wallet (e.g., SQLite, Legacy JSON ). #[prost(string, tag="8")] pub driver: ::prost::alloc::string::String, /// Path to the wallet file or storage location. #[prost(string, tag="9")] pub path: ::prost::alloc::string::String, } /// Request message for listing wallet addresses. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct ListAddressesRequest { /// The name of the queried wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Filter addresses by their types. If empty, all address types are included. #[prost(enumeration="AddressType", repeated, tag="2")] pub address_types: ::prost::alloc::vec::Vec, } /// Response message contains wallet addresses. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListAddressesResponse { /// The name of the queried wallet. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// List of all addresses in the wallet with their details. #[prost(message, repeated, tag="2")] pub addrs: ::prost::alloc::vec::Vec, } /// Request message for updating wallet password. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct UpdatePasswordRequest { /// The name of the wallet whose password will be updated. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The current wallet password. #[prost(string, tag="2")] pub old_password: ::prost::alloc::string::String, /// The new wallet password. #[prost(string, tag="3")] pub new_password: ::prost::alloc::string::String, } /// Response message confirming wallet password update. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct UpdatePasswordResponse { /// The name of the wallet whose password was updated. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// WalletTransactionInfo contains information about a transaction in a wallet. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct WalletTransactionInfo { /// A sequence number for the transaction in the wallet. #[prost(int64, tag="1")] pub no: i64, /// The unique ID of the transaction. #[prost(string, tag="2")] pub tx_id: ::prost::alloc::string::String, /// The sender's address. #[prost(string, tag="3")] pub sender: ::prost::alloc::string::String, /// The receiver's address. #[prost(string, tag="4")] pub receiver: ::prost::alloc::string::String, /// The direction of the transaction relative to the wallet. #[prost(enumeration="TxDirection", tag="5")] pub direction: i32, /// The amount involved in the transaction in NanoPAC. #[prost(int64, tag="6")] pub amount: i64, /// The transaction fee in NanoPAC. #[prost(int64, tag="7")] pub fee: i64, /// A memo string for the transaction. #[prost(string, tag="8")] pub memo: ::prost::alloc::string::String, /// The current status of the transaction. #[prost(enumeration="TransactionStatus", tag="9")] pub status: i32, /// The block height containing the transaction. #[prost(uint32, tag="10")] pub block_height: u32, /// The type of transaction payload. #[prost(enumeration="PayloadType", tag="11")] pub payload_type: i32, /// The raw transaction data. #[prost(bytes="vec", tag="12")] pub data: ::prost::alloc::vec::Vec, /// A comment associated with the transaction in the wallet. #[prost(string, tag="13")] pub comment: ::prost::alloc::string::String, /// Unix timestamp of when the transaction was created. #[prost(int64, tag="14")] pub created_at: i64, /// Unix timestamp of when the transaction was last updated. #[prost(int64, tag="15")] pub updated_at: i64, } /// Request message for listing transactions of a wallet, optionally filtered by a specific address. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct ListTransactionsRequest { /// The name of the wallet to query transactions for. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Optional: The address to filter transactions. /// If empty or set to '*', transactions for all addresses in the wallet are included. #[prost(string, tag="2")] pub address: ::prost::alloc::string::String, /// Filter transactions by direction relative to the wallet. /// Defaults to any direction if not set. #[prost(enumeration="TxDirection", tag="3")] pub direction: i32, /// Optional: The maximum number of transactions to return. /// Defaults to 10 if not set. #[prost(int32, tag="4")] pub count: i32, /// Optional: The number of transactions to skip (for pagination). /// Defaults to 0 if not set. #[prost(int32, tag="5")] pub skip: i32, } /// Response message containing a list of transactions. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListTransactionsResponse { /// The name of the wallet queried. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// List of transactions for the wallet, filtered by the specified address if provided. #[prost(message, repeated, tag="2")] pub txs: ::prost::alloc::vec::Vec, } /// Request message for setting default fee. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SetDefaultFeeRequest { /// The name of the wallet to set the default fee. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// The default fee amount in NanoPAC. #[prost(int64, tag="2")] pub amount: i64, } /// Response message for updated default fee. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct SetDefaultFeeResponse { /// The name of the wallet where the default fee was updated. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, } /// Request message for getting mnemonic. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetMnemonicRequest { /// The name of the wallet to get the mnemonic. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Wallet password. #[prost(string, tag="2")] pub password: ::prost::alloc::string::String, } /// Response message contains mnemonic. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetMnemonicResponse { /// The mnemonic (seed phrase). #[prost(string, tag="1")] pub mnemonic: ::prost::alloc::string::String, } /// Request message for getting private key. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetPrivateKeyRequest { /// The name of the wallet containing the address. #[prost(string, tag="1")] pub wallet_name: ::prost::alloc::string::String, /// Wallet password. #[prost(string, tag="2")] pub password: ::prost::alloc::string::String, /// The address to get the private key. #[prost(string, tag="3")] pub address: ::prost::alloc::string::String, } /// Response message contains private key. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct GetPrivateKeyResponse { /// The private key in hexadecimal format. #[prost(string, tag="1")] pub private_key: ::prost::alloc::string::String, } /// AddressType defines different types of blockchain addresses. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum AddressType { /// Treasury address type. /// Should not be used to generate new addresses. Treasury = 0, /// Validator address type used for validator nodes. Validator = 1, /// Account address type with BLS signature scheme. BlsAccount = 2, /// Account address type with Ed25519 signature scheme. /// Note: Generating a new Ed25519 address requires the wallet password. Ed25519Account = 3, } impl AddressType { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Treasury => "ADDRESS_TYPE_TREASURY", Self::Validator => "ADDRESS_TYPE_VALIDATOR", Self::BlsAccount => "ADDRESS_TYPE_BLS_ACCOUNT", Self::Ed25519Account => "ADDRESS_TYPE_ED25519_ACCOUNT", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "ADDRESS_TYPE_TREASURY" => Some(Self::Treasury), "ADDRESS_TYPE_VALIDATOR" => Some(Self::Validator), "ADDRESS_TYPE_BLS_ACCOUNT" => Some(Self::BlsAccount), "ADDRESS_TYPE_ED25519_ACCOUNT" => Some(Self::Ed25519Account), _ => None, } } } /// TxDirection indicates the direction of a transaction relative to the wallet. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum TxDirection { /// include both incoming and outgoing transactions. Any = 0, /// Include only incoming transactions where the wallet receives funds. Incoming = 1, /// Include only outgoing transactions where the wallet sends funds. Outgoing = 2, } impl TxDirection { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Any => "TX_DIRECTION_ANY", Self::Incoming => "TX_DIRECTION_INCOMING", Self::Outgoing => "TX_DIRECTION_OUTGOING", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "TX_DIRECTION_ANY" => Some(Self::Any), "TX_DIRECTION_INCOMING" => Some(Self::Incoming), "TX_DIRECTION_OUTGOING" => Some(Self::Outgoing), _ => None, } } } /// TransactionStatus defines the status of a transaction. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum TransactionStatus { /// Pending status for transactions in the mempool. Pending = 0, /// Confirmed status for transactions included in a block. Confirmed = 1, /// Failed status for transactions that were not successful. Failed = -1, } impl TransactionStatus { /// String value of the enum field names used in the ProtoBuf definition. /// /// The values are not transformed in any way and thus are considered stable /// (if the ProtoBuf definition does not change) and safe for programmatic use. pub fn as_str_name(&self) -> &'static str { match self { Self::Pending => "TRANSACTION_STATUS_PENDING", Self::Confirmed => "TRANSACTION_STATUS_CONFIRMED", Self::Failed => "TRANSACTION_STATUS_FAILED", } } /// Creates an enum from field names used in the ProtoBuf definition. pub fn from_str_name(value: &str) -> ::core::option::Option { match value { "TRANSACTION_STATUS_PENDING" => Some(Self::Pending), "TRANSACTION_STATUS_CONFIRMED" => Some(Self::Confirmed), "TRANSACTION_STATUS_FAILED" => Some(Self::Failed), _ => None, } } } include!("pactus.serde.rs"); include!("pactus.tonic.rs"); // @@protoc_insertion_point(module) ================================================ FILE: www/grpc/gen/rust/pactus.serde.rs ================================================ // @generated impl serde::Serialize for AccountInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.hash.is_empty() { len += 1; } if !self.data.is_empty() { len += 1; } if self.number != 0 { len += 1; } if self.balance != 0 { len += 1; } if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.AccountInfo", len)?; if !self.hash.is_empty() { struct_ser.serialize_field("hash", &self.hash)?; } if !self.data.is_empty() { struct_ser.serialize_field("data", &self.data)?; } if self.number != 0 { struct_ser.serialize_field("number", &self.number)?; } if self.balance != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("balance", ToString::to_string(&self.balance).as_str())?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for AccountInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "hash", "data", "number", "balance", "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Hash, Data, Number, Balance, Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "hash" => Ok(GeneratedField::Hash), "data" => Ok(GeneratedField::Data), "number" => Ok(GeneratedField::Number), "balance" => Ok(GeneratedField::Balance), "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = AccountInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.AccountInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut hash__ = None; let mut data__ = None; let mut number__ = None; let mut balance__ = None; let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Hash => { if hash__.is_some() { return Err(serde::de::Error::duplicate_field("hash")); } hash__ = Some(map_.next_value()?); } GeneratedField::Data => { if data__.is_some() { return Err(serde::de::Error::duplicate_field("data")); } data__ = Some(map_.next_value()?); } GeneratedField::Number => { if number__.is_some() { return Err(serde::de::Error::duplicate_field("number")); } number__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Balance => { if balance__.is_some() { return Err(serde::de::Error::duplicate_field("balance")); } balance__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(AccountInfo { hash: hash__.unwrap_or_default(), data: data__.unwrap_or_default(), number: number__.unwrap_or_default(), balance: balance__.unwrap_or_default(), address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.AccountInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for AddressInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } if !self.public_key.is_empty() { len += 1; } if !self.label.is_empty() { len += 1; } if !self.path.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.AddressInfo", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } if !self.label.is_empty() { struct_ser.serialize_field("label", &self.label)?; } if !self.path.is_empty() { struct_ser.serialize_field("path", &self.path)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for AddressInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", "public_key", "publicKey", "label", "path", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, PublicKey, Label, Path, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), "label" => Ok(GeneratedField::Label), "path" => Ok(GeneratedField::Path), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = AddressInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.AddressInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; let mut public_key__ = None; let mut label__ = None; let mut path__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } GeneratedField::Label => { if label__.is_some() { return Err(serde::de::Error::duplicate_field("label")); } label__ = Some(map_.next_value()?); } GeneratedField::Path => { if path__.is_some() { return Err(serde::de::Error::duplicate_field("path")); } path__ = Some(map_.next_value()?); } } } Ok(AddressInfo { address: address__.unwrap_or_default(), public_key: public_key__.unwrap_or_default(), label: label__.unwrap_or_default(), path: path__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.AddressInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for AddressType { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Treasury => "ADDRESS_TYPE_TREASURY", Self::Validator => "ADDRESS_TYPE_VALIDATOR", Self::BlsAccount => "ADDRESS_TYPE_BLS_ACCOUNT", Self::Ed25519Account => "ADDRESS_TYPE_ED25519_ACCOUNT", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for AddressType { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "ADDRESS_TYPE_TREASURY", "ADDRESS_TYPE_VALIDATOR", "ADDRESS_TYPE_BLS_ACCOUNT", "ADDRESS_TYPE_ED25519_ACCOUNT", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = AddressType; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "ADDRESS_TYPE_TREASURY" => Ok(AddressType::Treasury), "ADDRESS_TYPE_VALIDATOR" => Ok(AddressType::Validator), "ADDRESS_TYPE_BLS_ACCOUNT" => Ok(AddressType::BlsAccount), "ADDRESS_TYPE_ED25519_ACCOUNT" => Ok(AddressType::Ed25519Account), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for BlockHeaderInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.version != 0 { len += 1; } if !self.prev_block_hash.is_empty() { len += 1; } if !self.state_root.is_empty() { len += 1; } if !self.sortition_seed.is_empty() { len += 1; } if !self.proposer_address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.BlockHeaderInfo", len)?; if self.version != 0 { struct_ser.serialize_field("version", &self.version)?; } if !self.prev_block_hash.is_empty() { struct_ser.serialize_field("prevBlockHash", &self.prev_block_hash)?; } if !self.state_root.is_empty() { struct_ser.serialize_field("stateRoot", &self.state_root)?; } if !self.sortition_seed.is_empty() { struct_ser.serialize_field("sortitionSeed", &self.sortition_seed)?; } if !self.proposer_address.is_empty() { struct_ser.serialize_field("proposerAddress", &self.proposer_address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for BlockHeaderInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "version", "prev_block_hash", "prevBlockHash", "state_root", "stateRoot", "sortition_seed", "sortitionSeed", "proposer_address", "proposerAddress", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Version, PrevBlockHash, StateRoot, SortitionSeed, ProposerAddress, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "version" => Ok(GeneratedField::Version), "prevBlockHash" | "prev_block_hash" => Ok(GeneratedField::PrevBlockHash), "stateRoot" | "state_root" => Ok(GeneratedField::StateRoot), "sortitionSeed" | "sortition_seed" => Ok(GeneratedField::SortitionSeed), "proposerAddress" | "proposer_address" => Ok(GeneratedField::ProposerAddress), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = BlockHeaderInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.BlockHeaderInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut version__ = None; let mut prev_block_hash__ = None; let mut state_root__ = None; let mut sortition_seed__ = None; let mut proposer_address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Version => { if version__.is_some() { return Err(serde::de::Error::duplicate_field("version")); } version__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::PrevBlockHash => { if prev_block_hash__.is_some() { return Err(serde::de::Error::duplicate_field("prevBlockHash")); } prev_block_hash__ = Some(map_.next_value()?); } GeneratedField::StateRoot => { if state_root__.is_some() { return Err(serde::de::Error::duplicate_field("stateRoot")); } state_root__ = Some(map_.next_value()?); } GeneratedField::SortitionSeed => { if sortition_seed__.is_some() { return Err(serde::de::Error::duplicate_field("sortitionSeed")); } sortition_seed__ = Some(map_.next_value()?); } GeneratedField::ProposerAddress => { if proposer_address__.is_some() { return Err(serde::de::Error::duplicate_field("proposerAddress")); } proposer_address__ = Some(map_.next_value()?); } } } Ok(BlockHeaderInfo { version: version__.unwrap_or_default(), prev_block_hash: prev_block_hash__.unwrap_or_default(), state_root: state_root__.unwrap_or_default(), sortition_seed: sortition_seed__.unwrap_or_default(), proposer_address: proposer_address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.BlockHeaderInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for BlockVerbosity { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Data => "BLOCK_VERBOSITY_DATA", Self::Info => "BLOCK_VERBOSITY_INFO", Self::Transactions => "BLOCK_VERBOSITY_TRANSACTIONS", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for BlockVerbosity { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "BLOCK_VERBOSITY_DATA", "BLOCK_VERBOSITY_INFO", "BLOCK_VERBOSITY_TRANSACTIONS", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = BlockVerbosity; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "BLOCK_VERBOSITY_DATA" => Ok(BlockVerbosity::Data), "BLOCK_VERBOSITY_INFO" => Ok(BlockVerbosity::Info), "BLOCK_VERBOSITY_TRANSACTIONS" => Ok(BlockVerbosity::Transactions), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for BroadcastTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.signed_raw_transaction.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.BroadcastTransactionRequest", len)?; if !self.signed_raw_transaction.is_empty() { struct_ser.serialize_field("signedRawTransaction", &self.signed_raw_transaction)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for BroadcastTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "signed_raw_transaction", "signedRawTransaction", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { SignedRawTransaction, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "signedRawTransaction" | "signed_raw_transaction" => Ok(GeneratedField::SignedRawTransaction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = BroadcastTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.BroadcastTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut signed_raw_transaction__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::SignedRawTransaction => { if signed_raw_transaction__.is_some() { return Err(serde::de::Error::duplicate_field("signedRawTransaction")); } signed_raw_transaction__ = Some(map_.next_value()?); } } } Ok(BroadcastTransactionRequest { signed_raw_transaction: signed_raw_transaction__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.BroadcastTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for BroadcastTransactionResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.id.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.BroadcastTransactionResponse", len)?; if !self.id.is_empty() { struct_ser.serialize_field("id", &self.id)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for BroadcastTransactionResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "id", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Id, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "id" => Ok(GeneratedField::Id), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = BroadcastTransactionResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.BroadcastTransactionResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut id__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Id => { if id__.is_some() { return Err(serde::de::Error::duplicate_field("id")); } id__ = Some(map_.next_value()?); } } } Ok(BroadcastTransactionResponse { id: id__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.BroadcastTransactionResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CalculateFeeRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.amount != 0 { len += 1; } if self.payload_type != 0 { len += 1; } if self.fixed_amount { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CalculateFeeRequest", len)?; if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } if self.payload_type != 0 { let v = PayloadType::try_from(self.payload_type) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.payload_type)))?; struct_ser.serialize_field("payloadType", &v)?; } if self.fixed_amount { struct_ser.serialize_field("fixedAmount", &self.fixed_amount)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CalculateFeeRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "amount", "payload_type", "payloadType", "fixed_amount", "fixedAmount", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Amount, PayloadType, FixedAmount, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "amount" => Ok(GeneratedField::Amount), "payloadType" | "payload_type" => Ok(GeneratedField::PayloadType), "fixedAmount" | "fixed_amount" => Ok(GeneratedField::FixedAmount), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CalculateFeeRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CalculateFeeRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut amount__ = None; let mut payload_type__ = None; let mut fixed_amount__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::PayloadType => { if payload_type__.is_some() { return Err(serde::de::Error::duplicate_field("payloadType")); } payload_type__ = Some(map_.next_value::()? as i32); } GeneratedField::FixedAmount => { if fixed_amount__.is_some() { return Err(serde::de::Error::duplicate_field("fixedAmount")); } fixed_amount__ = Some(map_.next_value()?); } } } Ok(CalculateFeeRequest { amount: amount__.unwrap_or_default(), payload_type: payload_type__.unwrap_or_default(), fixed_amount: fixed_amount__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CalculateFeeRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CalculateFeeResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.amount != 0 { len += 1; } if self.fee != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CalculateFeeResponse", len)?; if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CalculateFeeResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "amount", "fee", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Amount, Fee, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "amount" => Ok(GeneratedField::Amount), "fee" => Ok(GeneratedField::Fee), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CalculateFeeResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CalculateFeeResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut amount__ = None; let mut fee__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(CalculateFeeResponse { amount: amount__.unwrap_or_default(), fee: fee__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CalculateFeeResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CertificateInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.hash.is_empty() { len += 1; } if self.round != 0 { len += 1; } if !self.committers.is_empty() { len += 1; } if !self.absentees.is_empty() { len += 1; } if !self.signature.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CertificateInfo", len)?; if !self.hash.is_empty() { struct_ser.serialize_field("hash", &self.hash)?; } if self.round != 0 { struct_ser.serialize_field("round", &self.round)?; } if !self.committers.is_empty() { struct_ser.serialize_field("committers", &self.committers)?; } if !self.absentees.is_empty() { struct_ser.serialize_field("absentees", &self.absentees)?; } if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CertificateInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "hash", "round", "committers", "absentees", "signature", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Hash, Round, Committers, Absentees, Signature, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "hash" => Ok(GeneratedField::Hash), "round" => Ok(GeneratedField::Round), "committers" => Ok(GeneratedField::Committers), "absentees" => Ok(GeneratedField::Absentees), "signature" => Ok(GeneratedField::Signature), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CertificateInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CertificateInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut hash__ = None; let mut round__ = None; let mut committers__ = None; let mut absentees__ = None; let mut signature__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Hash => { if hash__.is_some() { return Err(serde::de::Error::duplicate_field("hash")); } hash__ = Some(map_.next_value()?); } GeneratedField::Round => { if round__.is_some() { return Err(serde::de::Error::duplicate_field("round")); } round__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Committers => { if committers__.is_some() { return Err(serde::de::Error::duplicate_field("committers")); } committers__ = Some(map_.next_value::>>()? .into_iter().map(|x| x.0).collect()) ; } GeneratedField::Absentees => { if absentees__.is_some() { return Err(serde::de::Error::duplicate_field("absentees")); } absentees__ = Some(map_.next_value::>>()? .into_iter().map(|x| x.0).collect()) ; } GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } } } Ok(CertificateInfo { hash: hash__.unwrap_or_default(), round: round__.unwrap_or_default(), committers: committers__.unwrap_or_default(), absentees: absentees__.unwrap_or_default(), signature: signature__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CertificateInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CheckTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.raw_transaction.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CheckTransactionRequest", len)?; if !self.raw_transaction.is_empty() { struct_ser.serialize_field("rawTransaction", &self.raw_transaction)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CheckTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "raw_transaction", "rawTransaction", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { RawTransaction, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "rawTransaction" | "raw_transaction" => Ok(GeneratedField::RawTransaction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CheckTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CheckTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut raw_transaction__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::RawTransaction => { if raw_transaction__.is_some() { return Err(serde::de::Error::duplicate_field("rawTransaction")); } raw_transaction__ = Some(map_.next_value()?); } } } Ok(CheckTransactionRequest { raw_transaction: raw_transaction__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CheckTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CheckTransactionResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.is_valid { len += 1; } if !self.error_message.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CheckTransactionResponse", len)?; if self.is_valid { struct_ser.serialize_field("isValid", &self.is_valid)?; } if !self.error_message.is_empty() { struct_ser.serialize_field("errorMessage", &self.error_message)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CheckTransactionResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "is_valid", "isValid", "error_message", "errorMessage", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { IsValid, ErrorMessage, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "isValid" | "is_valid" => Ok(GeneratedField::IsValid), "errorMessage" | "error_message" => Ok(GeneratedField::ErrorMessage), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CheckTransactionResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CheckTransactionResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut is_valid__ = None; let mut error_message__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::IsValid => { if is_valid__.is_some() { return Err(serde::de::Error::duplicate_field("isValid")); } is_valid__ = Some(map_.next_value()?); } GeneratedField::ErrorMessage => { if error_message__.is_some() { return Err(serde::de::Error::duplicate_field("errorMessage")); } error_message__ = Some(map_.next_value()?); } } } Ok(CheckTransactionResponse { is_valid: is_valid__.unwrap_or_default(), error_message: error_message__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CheckTransactionResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ConnectionInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.connections != 0 { len += 1; } if self.inbound_connections != 0 { len += 1; } if self.outbound_connections != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ConnectionInfo", len)?; if self.connections != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("connections", ToString::to_string(&self.connections).as_str())?; } if self.inbound_connections != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("inboundConnections", ToString::to_string(&self.inbound_connections).as_str())?; } if self.outbound_connections != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("outboundConnections", ToString::to_string(&self.outbound_connections).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ConnectionInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "connections", "inbound_connections", "inboundConnections", "outbound_connections", "outboundConnections", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Connections, InboundConnections, OutboundConnections, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "connections" => Ok(GeneratedField::Connections), "inboundConnections" | "inbound_connections" => Ok(GeneratedField::InboundConnections), "outboundConnections" | "outbound_connections" => Ok(GeneratedField::OutboundConnections), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ConnectionInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ConnectionInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut connections__ = None; let mut inbound_connections__ = None; let mut outbound_connections__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Connections => { if connections__.is_some() { return Err(serde::de::Error::duplicate_field("connections")); } connections__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::InboundConnections => { if inbound_connections__.is_some() { return Err(serde::de::Error::duplicate_field("inboundConnections")); } inbound_connections__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::OutboundConnections => { if outbound_connections__.is_some() { return Err(serde::de::Error::duplicate_field("outboundConnections")); } outbound_connections__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(ConnectionInfo { connections: connections__.unwrap_or_default(), inbound_connections: inbound_connections__.unwrap_or_default(), outbound_connections: outbound_connections__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ConnectionInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ConsensusInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } if self.active { len += 1; } if self.height != 0 { len += 1; } if self.round != 0 { len += 1; } if !self.votes.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ConsensusInfo", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if self.active { struct_ser.serialize_field("active", &self.active)?; } if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } if self.round != 0 { struct_ser.serialize_field("round", &self.round)?; } if !self.votes.is_empty() { struct_ser.serialize_field("votes", &self.votes)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ConsensusInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", "active", "height", "round", "votes", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, Active, Height, Round, Votes, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), "active" => Ok(GeneratedField::Active), "height" => Ok(GeneratedField::Height), "round" => Ok(GeneratedField::Round), "votes" => Ok(GeneratedField::Votes), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ConsensusInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ConsensusInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; let mut active__ = None; let mut height__ = None; let mut round__ = None; let mut votes__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Active => { if active__.is_some() { return Err(serde::de::Error::duplicate_field("active")); } active__ = Some(map_.next_value()?); } GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Round => { if round__.is_some() { return Err(serde::de::Error::duplicate_field("round")); } round__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Votes => { if votes__.is_some() { return Err(serde::de::Error::duplicate_field("votes")); } votes__ = Some(map_.next_value()?); } } } Ok(ConsensusInfo { address: address__.unwrap_or_default(), active: active__.unwrap_or_default(), height: height__.unwrap_or_default(), round: round__.unwrap_or_default(), votes: votes__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ConsensusInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CounterInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.bytes != 0 { len += 1; } if self.bundles != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CounterInfo", len)?; if self.bytes != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("bytes", ToString::to_string(&self.bytes).as_str())?; } if self.bundles != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("bundles", ToString::to_string(&self.bundles).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CounterInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "bytes", "bundles", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Bytes, Bundles, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "bytes" => Ok(GeneratedField::Bytes), "bundles" => Ok(GeneratedField::Bundles), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CounterInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CounterInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut bytes__ = None; let mut bundles__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Bytes => { if bytes__.is_some() { return Err(serde::de::Error::duplicate_field("bytes")); } bytes__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Bundles => { if bundles__.is_some() { return Err(serde::de::Error::duplicate_field("bundles")); } bundles__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(CounterInfo { bytes: bytes__.unwrap_or_default(), bundles: bundles__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CounterInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CreateWalletRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CreateWalletRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CreateWalletRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "password", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Password, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "password" => Ok(GeneratedField::Password), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CreateWalletRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CreateWalletRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut password__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } } } Ok(CreateWalletRequest { wallet_name: wallet_name__.unwrap_or_default(), password: password__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CreateWalletRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for CreateWalletResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.mnemonic.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.CreateWalletResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.mnemonic.is_empty() { struct_ser.serialize_field("mnemonic", &self.mnemonic)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for CreateWalletResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "mnemonic", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Mnemonic, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "mnemonic" => Ok(GeneratedField::Mnemonic), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = CreateWalletResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.CreateWalletResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut mnemonic__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Mnemonic => { if mnemonic__.is_some() { return Err(serde::de::Error::duplicate_field("mnemonic")); } mnemonic__ = Some(map_.next_value()?); } } } Ok(CreateWalletResponse { wallet_name: wallet_name__.unwrap_or_default(), mnemonic: mnemonic__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.CreateWalletResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for DecodeRawTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.raw_transaction.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.DecodeRawTransactionRequest", len)?; if !self.raw_transaction.is_empty() { struct_ser.serialize_field("rawTransaction", &self.raw_transaction)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for DecodeRawTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "raw_transaction", "rawTransaction", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { RawTransaction, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "rawTransaction" | "raw_transaction" => Ok(GeneratedField::RawTransaction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = DecodeRawTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.DecodeRawTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut raw_transaction__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::RawTransaction => { if raw_transaction__.is_some() { return Err(serde::de::Error::duplicate_field("rawTransaction")); } raw_transaction__ = Some(map_.next_value()?); } } } Ok(DecodeRawTransactionRequest { raw_transaction: raw_transaction__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.DecodeRawTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for DecodeRawTransactionResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.transaction.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.DecodeRawTransactionResponse", len)?; if let Some(v) = self.transaction.as_ref() { struct_ser.serialize_field("transaction", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for DecodeRawTransactionResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "transaction", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Transaction, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "transaction" => Ok(GeneratedField::Transaction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = DecodeRawTransactionResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.DecodeRawTransactionResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut transaction__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Transaction => { if transaction__.is_some() { return Err(serde::de::Error::duplicate_field("transaction")); } transaction__ = map_.next_value()?; } } } Ok(DecodeRawTransactionResponse { transaction: transaction__, }) } } deserializer.deserialize_struct("pactus.DecodeRawTransactionResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for Direction { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Unknown => "DIRECTION_UNKNOWN", Self::Inbound => "DIRECTION_INBOUND", Self::Outbound => "DIRECTION_OUTBOUND", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for Direction { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "DIRECTION_UNKNOWN", "DIRECTION_INBOUND", "DIRECTION_OUTBOUND", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = Direction; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "DIRECTION_UNKNOWN" => Ok(Direction::Unknown), "DIRECTION_INBOUND" => Ok(Direction::Inbound), "DIRECTION_OUTBOUND" => Ok(Direction::Outbound), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for GetAccountRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetAccountRequest", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetAccountRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetAccountRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetAccountRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(GetAccountRequest { address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetAccountRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetAccountResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.account.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetAccountResponse", len)?; if let Some(v) = self.account.as_ref() { struct_ser.serialize_field("account", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetAccountResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "account", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Account, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "account" => Ok(GeneratedField::Account), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetAccountResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetAccountResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut account__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Account => { if account__.is_some() { return Err(serde::de::Error::duplicate_field("account")); } account__ = map_.next_value()?; } } } Ok(GetAccountResponse { account: account__, }) } } deserializer.deserialize_struct("pactus.GetAccountResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetAddressInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetAddressInfoRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetAddressInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetAddressInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetAddressInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(GetAddressInfoRequest { wallet_name: wallet_name__.unwrap_or_default(), address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetAddressInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetAddressInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.addr.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetAddressInfoResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if let Some(v) = self.addr.as_ref() { struct_ser.serialize_field("addr", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetAddressInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "addr", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Addr, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "addr" => Ok(GeneratedField::Addr), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetAddressInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetAddressInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut addr__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Addr => { if addr__.is_some() { return Err(serde::de::Error::duplicate_field("addr")); } addr__ = map_.next_value()?; } } } Ok(GetAddressInfoResponse { wallet_name: wallet_name__.unwrap_or_default(), addr: addr__, }) } } deserializer.deserialize_struct("pactus.GetAddressInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockHashRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.height != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockHashRequest", len)?; if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockHashRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "height", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Height, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "height" => Ok(GeneratedField::Height), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockHashRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockHashRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut height__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetBlockHashRequest { height: height__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockHashRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockHashResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.hash.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockHashResponse", len)?; if !self.hash.is_empty() { struct_ser.serialize_field("hash", &self.hash)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockHashResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "hash", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Hash, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "hash" => Ok(GeneratedField::Hash), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockHashResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockHashResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut hash__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Hash => { if hash__.is_some() { return Err(serde::de::Error::duplicate_field("hash")); } hash__ = Some(map_.next_value()?); } } } Ok(GetBlockHashResponse { hash: hash__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockHashResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockHeightRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.hash.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockHeightRequest", len)?; if !self.hash.is_empty() { struct_ser.serialize_field("hash", &self.hash)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockHeightRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "hash", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Hash, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "hash" => Ok(GeneratedField::Hash), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockHeightRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockHeightRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut hash__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Hash => { if hash__.is_some() { return Err(serde::de::Error::duplicate_field("hash")); } hash__ = Some(map_.next_value()?); } } } Ok(GetBlockHeightRequest { hash: hash__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockHeightRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockHeightResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.height != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockHeightResponse", len)?; if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockHeightResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "height", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Height, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "height" => Ok(GeneratedField::Height), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockHeightResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockHeightResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut height__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetBlockHeightResponse { height: height__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockHeightResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.height != 0 { len += 1; } if self.verbosity != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockRequest", len)?; if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } if self.verbosity != 0 { let v = BlockVerbosity::try_from(self.verbosity) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.verbosity)))?; struct_ser.serialize_field("verbosity", &v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "height", "verbosity", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Height, Verbosity, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "height" => Ok(GeneratedField::Height), "verbosity" => Ok(GeneratedField::Verbosity), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut height__ = None; let mut verbosity__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Verbosity => { if verbosity__.is_some() { return Err(serde::de::Error::duplicate_field("verbosity")); } verbosity__ = Some(map_.next_value::()? as i32); } } } Ok(GetBlockRequest { height: height__.unwrap_or_default(), verbosity: verbosity__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.height != 0 { len += 1; } if !self.hash.is_empty() { len += 1; } if !self.data.is_empty() { len += 1; } if self.block_time != 0 { len += 1; } if self.header.is_some() { len += 1; } if self.prev_cert.is_some() { len += 1; } if !self.txs.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockResponse", len)?; if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } if !self.hash.is_empty() { struct_ser.serialize_field("hash", &self.hash)?; } if !self.data.is_empty() { struct_ser.serialize_field("data", &self.data)?; } if self.block_time != 0 { struct_ser.serialize_field("blockTime", &self.block_time)?; } if let Some(v) = self.header.as_ref() { struct_ser.serialize_field("header", v)?; } if let Some(v) = self.prev_cert.as_ref() { struct_ser.serialize_field("prevCert", v)?; } if !self.txs.is_empty() { struct_ser.serialize_field("txs", &self.txs)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "height", "hash", "data", "block_time", "blockTime", "header", "prev_cert", "prevCert", "txs", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Height, Hash, Data, BlockTime, Header, PrevCert, Txs, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "height" => Ok(GeneratedField::Height), "hash" => Ok(GeneratedField::Hash), "data" => Ok(GeneratedField::Data), "blockTime" | "block_time" => Ok(GeneratedField::BlockTime), "header" => Ok(GeneratedField::Header), "prevCert" | "prev_cert" => Ok(GeneratedField::PrevCert), "txs" => Ok(GeneratedField::Txs), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut height__ = None; let mut hash__ = None; let mut data__ = None; let mut block_time__ = None; let mut header__ = None; let mut prev_cert__ = None; let mut txs__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Hash => { if hash__.is_some() { return Err(serde::de::Error::duplicate_field("hash")); } hash__ = Some(map_.next_value()?); } GeneratedField::Data => { if data__.is_some() { return Err(serde::de::Error::duplicate_field("data")); } data__ = Some(map_.next_value()?); } GeneratedField::BlockTime => { if block_time__.is_some() { return Err(serde::de::Error::duplicate_field("blockTime")); } block_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Header => { if header__.is_some() { return Err(serde::de::Error::duplicate_field("header")); } header__ = map_.next_value()?; } GeneratedField::PrevCert => { if prev_cert__.is_some() { return Err(serde::de::Error::duplicate_field("prevCert")); } prev_cert__ = map_.next_value()?; } GeneratedField::Txs => { if txs__.is_some() { return Err(serde::de::Error::duplicate_field("txs")); } txs__ = Some(map_.next_value()?); } } } Ok(GetBlockResponse { height: height__.unwrap_or_default(), hash: hash__.unwrap_or_default(), data: data__.unwrap_or_default(), block_time: block_time__.unwrap_or_default(), header: header__, prev_cert: prev_cert__, txs: txs__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockchainInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.GetBlockchainInfoRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockchainInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockchainInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockchainInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(GetBlockchainInfoRequest { }) } } deserializer.deserialize_struct("pactus.GetBlockchainInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetBlockchainInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.last_block_height != 0 { len += 1; } if !self.last_block_hash.is_empty() { len += 1; } if self.last_block_time != 0 { len += 1; } if self.total_accounts != 0 { len += 1; } if self.total_validators != 0 { len += 1; } if self.active_validators != 0 { len += 1; } if self.total_power != 0 { len += 1; } if self.committee_power != 0 { len += 1; } if self.is_pruned { len += 1; } if self.pruning_height != 0 { len += 1; } if self.in_committee { len += 1; } if self.committee_size != 0 { len += 1; } if self.average_score != 0. { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetBlockchainInfoResponse", len)?; if self.last_block_height != 0 { struct_ser.serialize_field("lastBlockHeight", &self.last_block_height)?; } if !self.last_block_hash.is_empty() { struct_ser.serialize_field("lastBlockHash", &self.last_block_hash)?; } if self.last_block_time != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("lastBlockTime", ToString::to_string(&self.last_block_time).as_str())?; } if self.total_accounts != 0 { struct_ser.serialize_field("totalAccounts", &self.total_accounts)?; } if self.total_validators != 0 { struct_ser.serialize_field("totalValidators", &self.total_validators)?; } if self.active_validators != 0 { struct_ser.serialize_field("activeValidators", &self.active_validators)?; } if self.total_power != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("totalPower", ToString::to_string(&self.total_power).as_str())?; } if self.committee_power != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("committeePower", ToString::to_string(&self.committee_power).as_str())?; } if self.is_pruned { struct_ser.serialize_field("isPruned", &self.is_pruned)?; } if self.pruning_height != 0 { struct_ser.serialize_field("pruningHeight", &self.pruning_height)?; } if self.in_committee { struct_ser.serialize_field("inCommittee", &self.in_committee)?; } if self.committee_size != 0 { struct_ser.serialize_field("committeeSize", &self.committee_size)?; } if self.average_score != 0. { struct_ser.serialize_field("averageScore", &self.average_score)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetBlockchainInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "last_block_height", "lastBlockHeight", "last_block_hash", "lastBlockHash", "last_block_time", "lastBlockTime", "total_accounts", "totalAccounts", "total_validators", "totalValidators", "active_validators", "activeValidators", "total_power", "totalPower", "committee_power", "committeePower", "is_pruned", "isPruned", "pruning_height", "pruningHeight", "in_committee", "inCommittee", "committee_size", "committeeSize", "average_score", "averageScore", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { LastBlockHeight, LastBlockHash, LastBlockTime, TotalAccounts, TotalValidators, ActiveValidators, TotalPower, CommitteePower, IsPruned, PruningHeight, InCommittee, CommitteeSize, AverageScore, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "lastBlockHeight" | "last_block_height" => Ok(GeneratedField::LastBlockHeight), "lastBlockHash" | "last_block_hash" => Ok(GeneratedField::LastBlockHash), "lastBlockTime" | "last_block_time" => Ok(GeneratedField::LastBlockTime), "totalAccounts" | "total_accounts" => Ok(GeneratedField::TotalAccounts), "totalValidators" | "total_validators" => Ok(GeneratedField::TotalValidators), "activeValidators" | "active_validators" => Ok(GeneratedField::ActiveValidators), "totalPower" | "total_power" => Ok(GeneratedField::TotalPower), "committeePower" | "committee_power" => Ok(GeneratedField::CommitteePower), "isPruned" | "is_pruned" => Ok(GeneratedField::IsPruned), "pruningHeight" | "pruning_height" => Ok(GeneratedField::PruningHeight), "inCommittee" | "in_committee" => Ok(GeneratedField::InCommittee), "committeeSize" | "committee_size" => Ok(GeneratedField::CommitteeSize), "averageScore" | "average_score" => Ok(GeneratedField::AverageScore), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetBlockchainInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetBlockchainInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut last_block_height__ = None; let mut last_block_hash__ = None; let mut last_block_time__ = None; let mut total_accounts__ = None; let mut total_validators__ = None; let mut active_validators__ = None; let mut total_power__ = None; let mut committee_power__ = None; let mut is_pruned__ = None; let mut pruning_height__ = None; let mut in_committee__ = None; let mut committee_size__ = None; let mut average_score__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::LastBlockHeight => { if last_block_height__.is_some() { return Err(serde::de::Error::duplicate_field("lastBlockHeight")); } last_block_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LastBlockHash => { if last_block_hash__.is_some() { return Err(serde::de::Error::duplicate_field("lastBlockHash")); } last_block_hash__ = Some(map_.next_value()?); } GeneratedField::LastBlockTime => { if last_block_time__.is_some() { return Err(serde::de::Error::duplicate_field("lastBlockTime")); } last_block_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::TotalAccounts => { if total_accounts__.is_some() { return Err(serde::de::Error::duplicate_field("totalAccounts")); } total_accounts__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::TotalValidators => { if total_validators__.is_some() { return Err(serde::de::Error::duplicate_field("totalValidators")); } total_validators__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::ActiveValidators => { if active_validators__.is_some() { return Err(serde::de::Error::duplicate_field("activeValidators")); } active_validators__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::TotalPower => { if total_power__.is_some() { return Err(serde::de::Error::duplicate_field("totalPower")); } total_power__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::CommitteePower => { if committee_power__.is_some() { return Err(serde::de::Error::duplicate_field("committeePower")); } committee_power__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::IsPruned => { if is_pruned__.is_some() { return Err(serde::de::Error::duplicate_field("isPruned")); } is_pruned__ = Some(map_.next_value()?); } GeneratedField::PruningHeight => { if pruning_height__.is_some() { return Err(serde::de::Error::duplicate_field("pruningHeight")); } pruning_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::InCommittee => { if in_committee__.is_some() { return Err(serde::de::Error::duplicate_field("inCommittee")); } in_committee__ = Some(map_.next_value()?); } GeneratedField::CommitteeSize => { if committee_size__.is_some() { return Err(serde::de::Error::duplicate_field("committeeSize")); } committee_size__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::AverageScore => { if average_score__.is_some() { return Err(serde::de::Error::duplicate_field("averageScore")); } average_score__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetBlockchainInfoResponse { last_block_height: last_block_height__.unwrap_or_default(), last_block_hash: last_block_hash__.unwrap_or_default(), last_block_time: last_block_time__.unwrap_or_default(), total_accounts: total_accounts__.unwrap_or_default(), total_validators: total_validators__.unwrap_or_default(), active_validators: active_validators__.unwrap_or_default(), total_power: total_power__.unwrap_or_default(), committee_power: committee_power__.unwrap_or_default(), is_pruned: is_pruned__.unwrap_or_default(), pruning_height: pruning_height__.unwrap_or_default(), in_committee: in_committee__.unwrap_or_default(), committee_size: committee_size__.unwrap_or_default(), average_score: average_score__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetBlockchainInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetCommitteeInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.GetCommitteeInfoRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetCommitteeInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetCommitteeInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetCommitteeInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(GetCommitteeInfoRequest { }) } } deserializer.deserialize_struct("pactus.GetCommitteeInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetCommitteeInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.committee_size != 0 { len += 1; } if self.committee_power != 0 { len += 1; } if self.total_power != 0 { len += 1; } if !self.validators.is_empty() { len += 1; } if !self.protocol_versions.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetCommitteeInfoResponse", len)?; if self.committee_size != 0 { struct_ser.serialize_field("committeeSize", &self.committee_size)?; } if self.committee_power != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("committeePower", ToString::to_string(&self.committee_power).as_str())?; } if self.total_power != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("totalPower", ToString::to_string(&self.total_power).as_str())?; } if !self.validators.is_empty() { struct_ser.serialize_field("validators", &self.validators)?; } if !self.protocol_versions.is_empty() { struct_ser.serialize_field("protocolVersions", &self.protocol_versions)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetCommitteeInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "committee_size", "committeeSize", "committee_power", "committeePower", "total_power", "totalPower", "validators", "protocol_versions", "protocolVersions", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { CommitteeSize, CommitteePower, TotalPower, Validators, ProtocolVersions, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "committeeSize" | "committee_size" => Ok(GeneratedField::CommitteeSize), "committeePower" | "committee_power" => Ok(GeneratedField::CommitteePower), "totalPower" | "total_power" => Ok(GeneratedField::TotalPower), "validators" => Ok(GeneratedField::Validators), "protocolVersions" | "protocol_versions" => Ok(GeneratedField::ProtocolVersions), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetCommitteeInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetCommitteeInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut committee_size__ = None; let mut committee_power__ = None; let mut total_power__ = None; let mut validators__ = None; let mut protocol_versions__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::CommitteeSize => { if committee_size__.is_some() { return Err(serde::de::Error::duplicate_field("committeeSize")); } committee_size__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::CommitteePower => { if committee_power__.is_some() { return Err(serde::de::Error::duplicate_field("committeePower")); } committee_power__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::TotalPower => { if total_power__.is_some() { return Err(serde::de::Error::duplicate_field("totalPower")); } total_power__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Validators => { if validators__.is_some() { return Err(serde::de::Error::duplicate_field("validators")); } validators__ = Some(map_.next_value()?); } GeneratedField::ProtocolVersions => { if protocol_versions__.is_some() { return Err(serde::de::Error::duplicate_field("protocolVersions")); } protocol_versions__ = Some( map_.next_value::, ::pbjson::private::NumberDeserialize>>()? .into_iter().map(|(k,v)| (k.0, v.0)).collect() ); } } } Ok(GetCommitteeInfoResponse { committee_size: committee_size__.unwrap_or_default(), committee_power: committee_power__.unwrap_or_default(), total_power: total_power__.unwrap_or_default(), validators: validators__.unwrap_or_default(), protocol_versions: protocol_versions__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetCommitteeInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetConsensusInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.GetConsensusInfoRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetConsensusInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetConsensusInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetConsensusInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(GetConsensusInfoRequest { }) } } deserializer.deserialize_struct("pactus.GetConsensusInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetConsensusInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.proposal.is_some() { len += 1; } if !self.instances.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetConsensusInfoResponse", len)?; if let Some(v) = self.proposal.as_ref() { struct_ser.serialize_field("proposal", v)?; } if !self.instances.is_empty() { struct_ser.serialize_field("instances", &self.instances)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetConsensusInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "proposal", "instances", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Proposal, Instances, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "proposal" => Ok(GeneratedField::Proposal), "instances" => Ok(GeneratedField::Instances), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetConsensusInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetConsensusInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut proposal__ = None; let mut instances__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Proposal => { if proposal__.is_some() { return Err(serde::de::Error::duplicate_field("proposal")); } proposal__ = map_.next_value()?; } GeneratedField::Instances => { if instances__.is_some() { return Err(serde::de::Error::duplicate_field("instances")); } instances__ = Some(map_.next_value()?); } } } Ok(GetConsensusInfoResponse { proposal: proposal__, instances: instances__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetConsensusInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetMnemonicRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetMnemonicRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetMnemonicRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "password", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Password, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "password" => Ok(GeneratedField::Password), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetMnemonicRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetMnemonicRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut password__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } } } Ok(GetMnemonicRequest { wallet_name: wallet_name__.unwrap_or_default(), password: password__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetMnemonicRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetMnemonicResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.mnemonic.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetMnemonicResponse", len)?; if !self.mnemonic.is_empty() { struct_ser.serialize_field("mnemonic", &self.mnemonic)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetMnemonicResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "mnemonic", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Mnemonic, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "mnemonic" => Ok(GeneratedField::Mnemonic), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetMnemonicResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetMnemonicResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut mnemonic__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Mnemonic => { if mnemonic__.is_some() { return Err(serde::de::Error::duplicate_field("mnemonic")); } mnemonic__ = Some(map_.next_value()?); } } } Ok(GetMnemonicResponse { mnemonic: mnemonic__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetMnemonicResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetNetworkInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.GetNetworkInfoRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetNetworkInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetNetworkInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetNetworkInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(GetNetworkInfoRequest { }) } } deserializer.deserialize_struct("pactus.GetNetworkInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetNetworkInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.network_name.is_empty() { len += 1; } if self.connected_peers_count != 0 { len += 1; } if self.metric_info.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetNetworkInfoResponse", len)?; if !self.network_name.is_empty() { struct_ser.serialize_field("networkName", &self.network_name)?; } if self.connected_peers_count != 0 { struct_ser.serialize_field("connectedPeersCount", &self.connected_peers_count)?; } if let Some(v) = self.metric_info.as_ref() { struct_ser.serialize_field("metricInfo", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetNetworkInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "network_name", "networkName", "connected_peers_count", "connectedPeersCount", "metric_info", "metricInfo", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { NetworkName, ConnectedPeersCount, MetricInfo, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "networkName" | "network_name" => Ok(GeneratedField::NetworkName), "connectedPeersCount" | "connected_peers_count" => Ok(GeneratedField::ConnectedPeersCount), "metricInfo" | "metric_info" => Ok(GeneratedField::MetricInfo), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetNetworkInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetNetworkInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut network_name__ = None; let mut connected_peers_count__ = None; let mut metric_info__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::NetworkName => { if network_name__.is_some() { return Err(serde::de::Error::duplicate_field("networkName")); } network_name__ = Some(map_.next_value()?); } GeneratedField::ConnectedPeersCount => { if connected_peers_count__.is_some() { return Err(serde::de::Error::duplicate_field("connectedPeersCount")); } connected_peers_count__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::MetricInfo => { if metric_info__.is_some() { return Err(serde::de::Error::duplicate_field("metricInfo")); } metric_info__ = map_.next_value()?; } } } Ok(GetNetworkInfoResponse { network_name: network_name__.unwrap_or_default(), connected_peers_count: connected_peers_count__.unwrap_or_default(), metric_info: metric_info__, }) } } deserializer.deserialize_struct("pactus.GetNetworkInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetNewAddressRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.address_type != 0 { len += 1; } if !self.label.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetNewAddressRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if self.address_type != 0 { let v = AddressType::try_from(self.address_type) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.address_type)))?; struct_ser.serialize_field("addressType", &v)?; } if !self.label.is_empty() { struct_ser.serialize_field("label", &self.label)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetNewAddressRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "address_type", "addressType", "label", "password", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, AddressType, Label, Password, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "addressType" | "address_type" => Ok(GeneratedField::AddressType), "label" => Ok(GeneratedField::Label), "password" => Ok(GeneratedField::Password), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetNewAddressRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetNewAddressRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut address_type__ = None; let mut label__ = None; let mut password__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::AddressType => { if address_type__.is_some() { return Err(serde::de::Error::duplicate_field("addressType")); } address_type__ = Some(map_.next_value::()? as i32); } GeneratedField::Label => { if label__.is_some() { return Err(serde::de::Error::duplicate_field("label")); } label__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } } } Ok(GetNewAddressRequest { wallet_name: wallet_name__.unwrap_or_default(), address_type: address_type__.unwrap_or_default(), label: label__.unwrap_or_default(), password: password__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetNewAddressRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetNewAddressResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.addr.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetNewAddressResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if let Some(v) = self.addr.as_ref() { struct_ser.serialize_field("addr", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetNewAddressResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "addr", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Addr, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "addr" => Ok(GeneratedField::Addr), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetNewAddressResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetNewAddressResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut addr__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Addr => { if addr__.is_some() { return Err(serde::de::Error::duplicate_field("addr")); } addr__ = map_.next_value()?; } } } Ok(GetNewAddressResponse { wallet_name: wallet_name__.unwrap_or_default(), addr: addr__, }) } } deserializer.deserialize_struct("pactus.GetNewAddressResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetNodeInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.GetNodeInfoRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetNodeInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetNodeInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetNodeInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(GetNodeInfoRequest { }) } } deserializer.deserialize_struct("pactus.GetNodeInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetNodeInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.moniker.is_empty() { len += 1; } if !self.agent.is_empty() { len += 1; } if !self.peer_id.is_empty() { len += 1; } if self.started_at != 0 { len += 1; } if !self.reachability.is_empty() { len += 1; } if self.services != 0 { len += 1; } if !self.services_names.is_empty() { len += 1; } if !self.local_addrs.is_empty() { len += 1; } if !self.protocols.is_empty() { len += 1; } if self.clock_offset != 0. { len += 1; } if self.connection_info.is_some() { len += 1; } if !self.zmq_publishers.is_empty() { len += 1; } if self.current_time != 0 { len += 1; } if !self.network_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetNodeInfoResponse", len)?; if !self.moniker.is_empty() { struct_ser.serialize_field("moniker", &self.moniker)?; } if !self.agent.is_empty() { struct_ser.serialize_field("agent", &self.agent)?; } if !self.peer_id.is_empty() { struct_ser.serialize_field("peerId", &self.peer_id)?; } if self.started_at != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("startedAt", ToString::to_string(&self.started_at).as_str())?; } if !self.reachability.is_empty() { struct_ser.serialize_field("reachability", &self.reachability)?; } if self.services != 0 { struct_ser.serialize_field("services", &self.services)?; } if !self.services_names.is_empty() { struct_ser.serialize_field("servicesNames", &self.services_names)?; } if !self.local_addrs.is_empty() { struct_ser.serialize_field("localAddrs", &self.local_addrs)?; } if !self.protocols.is_empty() { struct_ser.serialize_field("protocols", &self.protocols)?; } if self.clock_offset != 0. { struct_ser.serialize_field("clockOffset", &self.clock_offset)?; } if let Some(v) = self.connection_info.as_ref() { struct_ser.serialize_field("connectionInfo", v)?; } if !self.zmq_publishers.is_empty() { struct_ser.serialize_field("zmqPublishers", &self.zmq_publishers)?; } if self.current_time != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("currentTime", ToString::to_string(&self.current_time).as_str())?; } if !self.network_name.is_empty() { struct_ser.serialize_field("networkName", &self.network_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetNodeInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "moniker", "agent", "peer_id", "peerId", "started_at", "startedAt", "reachability", "services", "services_names", "servicesNames", "local_addrs", "localAddrs", "protocols", "clock_offset", "clockOffset", "connection_info", "connectionInfo", "zmq_publishers", "zmqPublishers", "current_time", "currentTime", "network_name", "networkName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Moniker, Agent, PeerId, StartedAt, Reachability, Services, ServicesNames, LocalAddrs, Protocols, ClockOffset, ConnectionInfo, ZmqPublishers, CurrentTime, NetworkName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "moniker" => Ok(GeneratedField::Moniker), "agent" => Ok(GeneratedField::Agent), "peerId" | "peer_id" => Ok(GeneratedField::PeerId), "startedAt" | "started_at" => Ok(GeneratedField::StartedAt), "reachability" => Ok(GeneratedField::Reachability), "services" => Ok(GeneratedField::Services), "servicesNames" | "services_names" => Ok(GeneratedField::ServicesNames), "localAddrs" | "local_addrs" => Ok(GeneratedField::LocalAddrs), "protocols" => Ok(GeneratedField::Protocols), "clockOffset" | "clock_offset" => Ok(GeneratedField::ClockOffset), "connectionInfo" | "connection_info" => Ok(GeneratedField::ConnectionInfo), "zmqPublishers" | "zmq_publishers" => Ok(GeneratedField::ZmqPublishers), "currentTime" | "current_time" => Ok(GeneratedField::CurrentTime), "networkName" | "network_name" => Ok(GeneratedField::NetworkName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetNodeInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetNodeInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut moniker__ = None; let mut agent__ = None; let mut peer_id__ = None; let mut started_at__ = None; let mut reachability__ = None; let mut services__ = None; let mut services_names__ = None; let mut local_addrs__ = None; let mut protocols__ = None; let mut clock_offset__ = None; let mut connection_info__ = None; let mut zmq_publishers__ = None; let mut current_time__ = None; let mut network_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Moniker => { if moniker__.is_some() { return Err(serde::de::Error::duplicate_field("moniker")); } moniker__ = Some(map_.next_value()?); } GeneratedField::Agent => { if agent__.is_some() { return Err(serde::de::Error::duplicate_field("agent")); } agent__ = Some(map_.next_value()?); } GeneratedField::PeerId => { if peer_id__.is_some() { return Err(serde::de::Error::duplicate_field("peerId")); } peer_id__ = Some(map_.next_value()?); } GeneratedField::StartedAt => { if started_at__.is_some() { return Err(serde::de::Error::duplicate_field("startedAt")); } started_at__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Reachability => { if reachability__.is_some() { return Err(serde::de::Error::duplicate_field("reachability")); } reachability__ = Some(map_.next_value()?); } GeneratedField::Services => { if services__.is_some() { return Err(serde::de::Error::duplicate_field("services")); } services__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::ServicesNames => { if services_names__.is_some() { return Err(serde::de::Error::duplicate_field("servicesNames")); } services_names__ = Some(map_.next_value()?); } GeneratedField::LocalAddrs => { if local_addrs__.is_some() { return Err(serde::de::Error::duplicate_field("localAddrs")); } local_addrs__ = Some(map_.next_value()?); } GeneratedField::Protocols => { if protocols__.is_some() { return Err(serde::de::Error::duplicate_field("protocols")); } protocols__ = Some(map_.next_value()?); } GeneratedField::ClockOffset => { if clock_offset__.is_some() { return Err(serde::de::Error::duplicate_field("clockOffset")); } clock_offset__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::ConnectionInfo => { if connection_info__.is_some() { return Err(serde::de::Error::duplicate_field("connectionInfo")); } connection_info__ = map_.next_value()?; } GeneratedField::ZmqPublishers => { if zmq_publishers__.is_some() { return Err(serde::de::Error::duplicate_field("zmqPublishers")); } zmq_publishers__ = Some(map_.next_value()?); } GeneratedField::CurrentTime => { if current_time__.is_some() { return Err(serde::de::Error::duplicate_field("currentTime")); } current_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::NetworkName => { if network_name__.is_some() { return Err(serde::de::Error::duplicate_field("networkName")); } network_name__ = Some(map_.next_value()?); } } } Ok(GetNodeInfoResponse { moniker: moniker__.unwrap_or_default(), agent: agent__.unwrap_or_default(), peer_id: peer_id__.unwrap_or_default(), started_at: started_at__.unwrap_or_default(), reachability: reachability__.unwrap_or_default(), services: services__.unwrap_or_default(), services_names: services_names__.unwrap_or_default(), local_addrs: local_addrs__.unwrap_or_default(), protocols: protocols__.unwrap_or_default(), clock_offset: clock_offset__.unwrap_or_default(), connection_info: connection_info__, zmq_publishers: zmq_publishers__.unwrap_or_default(), current_time: current_time__.unwrap_or_default(), network_name: network_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetNodeInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetPrivateKeyRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetPrivateKeyRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetPrivateKeyRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "password", "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Password, Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "password" => Ok(GeneratedField::Password), "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetPrivateKeyRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetPrivateKeyRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut password__ = None; let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(GetPrivateKeyRequest { wallet_name: wallet_name__.unwrap_or_default(), password: password__.unwrap_or_default(), address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetPrivateKeyRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetPrivateKeyResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.private_key.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetPrivateKeyResponse", len)?; if !self.private_key.is_empty() { struct_ser.serialize_field("privateKey", &self.private_key)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetPrivateKeyResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "private_key", "privateKey", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PrivateKey, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "privateKey" | "private_key" => Ok(GeneratedField::PrivateKey), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetPrivateKeyResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetPrivateKeyResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut private_key__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PrivateKey => { if private_key__.is_some() { return Err(serde::de::Error::duplicate_field("privateKey")); } private_key__ = Some(map_.next_value()?); } } } Ok(GetPrivateKeyResponse { private_key: private_key__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetPrivateKeyResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetPublicKeyRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetPublicKeyRequest", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetPublicKeyRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetPublicKeyRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetPublicKeyRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(GetPublicKeyRequest { address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetPublicKeyRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetPublicKeyResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.public_key.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetPublicKeyResponse", len)?; if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetPublicKeyResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "public_key", "publicKey", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PublicKey, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetPublicKeyResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetPublicKeyResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut public_key__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } } } Ok(GetPublicKeyResponse { public_key: public_key__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetPublicKeyResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetRawBatchTransferTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.lock_time != 0 { len += 1; } if !self.sender.is_empty() { len += 1; } if !self.recipients.is_empty() { len += 1; } if self.fee != 0 { len += 1; } if !self.memo.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetRawBatchTransferTransactionRequest", len)?; if self.lock_time != 0 { struct_ser.serialize_field("lockTime", &self.lock_time)?; } if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.recipients.is_empty() { struct_ser.serialize_field("recipients", &self.recipients)?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetRawBatchTransferTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "lock_time", "lockTime", "sender", "recipients", "fee", "memo", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { LockTime, Sender, Recipients, Fee, Memo, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "lockTime" | "lock_time" => Ok(GeneratedField::LockTime), "sender" => Ok(GeneratedField::Sender), "recipients" => Ok(GeneratedField::Recipients), "fee" => Ok(GeneratedField::Fee), "memo" => Ok(GeneratedField::Memo), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetRawBatchTransferTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetRawBatchTransferTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut lock_time__ = None; let mut sender__ = None; let mut recipients__ = None; let mut fee__ = None; let mut memo__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::LockTime => { if lock_time__.is_some() { return Err(serde::de::Error::duplicate_field("lockTime")); } lock_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Recipients => { if recipients__.is_some() { return Err(serde::de::Error::duplicate_field("recipients")); } recipients__ = Some(map_.next_value()?); } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } } } Ok(GetRawBatchTransferTransactionRequest { lock_time: lock_time__.unwrap_or_default(), sender: sender__.unwrap_or_default(), recipients: recipients__.unwrap_or_default(), fee: fee__.unwrap_or_default(), memo: memo__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetRawBatchTransferTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetRawBondTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.lock_time != 0 { len += 1; } if !self.sender.is_empty() { len += 1; } if !self.receiver.is_empty() { len += 1; } if self.stake != 0 { len += 1; } if !self.public_key.is_empty() { len += 1; } if self.fee != 0 { len += 1; } if !self.memo.is_empty() { len += 1; } if !self.delegate_owner.is_empty() { len += 1; } if self.delegate_share != 0 { len += 1; } if self.delegate_expiry != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetRawBondTransactionRequest", len)?; if self.lock_time != 0 { struct_ser.serialize_field("lockTime", &self.lock_time)?; } if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.receiver.is_empty() { struct_ser.serialize_field("receiver", &self.receiver)?; } if self.stake != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("stake", ToString::to_string(&self.stake).as_str())?; } if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } if !self.delegate_owner.is_empty() { struct_ser.serialize_field("delegateOwner", &self.delegate_owner)?; } if self.delegate_share != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("delegateShare", ToString::to_string(&self.delegate_share).as_str())?; } if self.delegate_expiry != 0 { struct_ser.serialize_field("delegateExpiry", &self.delegate_expiry)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetRawBondTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "lock_time", "lockTime", "sender", "receiver", "stake", "public_key", "publicKey", "fee", "memo", "delegate_owner", "delegateOwner", "delegate_share", "delegateShare", "delegate_expiry", "delegateExpiry", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { LockTime, Sender, Receiver, Stake, PublicKey, Fee, Memo, DelegateOwner, DelegateShare, DelegateExpiry, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "lockTime" | "lock_time" => Ok(GeneratedField::LockTime), "sender" => Ok(GeneratedField::Sender), "receiver" => Ok(GeneratedField::Receiver), "stake" => Ok(GeneratedField::Stake), "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), "fee" => Ok(GeneratedField::Fee), "memo" => Ok(GeneratedField::Memo), "delegateOwner" | "delegate_owner" => Ok(GeneratedField::DelegateOwner), "delegateShare" | "delegate_share" => Ok(GeneratedField::DelegateShare), "delegateExpiry" | "delegate_expiry" => Ok(GeneratedField::DelegateExpiry), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetRawBondTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetRawBondTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut lock_time__ = None; let mut sender__ = None; let mut receiver__ = None; let mut stake__ = None; let mut public_key__ = None; let mut fee__ = None; let mut memo__ = None; let mut delegate_owner__ = None; let mut delegate_share__ = None; let mut delegate_expiry__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::LockTime => { if lock_time__.is_some() { return Err(serde::de::Error::duplicate_field("lockTime")); } lock_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Receiver => { if receiver__.is_some() { return Err(serde::de::Error::duplicate_field("receiver")); } receiver__ = Some(map_.next_value()?); } GeneratedField::Stake => { if stake__.is_some() { return Err(serde::de::Error::duplicate_field("stake")); } stake__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } GeneratedField::DelegateOwner => { if delegate_owner__.is_some() { return Err(serde::de::Error::duplicate_field("delegateOwner")); } delegate_owner__ = Some(map_.next_value()?); } GeneratedField::DelegateShare => { if delegate_share__.is_some() { return Err(serde::de::Error::duplicate_field("delegateShare")); } delegate_share__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::DelegateExpiry => { if delegate_expiry__.is_some() { return Err(serde::de::Error::duplicate_field("delegateExpiry")); } delegate_expiry__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetRawBondTransactionRequest { lock_time: lock_time__.unwrap_or_default(), sender: sender__.unwrap_or_default(), receiver: receiver__.unwrap_or_default(), stake: stake__.unwrap_or_default(), public_key: public_key__.unwrap_or_default(), fee: fee__.unwrap_or_default(), memo: memo__.unwrap_or_default(), delegate_owner: delegate_owner__.unwrap_or_default(), delegate_share: delegate_share__.unwrap_or_default(), delegate_expiry: delegate_expiry__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetRawBondTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetRawTransactionResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.raw_transaction.is_empty() { len += 1; } if !self.id.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetRawTransactionResponse", len)?; if !self.raw_transaction.is_empty() { struct_ser.serialize_field("rawTransaction", &self.raw_transaction)?; } if !self.id.is_empty() { struct_ser.serialize_field("id", &self.id)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetRawTransactionResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "raw_transaction", "rawTransaction", "id", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { RawTransaction, Id, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "rawTransaction" | "raw_transaction" => Ok(GeneratedField::RawTransaction), "id" => Ok(GeneratedField::Id), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetRawTransactionResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetRawTransactionResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut raw_transaction__ = None; let mut id__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::RawTransaction => { if raw_transaction__.is_some() { return Err(serde::de::Error::duplicate_field("rawTransaction")); } raw_transaction__ = Some(map_.next_value()?); } GeneratedField::Id => { if id__.is_some() { return Err(serde::de::Error::duplicate_field("id")); } id__ = Some(map_.next_value()?); } } } Ok(GetRawTransactionResponse { raw_transaction: raw_transaction__.unwrap_or_default(), id: id__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetRawTransactionResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetRawTransferTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.lock_time != 0 { len += 1; } if !self.sender.is_empty() { len += 1; } if !self.receiver.is_empty() { len += 1; } if self.amount != 0 { len += 1; } if self.fee != 0 { len += 1; } if !self.memo.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetRawTransferTransactionRequest", len)?; if self.lock_time != 0 { struct_ser.serialize_field("lockTime", &self.lock_time)?; } if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.receiver.is_empty() { struct_ser.serialize_field("receiver", &self.receiver)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetRawTransferTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "lock_time", "lockTime", "sender", "receiver", "amount", "fee", "memo", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { LockTime, Sender, Receiver, Amount, Fee, Memo, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "lockTime" | "lock_time" => Ok(GeneratedField::LockTime), "sender" => Ok(GeneratedField::Sender), "receiver" => Ok(GeneratedField::Receiver), "amount" => Ok(GeneratedField::Amount), "fee" => Ok(GeneratedField::Fee), "memo" => Ok(GeneratedField::Memo), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetRawTransferTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetRawTransferTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut lock_time__ = None; let mut sender__ = None; let mut receiver__ = None; let mut amount__ = None; let mut fee__ = None; let mut memo__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::LockTime => { if lock_time__.is_some() { return Err(serde::de::Error::duplicate_field("lockTime")); } lock_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Receiver => { if receiver__.is_some() { return Err(serde::de::Error::duplicate_field("receiver")); } receiver__ = Some(map_.next_value()?); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } } } Ok(GetRawTransferTransactionRequest { lock_time: lock_time__.unwrap_or_default(), sender: sender__.unwrap_or_default(), receiver: receiver__.unwrap_or_default(), amount: amount__.unwrap_or_default(), fee: fee__.unwrap_or_default(), memo: memo__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetRawTransferTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetRawUnbondTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.lock_time != 0 { len += 1; } if !self.validator_address.is_empty() { len += 1; } if !self.memo.is_empty() { len += 1; } if !self.delegate_owner.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetRawUnbondTransactionRequest", len)?; if self.lock_time != 0 { struct_ser.serialize_field("lockTime", &self.lock_time)?; } if !self.validator_address.is_empty() { struct_ser.serialize_field("validatorAddress", &self.validator_address)?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } if !self.delegate_owner.is_empty() { struct_ser.serialize_field("delegateOwner", &self.delegate_owner)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetRawUnbondTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "lock_time", "lockTime", "validator_address", "validatorAddress", "memo", "delegate_owner", "delegateOwner", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { LockTime, ValidatorAddress, Memo, DelegateOwner, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "lockTime" | "lock_time" => Ok(GeneratedField::LockTime), "validatorAddress" | "validator_address" => Ok(GeneratedField::ValidatorAddress), "memo" => Ok(GeneratedField::Memo), "delegateOwner" | "delegate_owner" => Ok(GeneratedField::DelegateOwner), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetRawUnbondTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetRawUnbondTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut lock_time__ = None; let mut validator_address__ = None; let mut memo__ = None; let mut delegate_owner__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::LockTime => { if lock_time__.is_some() { return Err(serde::de::Error::duplicate_field("lockTime")); } lock_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::ValidatorAddress => { if validator_address__.is_some() { return Err(serde::de::Error::duplicate_field("validatorAddress")); } validator_address__ = Some(map_.next_value()?); } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } GeneratedField::DelegateOwner => { if delegate_owner__.is_some() { return Err(serde::de::Error::duplicate_field("delegateOwner")); } delegate_owner__ = Some(map_.next_value()?); } } } Ok(GetRawUnbondTransactionRequest { lock_time: lock_time__.unwrap_or_default(), validator_address: validator_address__.unwrap_or_default(), memo: memo__.unwrap_or_default(), delegate_owner: delegate_owner__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetRawUnbondTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetRawWithdrawTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.lock_time != 0 { len += 1; } if !self.validator_address.is_empty() { len += 1; } if !self.account_address.is_empty() { len += 1; } if self.amount != 0 { len += 1; } if self.fee != 0 { len += 1; } if !self.memo.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetRawWithdrawTransactionRequest", len)?; if self.lock_time != 0 { struct_ser.serialize_field("lockTime", &self.lock_time)?; } if !self.validator_address.is_empty() { struct_ser.serialize_field("validatorAddress", &self.validator_address)?; } if !self.account_address.is_empty() { struct_ser.serialize_field("accountAddress", &self.account_address)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetRawWithdrawTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "lock_time", "lockTime", "validator_address", "validatorAddress", "account_address", "accountAddress", "amount", "fee", "memo", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { LockTime, ValidatorAddress, AccountAddress, Amount, Fee, Memo, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "lockTime" | "lock_time" => Ok(GeneratedField::LockTime), "validatorAddress" | "validator_address" => Ok(GeneratedField::ValidatorAddress), "accountAddress" | "account_address" => Ok(GeneratedField::AccountAddress), "amount" => Ok(GeneratedField::Amount), "fee" => Ok(GeneratedField::Fee), "memo" => Ok(GeneratedField::Memo), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetRawWithdrawTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetRawWithdrawTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut lock_time__ = None; let mut validator_address__ = None; let mut account_address__ = None; let mut amount__ = None; let mut fee__ = None; let mut memo__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::LockTime => { if lock_time__.is_some() { return Err(serde::de::Error::duplicate_field("lockTime")); } lock_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::ValidatorAddress => { if validator_address__.is_some() { return Err(serde::de::Error::duplicate_field("validatorAddress")); } validator_address__ = Some(map_.next_value()?); } GeneratedField::AccountAddress => { if account_address__.is_some() { return Err(serde::de::Error::duplicate_field("accountAddress")); } account_address__ = Some(map_.next_value()?); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } } } Ok(GetRawWithdrawTransactionRequest { lock_time: lock_time__.unwrap_or_default(), validator_address: validator_address__.unwrap_or_default(), account_address: account_address__.unwrap_or_default(), amount: amount__.unwrap_or_default(), fee: fee__.unwrap_or_default(), memo: memo__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetRawWithdrawTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTotalBalanceRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTotalBalanceRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTotalBalanceRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTotalBalanceRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTotalBalanceRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(GetTotalBalanceRequest { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTotalBalanceRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTotalBalanceResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.total_balance != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTotalBalanceResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if self.total_balance != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("totalBalance", ToString::to_string(&self.total_balance).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTotalBalanceResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "total_balance", "totalBalance", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, TotalBalance, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "totalBalance" | "total_balance" => Ok(GeneratedField::TotalBalance), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTotalBalanceResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTotalBalanceResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut total_balance__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::TotalBalance => { if total_balance__.is_some() { return Err(serde::de::Error::duplicate_field("totalBalance")); } total_balance__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetTotalBalanceResponse { wallet_name: wallet_name__.unwrap_or_default(), total_balance: total_balance__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTotalBalanceResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTotalStakeRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTotalStakeRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTotalStakeRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTotalStakeRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTotalStakeRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(GetTotalStakeRequest { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTotalStakeRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTotalStakeResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.total_stake != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTotalStakeResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if self.total_stake != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("totalStake", ToString::to_string(&self.total_stake).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTotalStakeResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "total_stake", "totalStake", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, TotalStake, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "totalStake" | "total_stake" => Ok(GeneratedField::TotalStake), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTotalStakeResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTotalStakeResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut total_stake__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::TotalStake => { if total_stake__.is_some() { return Err(serde::de::Error::duplicate_field("totalStake")); } total_stake__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetTotalStakeResponse { wallet_name: wallet_name__.unwrap_or_default(), total_stake: total_stake__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTotalStakeResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.id.is_empty() { len += 1; } if self.verbosity != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTransactionRequest", len)?; if !self.id.is_empty() { struct_ser.serialize_field("id", &self.id)?; } if self.verbosity != 0 { let v = TransactionVerbosity::try_from(self.verbosity) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.verbosity)))?; struct_ser.serialize_field("verbosity", &v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "id", "verbosity", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Id, Verbosity, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "id" => Ok(GeneratedField::Id), "verbosity" => Ok(GeneratedField::Verbosity), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut id__ = None; let mut verbosity__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Id => { if id__.is_some() { return Err(serde::de::Error::duplicate_field("id")); } id__ = Some(map_.next_value()?); } GeneratedField::Verbosity => { if verbosity__.is_some() { return Err(serde::de::Error::duplicate_field("verbosity")); } verbosity__ = Some(map_.next_value::()? as i32); } } } Ok(GetTransactionRequest { id: id__.unwrap_or_default(), verbosity: verbosity__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTransactionResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.block_height != 0 { len += 1; } if self.block_time != 0 { len += 1; } if self.transaction.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTransactionResponse", len)?; if self.block_height != 0 { struct_ser.serialize_field("blockHeight", &self.block_height)?; } if self.block_time != 0 { struct_ser.serialize_field("blockTime", &self.block_time)?; } if let Some(v) = self.transaction.as_ref() { struct_ser.serialize_field("transaction", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTransactionResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "block_height", "blockHeight", "block_time", "blockTime", "transaction", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { BlockHeight, BlockTime, Transaction, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "blockHeight" | "block_height" => Ok(GeneratedField::BlockHeight), "blockTime" | "block_time" => Ok(GeneratedField::BlockTime), "transaction" => Ok(GeneratedField::Transaction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTransactionResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTransactionResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut block_height__ = None; let mut block_time__ = None; let mut transaction__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::BlockHeight => { if block_height__.is_some() { return Err(serde::de::Error::duplicate_field("blockHeight")); } block_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::BlockTime => { if block_time__.is_some() { return Err(serde::de::Error::duplicate_field("blockTime")); } block_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Transaction => { if transaction__.is_some() { return Err(serde::de::Error::duplicate_field("transaction")); } transaction__ = map_.next_value()?; } } } Ok(GetTransactionResponse { block_height: block_height__.unwrap_or_default(), block_time: block_time__.unwrap_or_default(), transaction: transaction__, }) } } deserializer.deserialize_struct("pactus.GetTransactionResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTxPoolContentRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.payload_type != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTxPoolContentRequest", len)?; if self.payload_type != 0 { let v = PayloadType::try_from(self.payload_type) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.payload_type)))?; struct_ser.serialize_field("payloadType", &v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTxPoolContentRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "payload_type", "payloadType", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PayloadType, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "payloadType" | "payload_type" => Ok(GeneratedField::PayloadType), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTxPoolContentRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTxPoolContentRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut payload_type__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PayloadType => { if payload_type__.is_some() { return Err(serde::de::Error::duplicate_field("payloadType")); } payload_type__ = Some(map_.next_value::()? as i32); } } } Ok(GetTxPoolContentRequest { payload_type: payload_type__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTxPoolContentRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetTxPoolContentResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.txs.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetTxPoolContentResponse", len)?; if !self.txs.is_empty() { struct_ser.serialize_field("txs", &self.txs)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetTxPoolContentResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "txs", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Txs, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "txs" => Ok(GeneratedField::Txs), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetTxPoolContentResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetTxPoolContentResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut txs__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Txs => { if txs__.is_some() { return Err(serde::de::Error::duplicate_field("txs")); } txs__ = Some(map_.next_value()?); } } } Ok(GetTxPoolContentResponse { txs: txs__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetTxPoolContentResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorAddressRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.public_key.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetValidatorAddressRequest", len)?; if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorAddressRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "public_key", "publicKey", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PublicKey, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorAddressRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorAddressRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut public_key__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } } } Ok(GetValidatorAddressRequest { public_key: public_key__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetValidatorAddressRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorAddressResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetValidatorAddressResponse", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorAddressResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorAddressResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorAddressResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(GetValidatorAddressResponse { address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetValidatorAddressResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorAddressesRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.GetValidatorAddressesRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorAddressesRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorAddressesRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorAddressesRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(GetValidatorAddressesRequest { }) } } deserializer.deserialize_struct("pactus.GetValidatorAddressesRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorAddressesResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.addresses.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetValidatorAddressesResponse", len)?; if !self.addresses.is_empty() { struct_ser.serialize_field("addresses", &self.addresses)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorAddressesResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "addresses", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Addresses, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "addresses" => Ok(GeneratedField::Addresses), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorAddressesResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorAddressesResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut addresses__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Addresses => { if addresses__.is_some() { return Err(serde::de::Error::duplicate_field("addresses")); } addresses__ = Some(map_.next_value()?); } } } Ok(GetValidatorAddressesResponse { addresses: addresses__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetValidatorAddressesResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorByNumberRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.number != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetValidatorByNumberRequest", len)?; if self.number != 0 { struct_ser.serialize_field("number", &self.number)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorByNumberRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "number", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Number, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "number" => Ok(GeneratedField::Number), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorByNumberRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorByNumberRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut number__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Number => { if number__.is_some() { return Err(serde::de::Error::duplicate_field("number")); } number__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(GetValidatorByNumberRequest { number: number__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetValidatorByNumberRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetValidatorRequest", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(GetValidatorRequest { address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetValidatorRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetValidatorResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.validator.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetValidatorResponse", len)?; if let Some(v) = self.validator.as_ref() { struct_ser.serialize_field("validator", v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetValidatorResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "validator", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Validator, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "validator" => Ok(GeneratedField::Validator), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetValidatorResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetValidatorResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut validator__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Validator => { if validator__.is_some() { return Err(serde::de::Error::duplicate_field("validator")); } validator__ = map_.next_value()?; } } } Ok(GetValidatorResponse { validator: validator__, }) } } deserializer.deserialize_struct("pactus.GetValidatorResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetWalletInfoRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetWalletInfoRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetWalletInfoRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetWalletInfoRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetWalletInfoRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(GetWalletInfoRequest { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetWalletInfoRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for GetWalletInfoResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.version != 0 { len += 1; } if !self.network.is_empty() { len += 1; } if self.encrypted { len += 1; } if !self.uuid.is_empty() { len += 1; } if self.created_at != 0 { len += 1; } if self.default_fee != 0 { len += 1; } if !self.driver.is_empty() { len += 1; } if !self.path.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.GetWalletInfoResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if self.version != 0 { struct_ser.serialize_field("version", &self.version)?; } if !self.network.is_empty() { struct_ser.serialize_field("network", &self.network)?; } if self.encrypted { struct_ser.serialize_field("encrypted", &self.encrypted)?; } if !self.uuid.is_empty() { struct_ser.serialize_field("uuid", &self.uuid)?; } if self.created_at != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("createdAt", ToString::to_string(&self.created_at).as_str())?; } if self.default_fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("defaultFee", ToString::to_string(&self.default_fee).as_str())?; } if !self.driver.is_empty() { struct_ser.serialize_field("driver", &self.driver)?; } if !self.path.is_empty() { struct_ser.serialize_field("path", &self.path)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for GetWalletInfoResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "version", "network", "encrypted", "uuid", "created_at", "createdAt", "default_fee", "defaultFee", "driver", "path", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Version, Network, Encrypted, Uuid, CreatedAt, DefaultFee, Driver, Path, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "version" => Ok(GeneratedField::Version), "network" => Ok(GeneratedField::Network), "encrypted" => Ok(GeneratedField::Encrypted), "uuid" => Ok(GeneratedField::Uuid), "createdAt" | "created_at" => Ok(GeneratedField::CreatedAt), "defaultFee" | "default_fee" => Ok(GeneratedField::DefaultFee), "driver" => Ok(GeneratedField::Driver), "path" => Ok(GeneratedField::Path), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GetWalletInfoResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.GetWalletInfoResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut version__ = None; let mut network__ = None; let mut encrypted__ = None; let mut uuid__ = None; let mut created_at__ = None; let mut default_fee__ = None; let mut driver__ = None; let mut path__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Version => { if version__.is_some() { return Err(serde::de::Error::duplicate_field("version")); } version__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Network => { if network__.is_some() { return Err(serde::de::Error::duplicate_field("network")); } network__ = Some(map_.next_value()?); } GeneratedField::Encrypted => { if encrypted__.is_some() { return Err(serde::de::Error::duplicate_field("encrypted")); } encrypted__ = Some(map_.next_value()?); } GeneratedField::Uuid => { if uuid__.is_some() { return Err(serde::de::Error::duplicate_field("uuid")); } uuid__ = Some(map_.next_value()?); } GeneratedField::CreatedAt => { if created_at__.is_some() { return Err(serde::de::Error::duplicate_field("createdAt")); } created_at__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::DefaultFee => { if default_fee__.is_some() { return Err(serde::de::Error::duplicate_field("defaultFee")); } default_fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Driver => { if driver__.is_some() { return Err(serde::de::Error::duplicate_field("driver")); } driver__ = Some(map_.next_value()?); } GeneratedField::Path => { if path__.is_some() { return Err(serde::de::Error::duplicate_field("path")); } path__ = Some(map_.next_value()?); } } } Ok(GetWalletInfoResponse { wallet_name: wallet_name__.unwrap_or_default(), version: version__.unwrap_or_default(), network: network__.unwrap_or_default(), encrypted: encrypted__.unwrap_or_default(), uuid: uuid__.unwrap_or_default(), created_at: created_at__.unwrap_or_default(), default_fee: default_fee__.unwrap_or_default(), driver: driver__.unwrap_or_default(), path: path__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.GetWalletInfoResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListAddressesRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.address_types.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListAddressesRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.address_types.is_empty() { let v = self.address_types.iter().cloned().map(|v| { AddressType::try_from(v) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", v))) }).collect::, _>>()?; struct_ser.serialize_field("addressTypes", &v)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListAddressesRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "address_types", "addressTypes", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, AddressTypes, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "addressTypes" | "address_types" => Ok(GeneratedField::AddressTypes), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListAddressesRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListAddressesRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut address_types__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::AddressTypes => { if address_types__.is_some() { return Err(serde::de::Error::duplicate_field("addressTypes")); } address_types__ = Some(map_.next_value::>()?.into_iter().map(|x| x as i32).collect()); } } } Ok(ListAddressesRequest { wallet_name: wallet_name__.unwrap_or_default(), address_types: address_types__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListAddressesRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListAddressesResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.addrs.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListAddressesResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.addrs.is_empty() { struct_ser.serialize_field("addrs", &self.addrs)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListAddressesResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "addrs", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Addrs, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "addrs" => Ok(GeneratedField::Addrs), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListAddressesResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListAddressesResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut addrs__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Addrs => { if addrs__.is_some() { return Err(serde::de::Error::duplicate_field("addrs")); } addrs__ = Some(map_.next_value()?); } } } Ok(ListAddressesResponse { wallet_name: wallet_name__.unwrap_or_default(), addrs: addrs__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListAddressesResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListPeersRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.include_disconnected { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListPeersRequest", len)?; if self.include_disconnected { struct_ser.serialize_field("includeDisconnected", &self.include_disconnected)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListPeersRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "include_disconnected", "includeDisconnected", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { IncludeDisconnected, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "includeDisconnected" | "include_disconnected" => Ok(GeneratedField::IncludeDisconnected), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListPeersRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListPeersRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut include_disconnected__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::IncludeDisconnected => { if include_disconnected__.is_some() { return Err(serde::de::Error::duplicate_field("includeDisconnected")); } include_disconnected__ = Some(map_.next_value()?); } } } Ok(ListPeersRequest { include_disconnected: include_disconnected__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListPeersRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListPeersResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.peers.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListPeersResponse", len)?; if !self.peers.is_empty() { struct_ser.serialize_field("peers", &self.peers)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListPeersResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "peers", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Peers, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "peers" => Ok(GeneratedField::Peers), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListPeersResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListPeersResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut peers__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Peers => { if peers__.is_some() { return Err(serde::de::Error::duplicate_field("peers")); } peers__ = Some(map_.next_value()?); } } } Ok(ListPeersResponse { peers: peers__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListPeersResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListTransactionsRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } if self.direction != 0 { len += 1; } if self.count != 0 { len += 1; } if self.skip != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListTransactionsRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if self.direction != 0 { let v = TxDirection::try_from(self.direction) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.direction)))?; struct_ser.serialize_field("direction", &v)?; } if self.count != 0 { struct_ser.serialize_field("count", &self.count)?; } if self.skip != 0 { struct_ser.serialize_field("skip", &self.skip)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListTransactionsRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "address", "direction", "count", "skip", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Address, Direction, Count, Skip, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "address" => Ok(GeneratedField::Address), "direction" => Ok(GeneratedField::Direction), "count" => Ok(GeneratedField::Count), "skip" => Ok(GeneratedField::Skip), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListTransactionsRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListTransactionsRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut address__ = None; let mut direction__ = None; let mut count__ = None; let mut skip__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Direction => { if direction__.is_some() { return Err(serde::de::Error::duplicate_field("direction")); } direction__ = Some(map_.next_value::()? as i32); } GeneratedField::Count => { if count__.is_some() { return Err(serde::de::Error::duplicate_field("count")); } count__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Skip => { if skip__.is_some() { return Err(serde::de::Error::duplicate_field("skip")); } skip__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(ListTransactionsRequest { wallet_name: wallet_name__.unwrap_or_default(), address: address__.unwrap_or_default(), direction: direction__.unwrap_or_default(), count: count__.unwrap_or_default(), skip: skip__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListTransactionsRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListTransactionsResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.txs.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListTransactionsResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.txs.is_empty() { struct_ser.serialize_field("txs", &self.txs)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListTransactionsResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "txs", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Txs, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "txs" => Ok(GeneratedField::Txs), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListTransactionsResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListTransactionsResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut txs__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Txs => { if txs__.is_some() { return Err(serde::de::Error::duplicate_field("txs")); } txs__ = Some(map_.next_value()?); } } } Ok(ListTransactionsResponse { wallet_name: wallet_name__.unwrap_or_default(), txs: txs__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListTransactionsResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListWalletsRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.ListWalletsRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListWalletsRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListWalletsRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListWalletsRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(ListWalletsRequest { }) } } deserializer.deserialize_struct("pactus.ListWalletsRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ListWalletsResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallets.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ListWalletsResponse", len)?; if !self.wallets.is_empty() { struct_ser.serialize_field("wallets", &self.wallets)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ListWalletsResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallets", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Wallets, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "wallets" => Ok(GeneratedField::Wallets), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ListWalletsResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ListWalletsResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallets__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Wallets => { if wallets__.is_some() { return Err(serde::de::Error::duplicate_field("wallets")); } wallets__ = Some(map_.next_value()?); } } } Ok(ListWalletsResponse { wallets: wallets__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ListWalletsResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for LoadWalletRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.LoadWalletRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for LoadWalletRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = LoadWalletRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.LoadWalletRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(LoadWalletRequest { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.LoadWalletRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for LoadWalletResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.LoadWalletResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for LoadWalletResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = LoadWalletResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.LoadWalletResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(LoadWalletResponse { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.LoadWalletResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for MetricInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.total_invalid.is_some() { len += 1; } if self.total_sent.is_some() { len += 1; } if self.total_received.is_some() { len += 1; } if !self.message_sent.is_empty() { len += 1; } if !self.message_received.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.MetricInfo", len)?; if let Some(v) = self.total_invalid.as_ref() { struct_ser.serialize_field("totalInvalid", v)?; } if let Some(v) = self.total_sent.as_ref() { struct_ser.serialize_field("totalSent", v)?; } if let Some(v) = self.total_received.as_ref() { struct_ser.serialize_field("totalReceived", v)?; } if !self.message_sent.is_empty() { struct_ser.serialize_field("messageSent", &self.message_sent)?; } if !self.message_received.is_empty() { struct_ser.serialize_field("messageReceived", &self.message_received)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for MetricInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "total_invalid", "totalInvalid", "total_sent", "totalSent", "total_received", "totalReceived", "message_sent", "messageSent", "message_received", "messageReceived", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { TotalInvalid, TotalSent, TotalReceived, MessageSent, MessageReceived, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "totalInvalid" | "total_invalid" => Ok(GeneratedField::TotalInvalid), "totalSent" | "total_sent" => Ok(GeneratedField::TotalSent), "totalReceived" | "total_received" => Ok(GeneratedField::TotalReceived), "messageSent" | "message_sent" => Ok(GeneratedField::MessageSent), "messageReceived" | "message_received" => Ok(GeneratedField::MessageReceived), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = MetricInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.MetricInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut total_invalid__ = None; let mut total_sent__ = None; let mut total_received__ = None; let mut message_sent__ = None; let mut message_received__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::TotalInvalid => { if total_invalid__.is_some() { return Err(serde::de::Error::duplicate_field("totalInvalid")); } total_invalid__ = map_.next_value()?; } GeneratedField::TotalSent => { if total_sent__.is_some() { return Err(serde::de::Error::duplicate_field("totalSent")); } total_sent__ = map_.next_value()?; } GeneratedField::TotalReceived => { if total_received__.is_some() { return Err(serde::de::Error::duplicate_field("totalReceived")); } total_received__ = map_.next_value()?; } GeneratedField::MessageSent => { if message_sent__.is_some() { return Err(serde::de::Error::duplicate_field("messageSent")); } message_sent__ = Some( map_.next_value::, _>>()? .into_iter().map(|(k,v)| (k.0, v)).collect() ); } GeneratedField::MessageReceived => { if message_received__.is_some() { return Err(serde::de::Error::duplicate_field("messageReceived")); } message_received__ = Some( map_.next_value::, _>>()? .into_iter().map(|(k,v)| (k.0, v)).collect() ); } } } Ok(MetricInfo { total_invalid: total_invalid__, total_sent: total_sent__, total_received: total_received__, message_sent: message_sent__.unwrap_or_default(), message_received: message_received__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.MetricInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PayloadBatchTransfer { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.sender.is_empty() { len += 1; } if !self.recipients.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PayloadBatchTransfer", len)?; if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.recipients.is_empty() { struct_ser.serialize_field("recipients", &self.recipients)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PayloadBatchTransfer { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "sender", "recipients", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Sender, Recipients, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "sender" => Ok(GeneratedField::Sender), "recipients" => Ok(GeneratedField::Recipients), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadBatchTransfer; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PayloadBatchTransfer") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut sender__ = None; let mut recipients__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Recipients => { if recipients__.is_some() { return Err(serde::de::Error::duplicate_field("recipients")); } recipients__ = Some(map_.next_value()?); } } } Ok(PayloadBatchTransfer { sender: sender__.unwrap_or_default(), recipients: recipients__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PayloadBatchTransfer", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PayloadBond { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.sender.is_empty() { len += 1; } if !self.receiver.is_empty() { len += 1; } if self.stake != 0 { len += 1; } if !self.public_key.is_empty() { len += 1; } if self.is_delegated { len += 1; } if !self.delegate_owner.is_empty() { len += 1; } if self.delegate_share != 0 { len += 1; } if self.delegate_expiry != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PayloadBond", len)?; if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.receiver.is_empty() { struct_ser.serialize_field("receiver", &self.receiver)?; } if self.stake != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("stake", ToString::to_string(&self.stake).as_str())?; } if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } if self.is_delegated { struct_ser.serialize_field("isDelegated", &self.is_delegated)?; } if !self.delegate_owner.is_empty() { struct_ser.serialize_field("delegateOwner", &self.delegate_owner)?; } if self.delegate_share != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("delegateShare", ToString::to_string(&self.delegate_share).as_str())?; } if self.delegate_expiry != 0 { struct_ser.serialize_field("delegateExpiry", &self.delegate_expiry)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PayloadBond { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "sender", "receiver", "stake", "public_key", "publicKey", "is_delegated", "isDelegated", "delegate_owner", "delegateOwner", "delegate_share", "delegateShare", "delegate_expiry", "delegateExpiry", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Sender, Receiver, Stake, PublicKey, IsDelegated, DelegateOwner, DelegateShare, DelegateExpiry, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "sender" => Ok(GeneratedField::Sender), "receiver" => Ok(GeneratedField::Receiver), "stake" => Ok(GeneratedField::Stake), "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), "isDelegated" | "is_delegated" => Ok(GeneratedField::IsDelegated), "delegateOwner" | "delegate_owner" => Ok(GeneratedField::DelegateOwner), "delegateShare" | "delegate_share" => Ok(GeneratedField::DelegateShare), "delegateExpiry" | "delegate_expiry" => Ok(GeneratedField::DelegateExpiry), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadBond; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PayloadBond") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut sender__ = None; let mut receiver__ = None; let mut stake__ = None; let mut public_key__ = None; let mut is_delegated__ = None; let mut delegate_owner__ = None; let mut delegate_share__ = None; let mut delegate_expiry__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Receiver => { if receiver__.is_some() { return Err(serde::de::Error::duplicate_field("receiver")); } receiver__ = Some(map_.next_value()?); } GeneratedField::Stake => { if stake__.is_some() { return Err(serde::de::Error::duplicate_field("stake")); } stake__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } GeneratedField::IsDelegated => { if is_delegated__.is_some() { return Err(serde::de::Error::duplicate_field("isDelegated")); } is_delegated__ = Some(map_.next_value()?); } GeneratedField::DelegateOwner => { if delegate_owner__.is_some() { return Err(serde::de::Error::duplicate_field("delegateOwner")); } delegate_owner__ = Some(map_.next_value()?); } GeneratedField::DelegateShare => { if delegate_share__.is_some() { return Err(serde::de::Error::duplicate_field("delegateShare")); } delegate_share__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::DelegateExpiry => { if delegate_expiry__.is_some() { return Err(serde::de::Error::duplicate_field("delegateExpiry")); } delegate_expiry__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(PayloadBond { sender: sender__.unwrap_or_default(), receiver: receiver__.unwrap_or_default(), stake: stake__.unwrap_or_default(), public_key: public_key__.unwrap_or_default(), is_delegated: is_delegated__.unwrap_or_default(), delegate_owner: delegate_owner__.unwrap_or_default(), delegate_share: delegate_share__.unwrap_or_default(), delegate_expiry: delegate_expiry__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PayloadBond", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PayloadSortition { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.address.is_empty() { len += 1; } if !self.proof.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PayloadSortition", len)?; if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if !self.proof.is_empty() { struct_ser.serialize_field("proof", &self.proof)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PayloadSortition { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "address", "proof", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Address, Proof, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "address" => Ok(GeneratedField::Address), "proof" => Ok(GeneratedField::Proof), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadSortition; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PayloadSortition") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut address__ = None; let mut proof__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Proof => { if proof__.is_some() { return Err(serde::de::Error::duplicate_field("proof")); } proof__ = Some(map_.next_value()?); } } } Ok(PayloadSortition { address: address__.unwrap_or_default(), proof: proof__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PayloadSortition", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PayloadTransfer { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.sender.is_empty() { len += 1; } if !self.receiver.is_empty() { len += 1; } if self.amount != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PayloadTransfer", len)?; if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.receiver.is_empty() { struct_ser.serialize_field("receiver", &self.receiver)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PayloadTransfer { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "sender", "receiver", "amount", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Sender, Receiver, Amount, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "sender" => Ok(GeneratedField::Sender), "receiver" => Ok(GeneratedField::Receiver), "amount" => Ok(GeneratedField::Amount), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadTransfer; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PayloadTransfer") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut sender__ = None; let mut receiver__ = None; let mut amount__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Receiver => { if receiver__.is_some() { return Err(serde::de::Error::duplicate_field("receiver")); } receiver__ = Some(map_.next_value()?); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(PayloadTransfer { sender: sender__.unwrap_or_default(), receiver: receiver__.unwrap_or_default(), amount: amount__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PayloadTransfer", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PayloadType { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Unspecified => "PAYLOAD_TYPE_UNSPECIFIED", Self::Transfer => "PAYLOAD_TYPE_TRANSFER", Self::Bond => "PAYLOAD_TYPE_BOND", Self::Sortition => "PAYLOAD_TYPE_SORTITION", Self::Unbond => "PAYLOAD_TYPE_UNBOND", Self::Withdraw => "PAYLOAD_TYPE_WITHDRAW", Self::BatchTransfer => "PAYLOAD_TYPE_BATCH_TRANSFER", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for PayloadType { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "PAYLOAD_TYPE_UNSPECIFIED", "PAYLOAD_TYPE_TRANSFER", "PAYLOAD_TYPE_BOND", "PAYLOAD_TYPE_SORTITION", "PAYLOAD_TYPE_UNBOND", "PAYLOAD_TYPE_WITHDRAW", "PAYLOAD_TYPE_BATCH_TRANSFER", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadType; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "PAYLOAD_TYPE_UNSPECIFIED" => Ok(PayloadType::Unspecified), "PAYLOAD_TYPE_TRANSFER" => Ok(PayloadType::Transfer), "PAYLOAD_TYPE_BOND" => Ok(PayloadType::Bond), "PAYLOAD_TYPE_SORTITION" => Ok(PayloadType::Sortition), "PAYLOAD_TYPE_UNBOND" => Ok(PayloadType::Unbond), "PAYLOAD_TYPE_WITHDRAW" => Ok(PayloadType::Withdraw), "PAYLOAD_TYPE_BATCH_TRANSFER" => Ok(PayloadType::BatchTransfer), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for PayloadUnbond { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.validator.is_empty() { len += 1; } if !self.delegate_owner.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PayloadUnbond", len)?; if !self.validator.is_empty() { struct_ser.serialize_field("validator", &self.validator)?; } if !self.delegate_owner.is_empty() { struct_ser.serialize_field("delegateOwner", &self.delegate_owner)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PayloadUnbond { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "validator", "delegate_owner", "delegateOwner", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Validator, DelegateOwner, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "validator" => Ok(GeneratedField::Validator), "delegateOwner" | "delegate_owner" => Ok(GeneratedField::DelegateOwner), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadUnbond; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PayloadUnbond") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut validator__ = None; let mut delegate_owner__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Validator => { if validator__.is_some() { return Err(serde::de::Error::duplicate_field("validator")); } validator__ = Some(map_.next_value()?); } GeneratedField::DelegateOwner => { if delegate_owner__.is_some() { return Err(serde::de::Error::duplicate_field("delegateOwner")); } delegate_owner__ = Some(map_.next_value()?); } } } Ok(PayloadUnbond { validator: validator__.unwrap_or_default(), delegate_owner: delegate_owner__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PayloadUnbond", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PayloadWithdraw { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.validator_address.is_empty() { len += 1; } if !self.account_address.is_empty() { len += 1; } if self.amount != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PayloadWithdraw", len)?; if !self.validator_address.is_empty() { struct_ser.serialize_field("validatorAddress", &self.validator_address)?; } if !self.account_address.is_empty() { struct_ser.serialize_field("accountAddress", &self.account_address)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PayloadWithdraw { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "validator_address", "validatorAddress", "account_address", "accountAddress", "amount", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { ValidatorAddress, AccountAddress, Amount, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "validatorAddress" | "validator_address" => Ok(GeneratedField::ValidatorAddress), "accountAddress" | "account_address" => Ok(GeneratedField::AccountAddress), "amount" => Ok(GeneratedField::Amount), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PayloadWithdraw; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PayloadWithdraw") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut validator_address__ = None; let mut account_address__ = None; let mut amount__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::ValidatorAddress => { if validator_address__.is_some() { return Err(serde::de::Error::duplicate_field("validatorAddress")); } validator_address__ = Some(map_.next_value()?); } GeneratedField::AccountAddress => { if account_address__.is_some() { return Err(serde::de::Error::duplicate_field("accountAddress")); } account_address__ = Some(map_.next_value()?); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(PayloadWithdraw { validator_address: validator_address__.unwrap_or_default(), account_address: account_address__.unwrap_or_default(), amount: amount__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PayloadWithdraw", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PeerInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.status != 0 { len += 1; } if !self.moniker.is_empty() { len += 1; } if !self.agent.is_empty() { len += 1; } if !self.peer_id.is_empty() { len += 1; } if !self.consensus_keys.is_empty() { len += 1; } if !self.consensus_addresses.is_empty() { len += 1; } if self.services != 0 { len += 1; } if !self.last_block_hash.is_empty() { len += 1; } if self.height != 0 { len += 1; } if self.last_sent != 0 { len += 1; } if self.last_received != 0 { len += 1; } if !self.address.is_empty() { len += 1; } if self.direction != 0 { len += 1; } if !self.protocols.is_empty() { len += 1; } if self.total_sessions != 0 { len += 1; } if self.completed_sessions != 0 { len += 1; } if self.metric_info.is_some() { len += 1; } if self.outbound_hello_sent { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PeerInfo", len)?; if self.status != 0 { struct_ser.serialize_field("status", &self.status)?; } if !self.moniker.is_empty() { struct_ser.serialize_field("moniker", &self.moniker)?; } if !self.agent.is_empty() { struct_ser.serialize_field("agent", &self.agent)?; } if !self.peer_id.is_empty() { struct_ser.serialize_field("peerId", &self.peer_id)?; } if !self.consensus_keys.is_empty() { struct_ser.serialize_field("consensusKeys", &self.consensus_keys)?; } if !self.consensus_addresses.is_empty() { struct_ser.serialize_field("consensusAddresses", &self.consensus_addresses)?; } if self.services != 0 { struct_ser.serialize_field("services", &self.services)?; } if !self.last_block_hash.is_empty() { struct_ser.serialize_field("lastBlockHash", &self.last_block_hash)?; } if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } if self.last_sent != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("lastSent", ToString::to_string(&self.last_sent).as_str())?; } if self.last_received != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("lastReceived", ToString::to_string(&self.last_received).as_str())?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if self.direction != 0 { let v = Direction::try_from(self.direction) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.direction)))?; struct_ser.serialize_field("direction", &v)?; } if !self.protocols.is_empty() { struct_ser.serialize_field("protocols", &self.protocols)?; } if self.total_sessions != 0 { struct_ser.serialize_field("totalSessions", &self.total_sessions)?; } if self.completed_sessions != 0 { struct_ser.serialize_field("completedSessions", &self.completed_sessions)?; } if let Some(v) = self.metric_info.as_ref() { struct_ser.serialize_field("metricInfo", v)?; } if self.outbound_hello_sent { struct_ser.serialize_field("outboundHelloSent", &self.outbound_hello_sent)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PeerInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "status", "moniker", "agent", "peer_id", "peerId", "consensus_keys", "consensusKeys", "consensus_addresses", "consensusAddresses", "services", "last_block_hash", "lastBlockHash", "height", "last_sent", "lastSent", "last_received", "lastReceived", "address", "direction", "protocols", "total_sessions", "totalSessions", "completed_sessions", "completedSessions", "metric_info", "metricInfo", "outbound_hello_sent", "outboundHelloSent", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Status, Moniker, Agent, PeerId, ConsensusKeys, ConsensusAddresses, Services, LastBlockHash, Height, LastSent, LastReceived, Address, Direction, Protocols, TotalSessions, CompletedSessions, MetricInfo, OutboundHelloSent, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "status" => Ok(GeneratedField::Status), "moniker" => Ok(GeneratedField::Moniker), "agent" => Ok(GeneratedField::Agent), "peerId" | "peer_id" => Ok(GeneratedField::PeerId), "consensusKeys" | "consensus_keys" => Ok(GeneratedField::ConsensusKeys), "consensusAddresses" | "consensus_addresses" => Ok(GeneratedField::ConsensusAddresses), "services" => Ok(GeneratedField::Services), "lastBlockHash" | "last_block_hash" => Ok(GeneratedField::LastBlockHash), "height" => Ok(GeneratedField::Height), "lastSent" | "last_sent" => Ok(GeneratedField::LastSent), "lastReceived" | "last_received" => Ok(GeneratedField::LastReceived), "address" => Ok(GeneratedField::Address), "direction" => Ok(GeneratedField::Direction), "protocols" => Ok(GeneratedField::Protocols), "totalSessions" | "total_sessions" => Ok(GeneratedField::TotalSessions), "completedSessions" | "completed_sessions" => Ok(GeneratedField::CompletedSessions), "metricInfo" | "metric_info" => Ok(GeneratedField::MetricInfo), "outboundHelloSent" | "outbound_hello_sent" => Ok(GeneratedField::OutboundHelloSent), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PeerInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PeerInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut status__ = None; let mut moniker__ = None; let mut agent__ = None; let mut peer_id__ = None; let mut consensus_keys__ = None; let mut consensus_addresses__ = None; let mut services__ = None; let mut last_block_hash__ = None; let mut height__ = None; let mut last_sent__ = None; let mut last_received__ = None; let mut address__ = None; let mut direction__ = None; let mut protocols__ = None; let mut total_sessions__ = None; let mut completed_sessions__ = None; let mut metric_info__ = None; let mut outbound_hello_sent__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Status => { if status__.is_some() { return Err(serde::de::Error::duplicate_field("status")); } status__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Moniker => { if moniker__.is_some() { return Err(serde::de::Error::duplicate_field("moniker")); } moniker__ = Some(map_.next_value()?); } GeneratedField::Agent => { if agent__.is_some() { return Err(serde::de::Error::duplicate_field("agent")); } agent__ = Some(map_.next_value()?); } GeneratedField::PeerId => { if peer_id__.is_some() { return Err(serde::de::Error::duplicate_field("peerId")); } peer_id__ = Some(map_.next_value()?); } GeneratedField::ConsensusKeys => { if consensus_keys__.is_some() { return Err(serde::de::Error::duplicate_field("consensusKeys")); } consensus_keys__ = Some(map_.next_value()?); } GeneratedField::ConsensusAddresses => { if consensus_addresses__.is_some() { return Err(serde::de::Error::duplicate_field("consensusAddresses")); } consensus_addresses__ = Some(map_.next_value()?); } GeneratedField::Services => { if services__.is_some() { return Err(serde::de::Error::duplicate_field("services")); } services__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LastBlockHash => { if last_block_hash__.is_some() { return Err(serde::de::Error::duplicate_field("lastBlockHash")); } last_block_hash__ = Some(map_.next_value()?); } GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LastSent => { if last_sent__.is_some() { return Err(serde::de::Error::duplicate_field("lastSent")); } last_sent__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LastReceived => { if last_received__.is_some() { return Err(serde::de::Error::duplicate_field("lastReceived")); } last_received__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Direction => { if direction__.is_some() { return Err(serde::de::Error::duplicate_field("direction")); } direction__ = Some(map_.next_value::()? as i32); } GeneratedField::Protocols => { if protocols__.is_some() { return Err(serde::de::Error::duplicate_field("protocols")); } protocols__ = Some(map_.next_value()?); } GeneratedField::TotalSessions => { if total_sessions__.is_some() { return Err(serde::de::Error::duplicate_field("totalSessions")); } total_sessions__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::CompletedSessions => { if completed_sessions__.is_some() { return Err(serde::de::Error::duplicate_field("completedSessions")); } completed_sessions__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::MetricInfo => { if metric_info__.is_some() { return Err(serde::de::Error::duplicate_field("metricInfo")); } metric_info__ = map_.next_value()?; } GeneratedField::OutboundHelloSent => { if outbound_hello_sent__.is_some() { return Err(serde::de::Error::duplicate_field("outboundHelloSent")); } outbound_hello_sent__ = Some(map_.next_value()?); } } } Ok(PeerInfo { status: status__.unwrap_or_default(), moniker: moniker__.unwrap_or_default(), agent: agent__.unwrap_or_default(), peer_id: peer_id__.unwrap_or_default(), consensus_keys: consensus_keys__.unwrap_or_default(), consensus_addresses: consensus_addresses__.unwrap_or_default(), services: services__.unwrap_or_default(), last_block_hash: last_block_hash__.unwrap_or_default(), height: height__.unwrap_or_default(), last_sent: last_sent__.unwrap_or_default(), last_received: last_received__.unwrap_or_default(), address: address__.unwrap_or_default(), direction: direction__.unwrap_or_default(), protocols: protocols__.unwrap_or_default(), total_sessions: total_sessions__.unwrap_or_default(), completed_sessions: completed_sessions__.unwrap_or_default(), metric_info: metric_info__, outbound_hello_sent: outbound_hello_sent__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PeerInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PingRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.PingRequest", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PingRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PingRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PingRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(PingRequest { }) } } deserializer.deserialize_struct("pactus.PingRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PingResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let len = 0; let struct_ser = serializer.serialize_struct("pactus.PingResponse", len)?; struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PingResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { Err(serde::de::Error::unknown_field(value, FIELDS)) } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PingResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PingResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { while map_.next_key::()?.is_some() { let _ = map_.next_value::()?; } Ok(PingResponse { }) } } deserializer.deserialize_struct("pactus.PingResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ProposalInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.height != 0 { len += 1; } if self.round != 0 { len += 1; } if !self.block_data.is_empty() { len += 1; } if !self.signature.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ProposalInfo", len)?; if self.height != 0 { struct_ser.serialize_field("height", &self.height)?; } if self.round != 0 { struct_ser.serialize_field("round", &self.round)?; } if !self.block_data.is_empty() { struct_ser.serialize_field("blockData", &self.block_data)?; } if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ProposalInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "height", "round", "block_data", "blockData", "signature", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Height, Round, BlockData, Signature, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "height" => Ok(GeneratedField::Height), "round" => Ok(GeneratedField::Round), "blockData" | "block_data" => Ok(GeneratedField::BlockData), "signature" => Ok(GeneratedField::Signature), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ProposalInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ProposalInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut height__ = None; let mut round__ = None; let mut block_data__ = None; let mut signature__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Height => { if height__.is_some() { return Err(serde::de::Error::duplicate_field("height")); } height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Round => { if round__.is_some() { return Err(serde::de::Error::duplicate_field("round")); } round__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::BlockData => { if block_data__.is_some() { return Err(serde::de::Error::duplicate_field("blockData")); } block_data__ = Some(map_.next_value()?); } GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } } } Ok(ProposalInfo { height: height__.unwrap_or_default(), round: round__.unwrap_or_default(), block_data: block_data__.unwrap_or_default(), signature: signature__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ProposalInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PublicKeyAggregationRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.public_keys.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PublicKeyAggregationRequest", len)?; if !self.public_keys.is_empty() { struct_ser.serialize_field("publicKeys", &self.public_keys)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PublicKeyAggregationRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "public_keys", "publicKeys", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PublicKeys, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "publicKeys" | "public_keys" => Ok(GeneratedField::PublicKeys), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PublicKeyAggregationRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PublicKeyAggregationRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut public_keys__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PublicKeys => { if public_keys__.is_some() { return Err(serde::de::Error::duplicate_field("publicKeys")); } public_keys__ = Some(map_.next_value()?); } } } Ok(PublicKeyAggregationRequest { public_keys: public_keys__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PublicKeyAggregationRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for PublicKeyAggregationResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.public_key.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.PublicKeyAggregationResponse", len)?; if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for PublicKeyAggregationResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "public_key", "publicKey", "address", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PublicKey, Address, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), "address" => Ok(GeneratedField::Address), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = PublicKeyAggregationResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.PublicKeyAggregationResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut public_key__ = None; let mut address__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } } } Ok(PublicKeyAggregationResponse { public_key: public_key__.unwrap_or_default(), address: address__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.PublicKeyAggregationResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for Recipient { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.receiver.is_empty() { len += 1; } if self.amount != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.Recipient", len)?; if !self.receiver.is_empty() { struct_ser.serialize_field("receiver", &self.receiver)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for Recipient { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "receiver", "amount", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Receiver, Amount, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "receiver" => Ok(GeneratedField::Receiver), "amount" => Ok(GeneratedField::Amount), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = Recipient; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.Recipient") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut receiver__ = None; let mut amount__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Receiver => { if receiver__.is_some() { return Err(serde::de::Error::duplicate_field("receiver")); } receiver__ = Some(map_.next_value()?); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(Recipient { receiver: receiver__.unwrap_or_default(), amount: amount__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.Recipient", FIELDS, GeneratedVisitor) } } impl serde::Serialize for RestoreWalletRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.mnemonic.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.RestoreWalletRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.mnemonic.is_empty() { struct_ser.serialize_field("mnemonic", &self.mnemonic)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for RestoreWalletRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "mnemonic", "password", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Mnemonic, Password, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "mnemonic" => Ok(GeneratedField::Mnemonic), "password" => Ok(GeneratedField::Password), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = RestoreWalletRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.RestoreWalletRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut mnemonic__ = None; let mut password__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Mnemonic => { if mnemonic__.is_some() { return Err(serde::de::Error::duplicate_field("mnemonic")); } mnemonic__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } } } Ok(RestoreWalletRequest { wallet_name: wallet_name__.unwrap_or_default(), mnemonic: mnemonic__.unwrap_or_default(), password: password__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.RestoreWalletRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for RestoreWalletResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.RestoreWalletResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for RestoreWalletResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = RestoreWalletResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.RestoreWalletResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(RestoreWalletResponse { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.RestoreWalletResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SetAddressLabelRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } if !self.label.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SetAddressLabelRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if !self.label.is_empty() { struct_ser.serialize_field("label", &self.label)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SetAddressLabelRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "password", "address", "label", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Password, Address, Label, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "password" => Ok(GeneratedField::Password), "address" => Ok(GeneratedField::Address), "label" => Ok(GeneratedField::Label), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SetAddressLabelRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SetAddressLabelRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut password__ = None; let mut address__ = None; let mut label__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Label => { if label__.is_some() { return Err(serde::de::Error::duplicate_field("label")); } label__ = Some(map_.next_value()?); } } } Ok(SetAddressLabelRequest { wallet_name: wallet_name__.unwrap_or_default(), password: password__.unwrap_or_default(), address: address__.unwrap_or_default(), label: label__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SetAddressLabelRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SetAddressLabelResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } if !self.label.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SetAddressLabelResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if !self.label.is_empty() { struct_ser.serialize_field("label", &self.label)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SetAddressLabelResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "address", "label", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Address, Label, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "address" => Ok(GeneratedField::Address), "label" => Ok(GeneratedField::Label), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SetAddressLabelResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SetAddressLabelResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut address__ = None; let mut label__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Label => { if label__.is_some() { return Err(serde::de::Error::duplicate_field("label")); } label__ = Some(map_.next_value()?); } } } Ok(SetAddressLabelResponse { wallet_name: wallet_name__.unwrap_or_default(), address: address__.unwrap_or_default(), label: label__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SetAddressLabelResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SetDefaultFeeRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if self.amount != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SetDefaultFeeRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SetDefaultFeeRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "amount", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Amount, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "amount" => Ok(GeneratedField::Amount), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SetDefaultFeeRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SetDefaultFeeRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut amount__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(SetDefaultFeeRequest { wallet_name: wallet_name__.unwrap_or_default(), amount: amount__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SetDefaultFeeRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SetDefaultFeeResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SetDefaultFeeResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SetDefaultFeeResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SetDefaultFeeResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SetDefaultFeeResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(SetDefaultFeeResponse { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SetDefaultFeeResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignMessageRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } if !self.message.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignMessageRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if !self.message.is_empty() { struct_ser.serialize_field("message", &self.message)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignMessageRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "password", "address", "message", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, Password, Address, Message, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "password" => Ok(GeneratedField::Password), "address" => Ok(GeneratedField::Address), "message" => Ok(GeneratedField::Message), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignMessageRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignMessageRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut password__ = None; let mut address__ = None; let mut message__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Message => { if message__.is_some() { return Err(serde::de::Error::duplicate_field("message")); } message__ = Some(map_.next_value()?); } } } Ok(SignMessageRequest { wallet_name: wallet_name__.unwrap_or_default(), password: password__.unwrap_or_default(), address: address__.unwrap_or_default(), message: message__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignMessageRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignMessageResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.signature.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignMessageResponse", len)?; if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignMessageResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "signature", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Signature, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "signature" => Ok(GeneratedField::Signature), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignMessageResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignMessageResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut signature__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } } } Ok(SignMessageResponse { signature: signature__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignMessageResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignMessageWithPrivateKeyRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.private_key.is_empty() { len += 1; } if !self.message.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignMessageWithPrivateKeyRequest", len)?; if !self.private_key.is_empty() { struct_ser.serialize_field("privateKey", &self.private_key)?; } if !self.message.is_empty() { struct_ser.serialize_field("message", &self.message)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignMessageWithPrivateKeyRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "private_key", "privateKey", "message", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { PrivateKey, Message, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "privateKey" | "private_key" => Ok(GeneratedField::PrivateKey), "message" => Ok(GeneratedField::Message), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignMessageWithPrivateKeyRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignMessageWithPrivateKeyRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut private_key__ = None; let mut message__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::PrivateKey => { if private_key__.is_some() { return Err(serde::de::Error::duplicate_field("privateKey")); } private_key__ = Some(map_.next_value()?); } GeneratedField::Message => { if message__.is_some() { return Err(serde::de::Error::duplicate_field("message")); } message__ = Some(map_.next_value()?); } } } Ok(SignMessageWithPrivateKeyRequest { private_key: private_key__.unwrap_or_default(), message: message__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignMessageWithPrivateKeyRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignMessageWithPrivateKeyResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.signature.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignMessageWithPrivateKeyResponse", len)?; if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignMessageWithPrivateKeyResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "signature", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Signature, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "signature" => Ok(GeneratedField::Signature), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignMessageWithPrivateKeyResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignMessageWithPrivateKeyResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut signature__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } } } Ok(SignMessageWithPrivateKeyResponse { signature: signature__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignMessageWithPrivateKeyResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignRawTransactionRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.raw_transaction.is_empty() { len += 1; } if !self.password.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignRawTransactionRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.raw_transaction.is_empty() { struct_ser.serialize_field("rawTransaction", &self.raw_transaction)?; } if !self.password.is_empty() { struct_ser.serialize_field("password", &self.password)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignRawTransactionRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "raw_transaction", "rawTransaction", "password", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, RawTransaction, Password, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "rawTransaction" | "raw_transaction" => Ok(GeneratedField::RawTransaction), "password" => Ok(GeneratedField::Password), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignRawTransactionRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignRawTransactionRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut raw_transaction__ = None; let mut password__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::RawTransaction => { if raw_transaction__.is_some() { return Err(serde::de::Error::duplicate_field("rawTransaction")); } raw_transaction__ = Some(map_.next_value()?); } GeneratedField::Password => { if password__.is_some() { return Err(serde::de::Error::duplicate_field("password")); } password__ = Some(map_.next_value()?); } } } Ok(SignRawTransactionRequest { wallet_name: wallet_name__.unwrap_or_default(), raw_transaction: raw_transaction__.unwrap_or_default(), password: password__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignRawTransactionRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignRawTransactionResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.transaction_id.is_empty() { len += 1; } if !self.signed_raw_transaction.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignRawTransactionResponse", len)?; if !self.transaction_id.is_empty() { struct_ser.serialize_field("transactionId", &self.transaction_id)?; } if !self.signed_raw_transaction.is_empty() { struct_ser.serialize_field("signedRawTransaction", &self.signed_raw_transaction)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignRawTransactionResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "transaction_id", "transactionId", "signed_raw_transaction", "signedRawTransaction", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { TransactionId, SignedRawTransaction, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "transactionId" | "transaction_id" => Ok(GeneratedField::TransactionId), "signedRawTransaction" | "signed_raw_transaction" => Ok(GeneratedField::SignedRawTransaction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignRawTransactionResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignRawTransactionResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut transaction_id__ = None; let mut signed_raw_transaction__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::TransactionId => { if transaction_id__.is_some() { return Err(serde::de::Error::duplicate_field("transactionId")); } transaction_id__ = Some(map_.next_value()?); } GeneratedField::SignedRawTransaction => { if signed_raw_transaction__.is_some() { return Err(serde::de::Error::duplicate_field("signedRawTransaction")); } signed_raw_transaction__ = Some(map_.next_value()?); } } } Ok(SignRawTransactionResponse { transaction_id: transaction_id__.unwrap_or_default(), signed_raw_transaction: signed_raw_transaction__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignRawTransactionResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignatureAggregationRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.signatures.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignatureAggregationRequest", len)?; if !self.signatures.is_empty() { struct_ser.serialize_field("signatures", &self.signatures)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignatureAggregationRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "signatures", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Signatures, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "signatures" => Ok(GeneratedField::Signatures), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignatureAggregationRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignatureAggregationRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut signatures__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Signatures => { if signatures__.is_some() { return Err(serde::de::Error::duplicate_field("signatures")); } signatures__ = Some(map_.next_value()?); } } } Ok(SignatureAggregationRequest { signatures: signatures__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignatureAggregationRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for SignatureAggregationResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.signature.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.SignatureAggregationResponse", len)?; if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for SignatureAggregationResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "signature", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Signature, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "signature" => Ok(GeneratedField::Signature), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = SignatureAggregationResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.SignatureAggregationResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut signature__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } } } Ok(SignatureAggregationResponse { signature: signature__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.SignatureAggregationResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for TransactionInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.id.is_empty() { len += 1; } if !self.data.is_empty() { len += 1; } if self.version != 0 { len += 1; } if self.lock_time != 0 { len += 1; } if self.value != 0 { len += 1; } if self.fee != 0 { len += 1; } if self.payload_type != 0 { len += 1; } if !self.memo.is_empty() { len += 1; } if !self.public_key.is_empty() { len += 1; } if !self.signature.is_empty() { len += 1; } if self.block_height != 0 { len += 1; } if self.confirmed { len += 1; } if self.confirmations != 0 { len += 1; } if self.payload.is_some() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.TransactionInfo", len)?; if !self.id.is_empty() { struct_ser.serialize_field("id", &self.id)?; } if !self.data.is_empty() { struct_ser.serialize_field("data", &self.data)?; } if self.version != 0 { struct_ser.serialize_field("version", &self.version)?; } if self.lock_time != 0 { struct_ser.serialize_field("lockTime", &self.lock_time)?; } if self.value != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("value", ToString::to_string(&self.value).as_str())?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } if self.payload_type != 0 { let v = PayloadType::try_from(self.payload_type) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.payload_type)))?; struct_ser.serialize_field("payloadType", &v)?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } if self.block_height != 0 { struct_ser.serialize_field("blockHeight", &self.block_height)?; } if self.confirmed { struct_ser.serialize_field("confirmed", &self.confirmed)?; } if self.confirmations != 0 { struct_ser.serialize_field("confirmations", &self.confirmations)?; } if let Some(v) = self.payload.as_ref() { match v { transaction_info::Payload::Transfer(v) => { struct_ser.serialize_field("transfer", v)?; } transaction_info::Payload::Bond(v) => { struct_ser.serialize_field("bond", v)?; } transaction_info::Payload::Sortition(v) => { struct_ser.serialize_field("sortition", v)?; } transaction_info::Payload::Unbond(v) => { struct_ser.serialize_field("unbond", v)?; } transaction_info::Payload::Withdraw(v) => { struct_ser.serialize_field("withdraw", v)?; } transaction_info::Payload::BatchTransfer(v) => { struct_ser.serialize_field("batchTransfer", v)?; } } } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for TransactionInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "id", "data", "version", "lock_time", "lockTime", "value", "fee", "payload_type", "payloadType", "memo", "public_key", "publicKey", "signature", "block_height", "blockHeight", "confirmed", "confirmations", "transfer", "bond", "sortition", "unbond", "withdraw", "batch_transfer", "batchTransfer", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Id, Data, Version, LockTime, Value, Fee, PayloadType, Memo, PublicKey, Signature, BlockHeight, Confirmed, Confirmations, Transfer, Bond, Sortition, Unbond, Withdraw, BatchTransfer, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "id" => Ok(GeneratedField::Id), "data" => Ok(GeneratedField::Data), "version" => Ok(GeneratedField::Version), "lockTime" | "lock_time" => Ok(GeneratedField::LockTime), "value" => Ok(GeneratedField::Value), "fee" => Ok(GeneratedField::Fee), "payloadType" | "payload_type" => Ok(GeneratedField::PayloadType), "memo" => Ok(GeneratedField::Memo), "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), "signature" => Ok(GeneratedField::Signature), "blockHeight" | "block_height" => Ok(GeneratedField::BlockHeight), "confirmed" => Ok(GeneratedField::Confirmed), "confirmations" => Ok(GeneratedField::Confirmations), "transfer" => Ok(GeneratedField::Transfer), "bond" => Ok(GeneratedField::Bond), "sortition" => Ok(GeneratedField::Sortition), "unbond" => Ok(GeneratedField::Unbond), "withdraw" => Ok(GeneratedField::Withdraw), "batchTransfer" | "batch_transfer" => Ok(GeneratedField::BatchTransfer), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = TransactionInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.TransactionInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut id__ = None; let mut data__ = None; let mut version__ = None; let mut lock_time__ = None; let mut value__ = None; let mut fee__ = None; let mut payload_type__ = None; let mut memo__ = None; let mut public_key__ = None; let mut signature__ = None; let mut block_height__ = None; let mut confirmed__ = None; let mut confirmations__ = None; let mut payload__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Id => { if id__.is_some() { return Err(serde::de::Error::duplicate_field("id")); } id__ = Some(map_.next_value()?); } GeneratedField::Data => { if data__.is_some() { return Err(serde::de::Error::duplicate_field("data")); } data__ = Some(map_.next_value()?); } GeneratedField::Version => { if version__.is_some() { return Err(serde::de::Error::duplicate_field("version")); } version__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LockTime => { if lock_time__.is_some() { return Err(serde::de::Error::duplicate_field("lockTime")); } lock_time__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Value => { if value__.is_some() { return Err(serde::de::Error::duplicate_field("value")); } value__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::PayloadType => { if payload_type__.is_some() { return Err(serde::de::Error::duplicate_field("payloadType")); } payload_type__ = Some(map_.next_value::()? as i32); } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } GeneratedField::BlockHeight => { if block_height__.is_some() { return Err(serde::de::Error::duplicate_field("blockHeight")); } block_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Confirmed => { if confirmed__.is_some() { return Err(serde::de::Error::duplicate_field("confirmed")); } confirmed__ = Some(map_.next_value()?); } GeneratedField::Confirmations => { if confirmations__.is_some() { return Err(serde::de::Error::duplicate_field("confirmations")); } confirmations__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Transfer => { if payload__.is_some() { return Err(serde::de::Error::duplicate_field("transfer")); } payload__ = map_.next_value::<::std::option::Option<_>>()?.map(transaction_info::Payload::Transfer) ; } GeneratedField::Bond => { if payload__.is_some() { return Err(serde::de::Error::duplicate_field("bond")); } payload__ = map_.next_value::<::std::option::Option<_>>()?.map(transaction_info::Payload::Bond) ; } GeneratedField::Sortition => { if payload__.is_some() { return Err(serde::de::Error::duplicate_field("sortition")); } payload__ = map_.next_value::<::std::option::Option<_>>()?.map(transaction_info::Payload::Sortition) ; } GeneratedField::Unbond => { if payload__.is_some() { return Err(serde::de::Error::duplicate_field("unbond")); } payload__ = map_.next_value::<::std::option::Option<_>>()?.map(transaction_info::Payload::Unbond) ; } GeneratedField::Withdraw => { if payload__.is_some() { return Err(serde::de::Error::duplicate_field("withdraw")); } payload__ = map_.next_value::<::std::option::Option<_>>()?.map(transaction_info::Payload::Withdraw) ; } GeneratedField::BatchTransfer => { if payload__.is_some() { return Err(serde::de::Error::duplicate_field("batchTransfer")); } payload__ = map_.next_value::<::std::option::Option<_>>()?.map(transaction_info::Payload::BatchTransfer) ; } } } Ok(TransactionInfo { id: id__.unwrap_or_default(), data: data__.unwrap_or_default(), version: version__.unwrap_or_default(), lock_time: lock_time__.unwrap_or_default(), value: value__.unwrap_or_default(), fee: fee__.unwrap_or_default(), payload_type: payload_type__.unwrap_or_default(), memo: memo__.unwrap_or_default(), public_key: public_key__.unwrap_or_default(), signature: signature__.unwrap_or_default(), block_height: block_height__.unwrap_or_default(), confirmed: confirmed__.unwrap_or_default(), confirmations: confirmations__.unwrap_or_default(), payload: payload__, }) } } deserializer.deserialize_struct("pactus.TransactionInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for TransactionStatus { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Pending => "TRANSACTION_STATUS_PENDING", Self::Confirmed => "TRANSACTION_STATUS_CONFIRMED", Self::Failed => "TRANSACTION_STATUS_FAILED", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for TransactionStatus { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "TRANSACTION_STATUS_PENDING", "TRANSACTION_STATUS_CONFIRMED", "TRANSACTION_STATUS_FAILED", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = TransactionStatus; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "TRANSACTION_STATUS_PENDING" => Ok(TransactionStatus::Pending), "TRANSACTION_STATUS_CONFIRMED" => Ok(TransactionStatus::Confirmed), "TRANSACTION_STATUS_FAILED" => Ok(TransactionStatus::Failed), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for TransactionVerbosity { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Data => "TRANSACTION_VERBOSITY_DATA", Self::Info => "TRANSACTION_VERBOSITY_INFO", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for TransactionVerbosity { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "TRANSACTION_VERBOSITY_DATA", "TRANSACTION_VERBOSITY_INFO", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = TransactionVerbosity; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "TRANSACTION_VERBOSITY_DATA" => Ok(TransactionVerbosity::Data), "TRANSACTION_VERBOSITY_INFO" => Ok(TransactionVerbosity::Info), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for TxDirection { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Any => "TX_DIRECTION_ANY", Self::Incoming => "TX_DIRECTION_INCOMING", Self::Outgoing => "TX_DIRECTION_OUTGOING", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for TxDirection { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "TX_DIRECTION_ANY", "TX_DIRECTION_INCOMING", "TX_DIRECTION_OUTGOING", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = TxDirection; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "TX_DIRECTION_ANY" => Ok(TxDirection::Any), "TX_DIRECTION_INCOMING" => Ok(TxDirection::Incoming), "TX_DIRECTION_OUTGOING" => Ok(TxDirection::Outgoing), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for UnloadWalletRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.UnloadWalletRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for UnloadWalletRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = UnloadWalletRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.UnloadWalletRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(UnloadWalletRequest { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.UnloadWalletRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for UnloadWalletResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.UnloadWalletResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for UnloadWalletResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = UnloadWalletResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.UnloadWalletResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(UnloadWalletResponse { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.UnloadWalletResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for UpdatePasswordRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } if !self.old_password.is_empty() { len += 1; } if !self.new_password.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.UpdatePasswordRequest", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } if !self.old_password.is_empty() { struct_ser.serialize_field("oldPassword", &self.old_password)?; } if !self.new_password.is_empty() { struct_ser.serialize_field("newPassword", &self.new_password)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for UpdatePasswordRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", "old_password", "oldPassword", "new_password", "newPassword", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, OldPassword, NewPassword, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), "oldPassword" | "old_password" => Ok(GeneratedField::OldPassword), "newPassword" | "new_password" => Ok(GeneratedField::NewPassword), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = UpdatePasswordRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.UpdatePasswordRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; let mut old_password__ = None; let mut new_password__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } GeneratedField::OldPassword => { if old_password__.is_some() { return Err(serde::de::Error::duplicate_field("oldPassword")); } old_password__ = Some(map_.next_value()?); } GeneratedField::NewPassword => { if new_password__.is_some() { return Err(serde::de::Error::duplicate_field("newPassword")); } new_password__ = Some(map_.next_value()?); } } } Ok(UpdatePasswordRequest { wallet_name: wallet_name__.unwrap_or_default(), old_password: old_password__.unwrap_or_default(), new_password: new_password__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.UpdatePasswordRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for UpdatePasswordResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.wallet_name.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.UpdatePasswordResponse", len)?; if !self.wallet_name.is_empty() { struct_ser.serialize_field("walletName", &self.wallet_name)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for UpdatePasswordResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "wallet_name", "walletName", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { WalletName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "walletName" | "wallet_name" => Ok(GeneratedField::WalletName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = UpdatePasswordResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.UpdatePasswordResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut wallet_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::WalletName => { if wallet_name__.is_some() { return Err(serde::de::Error::duplicate_field("walletName")); } wallet_name__ = Some(map_.next_value()?); } } } Ok(UpdatePasswordResponse { wallet_name: wallet_name__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.UpdatePasswordResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ValidatorInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.hash.is_empty() { len += 1; } if !self.data.is_empty() { len += 1; } if !self.public_key.is_empty() { len += 1; } if self.number != 0 { len += 1; } if self.stake != 0 { len += 1; } if self.last_bonding_height != 0 { len += 1; } if self.last_sortition_height != 0 { len += 1; } if self.unbonding_height != 0 { len += 1; } if !self.address.is_empty() { len += 1; } if self.availability_score != 0. { len += 1; } if self.protocol_version != 0 { len += 1; } if self.is_delegated { len += 1; } if !self.delegate_owner.is_empty() { len += 1; } if self.delegate_share != 0 { len += 1; } if self.delegate_expiry != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ValidatorInfo", len)?; if !self.hash.is_empty() { struct_ser.serialize_field("hash", &self.hash)?; } if !self.data.is_empty() { struct_ser.serialize_field("data", &self.data)?; } if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } if self.number != 0 { struct_ser.serialize_field("number", &self.number)?; } if self.stake != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("stake", ToString::to_string(&self.stake).as_str())?; } if self.last_bonding_height != 0 { struct_ser.serialize_field("lastBondingHeight", &self.last_bonding_height)?; } if self.last_sortition_height != 0 { struct_ser.serialize_field("lastSortitionHeight", &self.last_sortition_height)?; } if self.unbonding_height != 0 { struct_ser.serialize_field("unbondingHeight", &self.unbonding_height)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if self.availability_score != 0. { struct_ser.serialize_field("availabilityScore", &self.availability_score)?; } if self.protocol_version != 0 { struct_ser.serialize_field("protocolVersion", &self.protocol_version)?; } if self.is_delegated { struct_ser.serialize_field("isDelegated", &self.is_delegated)?; } if !self.delegate_owner.is_empty() { struct_ser.serialize_field("delegateOwner", &self.delegate_owner)?; } if self.delegate_share != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("delegateShare", ToString::to_string(&self.delegate_share).as_str())?; } if self.delegate_expiry != 0 { struct_ser.serialize_field("delegateExpiry", &self.delegate_expiry)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ValidatorInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "hash", "data", "public_key", "publicKey", "number", "stake", "last_bonding_height", "lastBondingHeight", "last_sortition_height", "lastSortitionHeight", "unbonding_height", "unbondingHeight", "address", "availability_score", "availabilityScore", "protocol_version", "protocolVersion", "is_delegated", "isDelegated", "delegate_owner", "delegateOwner", "delegate_share", "delegateShare", "delegate_expiry", "delegateExpiry", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Hash, Data, PublicKey, Number, Stake, LastBondingHeight, LastSortitionHeight, UnbondingHeight, Address, AvailabilityScore, ProtocolVersion, IsDelegated, DelegateOwner, DelegateShare, DelegateExpiry, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "hash" => Ok(GeneratedField::Hash), "data" => Ok(GeneratedField::Data), "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), "number" => Ok(GeneratedField::Number), "stake" => Ok(GeneratedField::Stake), "lastBondingHeight" | "last_bonding_height" => Ok(GeneratedField::LastBondingHeight), "lastSortitionHeight" | "last_sortition_height" => Ok(GeneratedField::LastSortitionHeight), "unbondingHeight" | "unbonding_height" => Ok(GeneratedField::UnbondingHeight), "address" => Ok(GeneratedField::Address), "availabilityScore" | "availability_score" => Ok(GeneratedField::AvailabilityScore), "protocolVersion" | "protocol_version" => Ok(GeneratedField::ProtocolVersion), "isDelegated" | "is_delegated" => Ok(GeneratedField::IsDelegated), "delegateOwner" | "delegate_owner" => Ok(GeneratedField::DelegateOwner), "delegateShare" | "delegate_share" => Ok(GeneratedField::DelegateShare), "delegateExpiry" | "delegate_expiry" => Ok(GeneratedField::DelegateExpiry), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ValidatorInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ValidatorInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut hash__ = None; let mut data__ = None; let mut public_key__ = None; let mut number__ = None; let mut stake__ = None; let mut last_bonding_height__ = None; let mut last_sortition_height__ = None; let mut unbonding_height__ = None; let mut address__ = None; let mut availability_score__ = None; let mut protocol_version__ = None; let mut is_delegated__ = None; let mut delegate_owner__ = None; let mut delegate_share__ = None; let mut delegate_expiry__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Hash => { if hash__.is_some() { return Err(serde::de::Error::duplicate_field("hash")); } hash__ = Some(map_.next_value()?); } GeneratedField::Data => { if data__.is_some() { return Err(serde::de::Error::duplicate_field("data")); } data__ = Some(map_.next_value()?); } GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } GeneratedField::Number => { if number__.is_some() { return Err(serde::de::Error::duplicate_field("number")); } number__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Stake => { if stake__.is_some() { return Err(serde::de::Error::duplicate_field("stake")); } stake__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LastBondingHeight => { if last_bonding_height__.is_some() { return Err(serde::de::Error::duplicate_field("lastBondingHeight")); } last_bonding_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::LastSortitionHeight => { if last_sortition_height__.is_some() { return Err(serde::de::Error::duplicate_field("lastSortitionHeight")); } last_sortition_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::UnbondingHeight => { if unbonding_height__.is_some() { return Err(serde::de::Error::duplicate_field("unbondingHeight")); } unbonding_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::AvailabilityScore => { if availability_score__.is_some() { return Err(serde::de::Error::duplicate_field("availabilityScore")); } availability_score__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::ProtocolVersion => { if protocol_version__.is_some() { return Err(serde::de::Error::duplicate_field("protocolVersion")); } protocol_version__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::IsDelegated => { if is_delegated__.is_some() { return Err(serde::de::Error::duplicate_field("isDelegated")); } is_delegated__ = Some(map_.next_value()?); } GeneratedField::DelegateOwner => { if delegate_owner__.is_some() { return Err(serde::de::Error::duplicate_field("delegateOwner")); } delegate_owner__ = Some(map_.next_value()?); } GeneratedField::DelegateShare => { if delegate_share__.is_some() { return Err(serde::de::Error::duplicate_field("delegateShare")); } delegate_share__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::DelegateExpiry => { if delegate_expiry__.is_some() { return Err(serde::de::Error::duplicate_field("delegateExpiry")); } delegate_expiry__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(ValidatorInfo { hash: hash__.unwrap_or_default(), data: data__.unwrap_or_default(), public_key: public_key__.unwrap_or_default(), number: number__.unwrap_or_default(), stake: stake__.unwrap_or_default(), last_bonding_height: last_bonding_height__.unwrap_or_default(), last_sortition_height: last_sortition_height__.unwrap_or_default(), unbonding_height: unbonding_height__.unwrap_or_default(), address: address__.unwrap_or_default(), availability_score: availability_score__.unwrap_or_default(), protocol_version: protocol_version__.unwrap_or_default(), is_delegated: is_delegated__.unwrap_or_default(), delegate_owner: delegate_owner__.unwrap_or_default(), delegate_share: delegate_share__.unwrap_or_default(), delegate_expiry: delegate_expiry__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ValidatorInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for VerifyMessageRequest { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.message.is_empty() { len += 1; } if !self.signature.is_empty() { len += 1; } if !self.public_key.is_empty() { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.VerifyMessageRequest", len)?; if !self.message.is_empty() { struct_ser.serialize_field("message", &self.message)?; } if !self.signature.is_empty() { struct_ser.serialize_field("signature", &self.signature)?; } if !self.public_key.is_empty() { struct_ser.serialize_field("publicKey", &self.public_key)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for VerifyMessageRequest { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "message", "signature", "public_key", "publicKey", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Message, Signature, PublicKey, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "message" => Ok(GeneratedField::Message), "signature" => Ok(GeneratedField::Signature), "publicKey" | "public_key" => Ok(GeneratedField::PublicKey), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = VerifyMessageRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.VerifyMessageRequest") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut message__ = None; let mut signature__ = None; let mut public_key__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Message => { if message__.is_some() { return Err(serde::de::Error::duplicate_field("message")); } message__ = Some(map_.next_value()?); } GeneratedField::Signature => { if signature__.is_some() { return Err(serde::de::Error::duplicate_field("signature")); } signature__ = Some(map_.next_value()?); } GeneratedField::PublicKey => { if public_key__.is_some() { return Err(serde::de::Error::duplicate_field("publicKey")); } public_key__ = Some(map_.next_value()?); } } } Ok(VerifyMessageRequest { message: message__.unwrap_or_default(), signature: signature__.unwrap_or_default(), public_key: public_key__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.VerifyMessageRequest", FIELDS, GeneratedVisitor) } } impl serde::Serialize for VerifyMessageResponse { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.is_valid { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.VerifyMessageResponse", len)?; if self.is_valid { struct_ser.serialize_field("isValid", &self.is_valid)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for VerifyMessageResponse { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "is_valid", "isValid", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { IsValid, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "isValid" | "is_valid" => Ok(GeneratedField::IsValid), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = VerifyMessageResponse; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.VerifyMessageResponse") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut is_valid__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::IsValid => { if is_valid__.is_some() { return Err(serde::de::Error::duplicate_field("isValid")); } is_valid__ = Some(map_.next_value()?); } } } Ok(VerifyMessageResponse { is_valid: is_valid__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.VerifyMessageResponse", FIELDS, GeneratedVisitor) } } impl serde::Serialize for VoteInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.r#type != 0 { len += 1; } if !self.voter.is_empty() { len += 1; } if !self.block_hash.is_empty() { len += 1; } if self.round != 0 { len += 1; } if self.cp_round != 0 { len += 1; } if self.cp_value != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.VoteInfo", len)?; if self.r#type != 0 { let v = VoteType::try_from(self.r#type) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.r#type)))?; struct_ser.serialize_field("type", &v)?; } if !self.voter.is_empty() { struct_ser.serialize_field("voter", &self.voter)?; } if !self.block_hash.is_empty() { struct_ser.serialize_field("blockHash", &self.block_hash)?; } if self.round != 0 { struct_ser.serialize_field("round", &self.round)?; } if self.cp_round != 0 { struct_ser.serialize_field("cpRound", &self.cp_round)?; } if self.cp_value != 0 { struct_ser.serialize_field("cpValue", &self.cp_value)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for VoteInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "type", "voter", "block_hash", "blockHash", "round", "cp_round", "cpRound", "cp_value", "cpValue", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Type, Voter, BlockHash, Round, CpRound, CpValue, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "type" => Ok(GeneratedField::Type), "voter" => Ok(GeneratedField::Voter), "blockHash" | "block_hash" => Ok(GeneratedField::BlockHash), "round" => Ok(GeneratedField::Round), "cpRound" | "cp_round" => Ok(GeneratedField::CpRound), "cpValue" | "cp_value" => Ok(GeneratedField::CpValue), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = VoteInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.VoteInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut r#type__ = None; let mut voter__ = None; let mut block_hash__ = None; let mut round__ = None; let mut cp_round__ = None; let mut cp_value__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Type => { if r#type__.is_some() { return Err(serde::de::Error::duplicate_field("type")); } r#type__ = Some(map_.next_value::()? as i32); } GeneratedField::Voter => { if voter__.is_some() { return Err(serde::de::Error::duplicate_field("voter")); } voter__ = Some(map_.next_value()?); } GeneratedField::BlockHash => { if block_hash__.is_some() { return Err(serde::de::Error::duplicate_field("blockHash")); } block_hash__ = Some(map_.next_value()?); } GeneratedField::Round => { if round__.is_some() { return Err(serde::de::Error::duplicate_field("round")); } round__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::CpRound => { if cp_round__.is_some() { return Err(serde::de::Error::duplicate_field("cpRound")); } cp_round__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::CpValue => { if cp_value__.is_some() { return Err(serde::de::Error::duplicate_field("cpValue")); } cp_value__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(VoteInfo { r#type: r#type__.unwrap_or_default(), voter: voter__.unwrap_or_default(), block_hash: block_hash__.unwrap_or_default(), round: round__.unwrap_or_default(), cp_round: cp_round__.unwrap_or_default(), cp_value: cp_value__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.VoteInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for VoteType { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let variant = match self { Self::Unspecified => "VOTE_TYPE_UNSPECIFIED", Self::Prepare => "VOTE_TYPE_PREPARE", Self::Precommit => "VOTE_TYPE_PRECOMMIT", Self::CpPreVote => "VOTE_TYPE_CP_PRE_VOTE", Self::CpMainVote => "VOTE_TYPE_CP_MAIN_VOTE", Self::CpDecided => "VOTE_TYPE_CP_DECIDED", }; serializer.serialize_str(variant) } } impl<'de> serde::Deserialize<'de> for VoteType { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "VOTE_TYPE_UNSPECIFIED", "VOTE_TYPE_PREPARE", "VOTE_TYPE_PRECOMMIT", "VOTE_TYPE_CP_PRE_VOTE", "VOTE_TYPE_CP_MAIN_VOTE", "VOTE_TYPE_CP_DECIDED", ]; struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = VoteType; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } fn visit_i64(self, v: i64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) }) } fn visit_u64(self, v: u64) -> std::result::Result where E: serde::de::Error, { i32::try_from(v) .ok() .and_then(|x| x.try_into().ok()) .ok_or_else(|| { serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) }) } fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "VOTE_TYPE_UNSPECIFIED" => Ok(VoteType::Unspecified), "VOTE_TYPE_PREPARE" => Ok(VoteType::Prepare), "VOTE_TYPE_PRECOMMIT" => Ok(VoteType::Precommit), "VOTE_TYPE_CP_PRE_VOTE" => Ok(VoteType::CpPreVote), "VOTE_TYPE_CP_MAIN_VOTE" => Ok(VoteType::CpMainVote), "VOTE_TYPE_CP_DECIDED" => Ok(VoteType::CpDecided), _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), } } } deserializer.deserialize_any(GeneratedVisitor) } } impl serde::Serialize for WalletTransactionInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if self.no != 0 { len += 1; } if !self.tx_id.is_empty() { len += 1; } if !self.sender.is_empty() { len += 1; } if !self.receiver.is_empty() { len += 1; } if self.direction != 0 { len += 1; } if self.amount != 0 { len += 1; } if self.fee != 0 { len += 1; } if !self.memo.is_empty() { len += 1; } if self.status != 0 { len += 1; } if self.block_height != 0 { len += 1; } if self.payload_type != 0 { len += 1; } if !self.data.is_empty() { len += 1; } if !self.comment.is_empty() { len += 1; } if self.created_at != 0 { len += 1; } if self.updated_at != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.WalletTransactionInfo", len)?; if self.no != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("no", ToString::to_string(&self.no).as_str())?; } if !self.tx_id.is_empty() { struct_ser.serialize_field("txId", &self.tx_id)?; } if !self.sender.is_empty() { struct_ser.serialize_field("sender", &self.sender)?; } if !self.receiver.is_empty() { struct_ser.serialize_field("receiver", &self.receiver)?; } if self.direction != 0 { let v = TxDirection::try_from(self.direction) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.direction)))?; struct_ser.serialize_field("direction", &v)?; } if self.amount != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("amount", ToString::to_string(&self.amount).as_str())?; } if self.fee != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("fee", ToString::to_string(&self.fee).as_str())?; } if !self.memo.is_empty() { struct_ser.serialize_field("memo", &self.memo)?; } if self.status != 0 { let v = TransactionStatus::try_from(self.status) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.status)))?; struct_ser.serialize_field("status", &v)?; } if self.block_height != 0 { struct_ser.serialize_field("blockHeight", &self.block_height)?; } if self.payload_type != 0 { let v = PayloadType::try_from(self.payload_type) .map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.payload_type)))?; struct_ser.serialize_field("payloadType", &v)?; } if !self.data.is_empty() { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("data", pbjson::private::base64::encode(&self.data).as_str())?; } if !self.comment.is_empty() { struct_ser.serialize_field("comment", &self.comment)?; } if self.created_at != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("createdAt", ToString::to_string(&self.created_at).as_str())?; } if self.updated_at != 0 { #[allow(clippy::needless_borrow)] #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("updatedAt", ToString::to_string(&self.updated_at).as_str())?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for WalletTransactionInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "no", "tx_id", "txId", "sender", "receiver", "direction", "amount", "fee", "memo", "status", "block_height", "blockHeight", "payload_type", "payloadType", "data", "comment", "created_at", "createdAt", "updated_at", "updatedAt", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { No, TxId, Sender, Receiver, Direction, Amount, Fee, Memo, Status, BlockHeight, PayloadType, Data, Comment, CreatedAt, UpdatedAt, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "no" => Ok(GeneratedField::No), "txId" | "tx_id" => Ok(GeneratedField::TxId), "sender" => Ok(GeneratedField::Sender), "receiver" => Ok(GeneratedField::Receiver), "direction" => Ok(GeneratedField::Direction), "amount" => Ok(GeneratedField::Amount), "fee" => Ok(GeneratedField::Fee), "memo" => Ok(GeneratedField::Memo), "status" => Ok(GeneratedField::Status), "blockHeight" | "block_height" => Ok(GeneratedField::BlockHeight), "payloadType" | "payload_type" => Ok(GeneratedField::PayloadType), "data" => Ok(GeneratedField::Data), "comment" => Ok(GeneratedField::Comment), "createdAt" | "created_at" => Ok(GeneratedField::CreatedAt), "updatedAt" | "updated_at" => Ok(GeneratedField::UpdatedAt), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = WalletTransactionInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.WalletTransactionInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut no__ = None; let mut tx_id__ = None; let mut sender__ = None; let mut receiver__ = None; let mut direction__ = None; let mut amount__ = None; let mut fee__ = None; let mut memo__ = None; let mut status__ = None; let mut block_height__ = None; let mut payload_type__ = None; let mut data__ = None; let mut comment__ = None; let mut created_at__ = None; let mut updated_at__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::No => { if no__.is_some() { return Err(serde::de::Error::duplicate_field("no")); } no__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::TxId => { if tx_id__.is_some() { return Err(serde::de::Error::duplicate_field("txId")); } tx_id__ = Some(map_.next_value()?); } GeneratedField::Sender => { if sender__.is_some() { return Err(serde::de::Error::duplicate_field("sender")); } sender__ = Some(map_.next_value()?); } GeneratedField::Receiver => { if receiver__.is_some() { return Err(serde::de::Error::duplicate_field("receiver")); } receiver__ = Some(map_.next_value()?); } GeneratedField::Direction => { if direction__.is_some() { return Err(serde::de::Error::duplicate_field("direction")); } direction__ = Some(map_.next_value::()? as i32); } GeneratedField::Amount => { if amount__.is_some() { return Err(serde::de::Error::duplicate_field("amount")); } amount__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Fee => { if fee__.is_some() { return Err(serde::de::Error::duplicate_field("fee")); } fee__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::Memo => { if memo__.is_some() { return Err(serde::de::Error::duplicate_field("memo")); } memo__ = Some(map_.next_value()?); } GeneratedField::Status => { if status__.is_some() { return Err(serde::de::Error::duplicate_field("status")); } status__ = Some(map_.next_value::()? as i32); } GeneratedField::BlockHeight => { if block_height__.is_some() { return Err(serde::de::Error::duplicate_field("blockHeight")); } block_height__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::PayloadType => { if payload_type__.is_some() { return Err(serde::de::Error::duplicate_field("payloadType")); } payload_type__ = Some(map_.next_value::()? as i32); } GeneratedField::Data => { if data__.is_some() { return Err(serde::de::Error::duplicate_field("data")); } data__ = Some(map_.next_value::<::pbjson::private::BytesDeserialize<_>>()?.0) ; } GeneratedField::Comment => { if comment__.is_some() { return Err(serde::de::Error::duplicate_field("comment")); } comment__ = Some(map_.next_value()?); } GeneratedField::CreatedAt => { if created_at__.is_some() { return Err(serde::de::Error::duplicate_field("createdAt")); } created_at__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } GeneratedField::UpdatedAt => { if updated_at__.is_some() { return Err(serde::de::Error::duplicate_field("updatedAt")); } updated_at__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(WalletTransactionInfo { no: no__.unwrap_or_default(), tx_id: tx_id__.unwrap_or_default(), sender: sender__.unwrap_or_default(), receiver: receiver__.unwrap_or_default(), direction: direction__.unwrap_or_default(), amount: amount__.unwrap_or_default(), fee: fee__.unwrap_or_default(), memo: memo__.unwrap_or_default(), status: status__.unwrap_or_default(), block_height: block_height__.unwrap_or_default(), payload_type: payload_type__.unwrap_or_default(), data: data__.unwrap_or_default(), comment: comment__.unwrap_or_default(), created_at: created_at__.unwrap_or_default(), updated_at: updated_at__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.WalletTransactionInfo", FIELDS, GeneratedVisitor) } } impl serde::Serialize for ZmqPublisherInfo { #[allow(deprecated)] fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { use serde::ser::SerializeStruct; let mut len = 0; if !self.topic.is_empty() { len += 1; } if !self.address.is_empty() { len += 1; } if self.hwm != 0 { len += 1; } let mut struct_ser = serializer.serialize_struct("pactus.ZMQPublisherInfo", len)?; if !self.topic.is_empty() { struct_ser.serialize_field("topic", &self.topic)?; } if !self.address.is_empty() { struct_ser.serialize_field("address", &self.address)?; } if self.hwm != 0 { struct_ser.serialize_field("hwm", &self.hwm)?; } struct_ser.end() } } impl<'de> serde::Deserialize<'de> for ZmqPublisherInfo { #[allow(deprecated)] fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { const FIELDS: &[&str] = &[ "topic", "address", "hwm", ]; #[allow(clippy::enum_variant_names)] enum GeneratedField { Topic, Address, Hwm, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result where D: serde::Deserializer<'de>, { struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = GeneratedField; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "expected one of: {:?}", &FIELDS) } #[allow(unused_variables)] fn visit_str(self, value: &str) -> std::result::Result where E: serde::de::Error, { match value { "topic" => Ok(GeneratedField::Topic), "address" => Ok(GeneratedField::Address), "hwm" => Ok(GeneratedField::Hwm), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(GeneratedVisitor) } } struct GeneratedVisitor; impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { type Value = ZmqPublisherInfo; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("struct pactus.ZMQPublisherInfo") } fn visit_map(self, mut map_: V) -> std::result::Result where V: serde::de::MapAccess<'de>, { let mut topic__ = None; let mut address__ = None; let mut hwm__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Topic => { if topic__.is_some() { return Err(serde::de::Error::duplicate_field("topic")); } topic__ = Some(map_.next_value()?); } GeneratedField::Address => { if address__.is_some() { return Err(serde::de::Error::duplicate_field("address")); } address__ = Some(map_.next_value()?); } GeneratedField::Hwm => { if hwm__.is_some() { return Err(serde::de::Error::duplicate_field("hwm")); } hwm__ = Some(map_.next_value::<::pbjson::private::NumberDeserialize<_>>()?.0) ; } } } Ok(ZmqPublisherInfo { topic: topic__.unwrap_or_default(), address: address__.unwrap_or_default(), hwm: hwm__.unwrap_or_default(), }) } } deserializer.deserialize_struct("pactus.ZMQPublisherInfo", FIELDS, GeneratedVisitor) } } ================================================ FILE: www/grpc/gen/rust/pactus.tonic.rs ================================================ // @generated /// Generated client implementations. pub mod transaction_client { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; use tonic::codegen::http::Uri; #[derive(Debug, Clone)] pub struct TransactionClient { inner: tonic::client::Grpc, } impl TransactionClient { /// Attempt to create a new client by connecting to a given endpoint. pub async fn connect(dst: D) -> Result where D: TryInto, D::Error: Into, { let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; Ok(Self::new(conn)) } } impl TransactionClient where T: tonic::client::GrpcService, T::Error: Into, T::ResponseBody: Body + std::marker::Send + 'static, ::Error: Into + std::marker::Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_origin(inner: T, origin: Uri) -> Self { let inner = tonic::client::Grpc::with_origin(inner, origin); Self { inner } } pub fn with_interceptor( inner: T, interceptor: F, ) -> TransactionClient> where F: tonic::service::Interceptor, T::ResponseBody: Default, T: tonic::codegen::Service< http::Request, Response = http::Response< >::ResponseBody, >, >, , >>::Error: Into + std::marker::Send + std::marker::Sync, { TransactionClient::new(InterceptedService::new(inner, interceptor)) } /// Compress requests with the given encoding. /// /// This requires the server to support it otherwise it might respond with an /// error. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.send_compressed(encoding); self } /// Enable decompressing responses. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.accept_compressed(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_decoding_message_size(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_encoding_message_size(limit); self } pub async fn get_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/GetTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Transaction", "GetTransaction")); self.inner.unary(req, path, codec).await } pub async fn calculate_fee( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/CalculateFee", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Transaction", "CalculateFee")); self.inner.unary(req, path, codec).await } pub async fn broadcast_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/BroadcastTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Transaction", "BroadcastTransaction")); self.inner.unary(req, path, codec).await } pub async fn get_raw_transfer_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/GetRawTransferTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert( GrpcMethod::new("pactus.Transaction", "GetRawTransferTransaction"), ); self.inner.unary(req, path, codec).await } pub async fn get_raw_bond_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/GetRawBondTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Transaction", "GetRawBondTransaction")); self.inner.unary(req, path, codec).await } pub async fn get_raw_unbond_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/GetRawUnbondTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert( GrpcMethod::new("pactus.Transaction", "GetRawUnbondTransaction"), ); self.inner.unary(req, path, codec).await } pub async fn get_raw_withdraw_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/GetRawWithdrawTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert( GrpcMethod::new("pactus.Transaction", "GetRawWithdrawTransaction"), ); self.inner.unary(req, path, codec).await } pub async fn get_raw_batch_transfer_transaction( &mut self, request: impl tonic::IntoRequest< super::GetRawBatchTransferTransactionRequest, >, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/GetRawBatchTransferTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert( GrpcMethod::new( "pactus.Transaction", "GetRawBatchTransferTransaction", ), ); self.inner.unary(req, path, codec).await } pub async fn decode_raw_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/DecodeRawTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Transaction", "DecodeRawTransaction")); self.inner.unary(req, path, codec).await } pub async fn check_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Transaction/CheckTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Transaction", "CheckTransaction")); self.inner.unary(req, path, codec).await } } } /// Generated server implementations. pub mod transaction_server { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; /// Generated trait containing gRPC methods that should be implemented for use with TransactionServer. #[async_trait] pub trait Transaction: std::marker::Send + std::marker::Sync + 'static { async fn get_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn calculate_fee( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn broadcast_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_raw_transfer_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_raw_bond_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_raw_unbond_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_raw_withdraw_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_raw_batch_transfer_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn decode_raw_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn check_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; } #[derive(Debug)] pub struct TransactionServer { inner: Arc, accept_compression_encodings: EnabledCompressionEncodings, send_compression_encodings: EnabledCompressionEncodings, max_decoding_message_size: Option, max_encoding_message_size: Option, } impl TransactionServer { pub fn new(inner: T) -> Self { Self::from_arc(Arc::new(inner)) } pub fn from_arc(inner: Arc) -> Self { Self { inner, accept_compression_encodings: Default::default(), send_compression_encodings: Default::default(), max_decoding_message_size: None, max_encoding_message_size: None, } } pub fn with_interceptor( inner: T, interceptor: F, ) -> InterceptedService where F: tonic::service::Interceptor, { InterceptedService::new(Self::new(inner), interceptor) } /// Enable decompressing requests with the given encoding. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.accept_compression_encodings.enable(encoding); self } /// Compress responses with the given encoding, if the client supports it. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.send_compression_encodings.enable(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.max_decoding_message_size = Some(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.max_encoding_message_size = Some(limit); self } } impl tonic::codegen::Service> for TransactionServer where T: Transaction, B: Body + std::marker::Send + 'static, B::Error: Into + std::marker::Send + 'static, { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; fn poll_ready( &mut self, _cx: &mut Context<'_>, ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { match req.uri().path() { "/pactus.Transaction/GetTransaction" => { #[allow(non_camel_case_types)] struct GetTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for GetTransactionSvc { type Response = super::GetTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_transaction(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/CalculateFee" => { #[allow(non_camel_case_types)] struct CalculateFeeSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for CalculateFeeSvc { type Response = super::CalculateFeeResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::calculate_fee(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = CalculateFeeSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/BroadcastTransaction" => { #[allow(non_camel_case_types)] struct BroadcastTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for BroadcastTransactionSvc { type Response = super::BroadcastTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::broadcast_transaction(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = BroadcastTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/GetRawTransferTransaction" => { #[allow(non_camel_case_types)] struct GetRawTransferTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService< super::GetRawTransferTransactionRequest, > for GetRawTransferTransactionSvc { type Response = super::GetRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request< super::GetRawTransferTransactionRequest, >, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_raw_transfer_transaction( &inner, request, ) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetRawTransferTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/GetRawBondTransaction" => { #[allow(non_camel_case_types)] struct GetRawBondTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for GetRawBondTransactionSvc { type Response = super::GetRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_raw_bond_transaction( &inner, request, ) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetRawBondTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/GetRawUnbondTransaction" => { #[allow(non_camel_case_types)] struct GetRawUnbondTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for GetRawUnbondTransactionSvc { type Response = super::GetRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request< super::GetRawUnbondTransactionRequest, >, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_raw_unbond_transaction( &inner, request, ) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetRawUnbondTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/GetRawWithdrawTransaction" => { #[allow(non_camel_case_types)] struct GetRawWithdrawTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService< super::GetRawWithdrawTransactionRequest, > for GetRawWithdrawTransactionSvc { type Response = super::GetRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request< super::GetRawWithdrawTransactionRequest, >, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_raw_withdraw_transaction( &inner, request, ) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetRawWithdrawTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/GetRawBatchTransferTransaction" => { #[allow(non_camel_case_types)] struct GetRawBatchTransferTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService< super::GetRawBatchTransferTransactionRequest, > for GetRawBatchTransferTransactionSvc { type Response = super::GetRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request< super::GetRawBatchTransferTransactionRequest, >, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_raw_batch_transfer_transaction( &inner, request, ) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetRawBatchTransferTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/DecodeRawTransaction" => { #[allow(non_camel_case_types)] struct DecodeRawTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for DecodeRawTransactionSvc { type Response = super::DecodeRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::decode_raw_transaction(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = DecodeRawTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Transaction/CheckTransaction" => { #[allow(non_camel_case_types)] struct CheckTransactionSvc(pub Arc); impl< T: Transaction, > tonic::server::UnaryService for CheckTransactionSvc { type Response = super::CheckTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::check_transaction(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = CheckTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } _ => { Box::pin(async move { let mut response = http::Response::new( tonic::body::Body::default(), ); let headers = response.headers_mut(); headers .insert( tonic::Status::GRPC_STATUS, (tonic::Code::Unimplemented as i32).into(), ); headers .insert( http::header::CONTENT_TYPE, tonic::metadata::GRPC_CONTENT_TYPE, ); Ok(response) }) } } } } impl Clone for TransactionServer { fn clone(&self) -> Self { let inner = self.inner.clone(); Self { inner, accept_compression_encodings: self.accept_compression_encodings, send_compression_encodings: self.send_compression_encodings, max_decoding_message_size: self.max_decoding_message_size, max_encoding_message_size: self.max_encoding_message_size, } } } /// Generated gRPC service name pub const SERVICE_NAME: &str = "pactus.Transaction"; impl tonic::server::NamedService for TransactionServer { const NAME: &'static str = SERVICE_NAME; } } /// Generated client implementations. pub mod blockchain_client { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; use tonic::codegen::http::Uri; #[derive(Debug, Clone)] pub struct BlockchainClient { inner: tonic::client::Grpc, } impl BlockchainClient { /// Attempt to create a new client by connecting to a given endpoint. pub async fn connect(dst: D) -> Result where D: TryInto, D::Error: Into, { let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; Ok(Self::new(conn)) } } impl BlockchainClient where T: tonic::client::GrpcService, T::Error: Into, T::ResponseBody: Body + std::marker::Send + 'static, ::Error: Into + std::marker::Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_origin(inner: T, origin: Uri) -> Self { let inner = tonic::client::Grpc::with_origin(inner, origin); Self { inner } } pub fn with_interceptor( inner: T, interceptor: F, ) -> BlockchainClient> where F: tonic::service::Interceptor, T::ResponseBody: Default, T: tonic::codegen::Service< http::Request, Response = http::Response< >::ResponseBody, >, >, , >>::Error: Into + std::marker::Send + std::marker::Sync, { BlockchainClient::new(InterceptedService::new(inner, interceptor)) } /// Compress requests with the given encoding. /// /// This requires the server to support it otherwise it might respond with an /// error. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.send_compressed(encoding); self } /// Enable decompressing responses. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.accept_compressed(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_decoding_message_size(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_encoding_message_size(limit); self } pub async fn get_block( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetBlock", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetBlock")); self.inner.unary(req, path, codec).await } pub async fn get_block_hash( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetBlockHash", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetBlockHash")); self.inner.unary(req, path, codec).await } pub async fn get_block_height( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetBlockHeight", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetBlockHeight")); self.inner.unary(req, path, codec).await } pub async fn get_blockchain_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetBlockchainInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetBlockchainInfo")); self.inner.unary(req, path, codec).await } pub async fn get_committee_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetCommitteeInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetCommitteeInfo")); self.inner.unary(req, path, codec).await } pub async fn get_consensus_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetConsensusInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetConsensusInfo")); self.inner.unary(req, path, codec).await } pub async fn get_account( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetAccount", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetAccount")); self.inner.unary(req, path, codec).await } pub async fn get_validator( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetValidator", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetValidator")); self.inner.unary(req, path, codec).await } pub async fn get_validator_by_number( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetValidatorByNumber", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetValidatorByNumber")); self.inner.unary(req, path, codec).await } pub async fn get_validator_addresses( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetValidatorAddresses", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetValidatorAddresses")); self.inner.unary(req, path, codec).await } pub async fn get_public_key( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetPublicKey", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetPublicKey")); self.inner.unary(req, path, codec).await } pub async fn get_tx_pool_content( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Blockchain/GetTxPoolContent", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Blockchain", "GetTxPoolContent")); self.inner.unary(req, path, codec).await } } } /// Generated server implementations. pub mod blockchain_server { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; /// Generated trait containing gRPC methods that should be implemented for use with BlockchainServer. #[async_trait] pub trait Blockchain: std::marker::Send + std::marker::Sync + 'static { async fn get_block( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_block_hash( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_block_height( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_blockchain_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_committee_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_consensus_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_account( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_validator( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_validator_by_number( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_validator_addresses( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_public_key( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_tx_pool_content( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; } #[derive(Debug)] pub struct BlockchainServer { inner: Arc, accept_compression_encodings: EnabledCompressionEncodings, send_compression_encodings: EnabledCompressionEncodings, max_decoding_message_size: Option, max_encoding_message_size: Option, } impl BlockchainServer { pub fn new(inner: T) -> Self { Self::from_arc(Arc::new(inner)) } pub fn from_arc(inner: Arc) -> Self { Self { inner, accept_compression_encodings: Default::default(), send_compression_encodings: Default::default(), max_decoding_message_size: None, max_encoding_message_size: None, } } pub fn with_interceptor( inner: T, interceptor: F, ) -> InterceptedService where F: tonic::service::Interceptor, { InterceptedService::new(Self::new(inner), interceptor) } /// Enable decompressing requests with the given encoding. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.accept_compression_encodings.enable(encoding); self } /// Compress responses with the given encoding, if the client supports it. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.send_compression_encodings.enable(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.max_decoding_message_size = Some(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.max_encoding_message_size = Some(limit); self } } impl tonic::codegen::Service> for BlockchainServer where T: Blockchain, B: Body + std::marker::Send + 'static, B::Error: Into + std::marker::Send + 'static, { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; fn poll_ready( &mut self, _cx: &mut Context<'_>, ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { match req.uri().path() { "/pactus.Blockchain/GetBlock" => { #[allow(non_camel_case_types)] struct GetBlockSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetBlockSvc { type Response = super::GetBlockResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_block(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetBlockSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetBlockHash" => { #[allow(non_camel_case_types)] struct GetBlockHashSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetBlockHashSvc { type Response = super::GetBlockHashResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_block_hash(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetBlockHashSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetBlockHeight" => { #[allow(non_camel_case_types)] struct GetBlockHeightSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetBlockHeightSvc { type Response = super::GetBlockHeightResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_block_height(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetBlockHeightSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetBlockchainInfo" => { #[allow(non_camel_case_types)] struct GetBlockchainInfoSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetBlockchainInfoSvc { type Response = super::GetBlockchainInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_blockchain_info(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetBlockchainInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetCommitteeInfo" => { #[allow(non_camel_case_types)] struct GetCommitteeInfoSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetCommitteeInfoSvc { type Response = super::GetCommitteeInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_committee_info(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetCommitteeInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetConsensusInfo" => { #[allow(non_camel_case_types)] struct GetConsensusInfoSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetConsensusInfoSvc { type Response = super::GetConsensusInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_consensus_info(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetConsensusInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetAccount" => { #[allow(non_camel_case_types)] struct GetAccountSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetAccountSvc { type Response = super::GetAccountResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_account(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetAccountSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetValidator" => { #[allow(non_camel_case_types)] struct GetValidatorSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetValidatorSvc { type Response = super::GetValidatorResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_validator(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetValidatorSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetValidatorByNumber" => { #[allow(non_camel_case_types)] struct GetValidatorByNumberSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetValidatorByNumberSvc { type Response = super::GetValidatorResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_validator_by_number(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetValidatorByNumberSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetValidatorAddresses" => { #[allow(non_camel_case_types)] struct GetValidatorAddressesSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetValidatorAddressesSvc { type Response = super::GetValidatorAddressesResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_validator_addresses(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetValidatorAddressesSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetPublicKey" => { #[allow(non_camel_case_types)] struct GetPublicKeySvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetPublicKeySvc { type Response = super::GetPublicKeyResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_public_key(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetPublicKeySvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Blockchain/GetTxPoolContent" => { #[allow(non_camel_case_types)] struct GetTxPoolContentSvc(pub Arc); impl< T: Blockchain, > tonic::server::UnaryService for GetTxPoolContentSvc { type Response = super::GetTxPoolContentResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_tx_pool_content(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetTxPoolContentSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } _ => { Box::pin(async move { let mut response = http::Response::new( tonic::body::Body::default(), ); let headers = response.headers_mut(); headers .insert( tonic::Status::GRPC_STATUS, (tonic::Code::Unimplemented as i32).into(), ); headers .insert( http::header::CONTENT_TYPE, tonic::metadata::GRPC_CONTENT_TYPE, ); Ok(response) }) } } } } impl Clone for BlockchainServer { fn clone(&self) -> Self { let inner = self.inner.clone(); Self { inner, accept_compression_encodings: self.accept_compression_encodings, send_compression_encodings: self.send_compression_encodings, max_decoding_message_size: self.max_decoding_message_size, max_encoding_message_size: self.max_encoding_message_size, } } } /// Generated gRPC service name pub const SERVICE_NAME: &str = "pactus.Blockchain"; impl tonic::server::NamedService for BlockchainServer { const NAME: &'static str = SERVICE_NAME; } } /// Generated client implementations. pub mod network_client { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; use tonic::codegen::http::Uri; #[derive(Debug, Clone)] pub struct NetworkClient { inner: tonic::client::Grpc, } impl NetworkClient { /// Attempt to create a new client by connecting to a given endpoint. pub async fn connect(dst: D) -> Result where D: TryInto, D::Error: Into, { let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; Ok(Self::new(conn)) } } impl NetworkClient where T: tonic::client::GrpcService, T::Error: Into, T::ResponseBody: Body + std::marker::Send + 'static, ::Error: Into + std::marker::Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_origin(inner: T, origin: Uri) -> Self { let inner = tonic::client::Grpc::with_origin(inner, origin); Self { inner } } pub fn with_interceptor( inner: T, interceptor: F, ) -> NetworkClient> where F: tonic::service::Interceptor, T::ResponseBody: Default, T: tonic::codegen::Service< http::Request, Response = http::Response< >::ResponseBody, >, >, , >>::Error: Into + std::marker::Send + std::marker::Sync, { NetworkClient::new(InterceptedService::new(inner, interceptor)) } /// Compress requests with the given encoding. /// /// This requires the server to support it otherwise it might respond with an /// error. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.send_compressed(encoding); self } /// Enable decompressing responses. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.accept_compressed(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_decoding_message_size(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_encoding_message_size(limit); self } pub async fn get_network_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Network/GetNetworkInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Network", "GetNetworkInfo")); self.inner.unary(req, path, codec).await } pub async fn list_peers( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static("/pactus.Network/ListPeers"); let mut req = request.into_request(); req.extensions_mut().insert(GrpcMethod::new("pactus.Network", "ListPeers")); self.inner.unary(req, path, codec).await } pub async fn get_node_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Network/GetNodeInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Network", "GetNodeInfo")); self.inner.unary(req, path, codec).await } pub async fn ping( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result, tonic::Status> { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static("/pactus.Network/Ping"); let mut req = request.into_request(); req.extensions_mut().insert(GrpcMethod::new("pactus.Network", "Ping")); self.inner.unary(req, path, codec).await } } } /// Generated server implementations. pub mod network_server { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; /// Generated trait containing gRPC methods that should be implemented for use with NetworkServer. #[async_trait] pub trait Network: std::marker::Send + std::marker::Sync + 'static { async fn get_network_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn list_peers( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_node_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn ping( &self, request: tonic::Request, ) -> std::result::Result, tonic::Status>; } #[derive(Debug)] pub struct NetworkServer { inner: Arc, accept_compression_encodings: EnabledCompressionEncodings, send_compression_encodings: EnabledCompressionEncodings, max_decoding_message_size: Option, max_encoding_message_size: Option, } impl NetworkServer { pub fn new(inner: T) -> Self { Self::from_arc(Arc::new(inner)) } pub fn from_arc(inner: Arc) -> Self { Self { inner, accept_compression_encodings: Default::default(), send_compression_encodings: Default::default(), max_decoding_message_size: None, max_encoding_message_size: None, } } pub fn with_interceptor( inner: T, interceptor: F, ) -> InterceptedService where F: tonic::service::Interceptor, { InterceptedService::new(Self::new(inner), interceptor) } /// Enable decompressing requests with the given encoding. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.accept_compression_encodings.enable(encoding); self } /// Compress responses with the given encoding, if the client supports it. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.send_compression_encodings.enable(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.max_decoding_message_size = Some(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.max_encoding_message_size = Some(limit); self } } impl tonic::codegen::Service> for NetworkServer where T: Network, B: Body + std::marker::Send + 'static, B::Error: Into + std::marker::Send + 'static, { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; fn poll_ready( &mut self, _cx: &mut Context<'_>, ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { match req.uri().path() { "/pactus.Network/GetNetworkInfo" => { #[allow(non_camel_case_types)] struct GetNetworkInfoSvc(pub Arc); impl< T: Network, > tonic::server::UnaryService for GetNetworkInfoSvc { type Response = super::GetNetworkInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_network_info(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetNetworkInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Network/ListPeers" => { #[allow(non_camel_case_types)] struct ListPeersSvc(pub Arc); impl tonic::server::UnaryService for ListPeersSvc { type Response = super::ListPeersResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::list_peers(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = ListPeersSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Network/GetNodeInfo" => { #[allow(non_camel_case_types)] struct GetNodeInfoSvc(pub Arc); impl< T: Network, > tonic::server::UnaryService for GetNodeInfoSvc { type Response = super::GetNodeInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_node_info(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetNodeInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Network/Ping" => { #[allow(non_camel_case_types)] struct PingSvc(pub Arc); impl tonic::server::UnaryService for PingSvc { type Response = super::PingResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::ping(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = PingSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } _ => { Box::pin(async move { let mut response = http::Response::new( tonic::body::Body::default(), ); let headers = response.headers_mut(); headers .insert( tonic::Status::GRPC_STATUS, (tonic::Code::Unimplemented as i32).into(), ); headers .insert( http::header::CONTENT_TYPE, tonic::metadata::GRPC_CONTENT_TYPE, ); Ok(response) }) } } } } impl Clone for NetworkServer { fn clone(&self) -> Self { let inner = self.inner.clone(); Self { inner, accept_compression_encodings: self.accept_compression_encodings, send_compression_encodings: self.send_compression_encodings, max_decoding_message_size: self.max_decoding_message_size, max_encoding_message_size: self.max_encoding_message_size, } } } /// Generated gRPC service name pub const SERVICE_NAME: &str = "pactus.Network"; impl tonic::server::NamedService for NetworkServer { const NAME: &'static str = SERVICE_NAME; } } /// Generated client implementations. pub mod utils_client { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; use tonic::codegen::http::Uri; #[derive(Debug, Clone)] pub struct UtilsClient { inner: tonic::client::Grpc, } impl UtilsClient { /// Attempt to create a new client by connecting to a given endpoint. pub async fn connect(dst: D) -> Result where D: TryInto, D::Error: Into, { let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; Ok(Self::new(conn)) } } impl UtilsClient where T: tonic::client::GrpcService, T::Error: Into, T::ResponseBody: Body + std::marker::Send + 'static, ::Error: Into + std::marker::Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_origin(inner: T, origin: Uri) -> Self { let inner = tonic::client::Grpc::with_origin(inner, origin); Self { inner } } pub fn with_interceptor( inner: T, interceptor: F, ) -> UtilsClient> where F: tonic::service::Interceptor, T::ResponseBody: Default, T: tonic::codegen::Service< http::Request, Response = http::Response< >::ResponseBody, >, >, , >>::Error: Into + std::marker::Send + std::marker::Sync, { UtilsClient::new(InterceptedService::new(inner, interceptor)) } /// Compress requests with the given encoding. /// /// This requires the server to support it otherwise it might respond with an /// error. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.send_compressed(encoding); self } /// Enable decompressing responses. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.accept_compressed(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_decoding_message_size(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_encoding_message_size(limit); self } pub async fn sign_message_with_private_key( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Utils/SignMessageWithPrivateKey", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Utils", "SignMessageWithPrivateKey")); self.inner.unary(req, path, codec).await } pub async fn verify_message( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Utils/VerifyMessage", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Utils", "VerifyMessage")); self.inner.unary(req, path, codec).await } pub async fn public_key_aggregation( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Utils/PublicKeyAggregation", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Utils", "PublicKeyAggregation")); self.inner.unary(req, path, codec).await } pub async fn signature_aggregation( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Utils/SignatureAggregation", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Utils", "SignatureAggregation")); self.inner.unary(req, path, codec).await } } } /// Generated server implementations. pub mod utils_server { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; /// Generated trait containing gRPC methods that should be implemented for use with UtilsServer. #[async_trait] pub trait Utils: std::marker::Send + std::marker::Sync + 'static { async fn sign_message_with_private_key( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn verify_message( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn public_key_aggregation( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn signature_aggregation( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; } #[derive(Debug)] pub struct UtilsServer { inner: Arc, accept_compression_encodings: EnabledCompressionEncodings, send_compression_encodings: EnabledCompressionEncodings, max_decoding_message_size: Option, max_encoding_message_size: Option, } impl UtilsServer { pub fn new(inner: T) -> Self { Self::from_arc(Arc::new(inner)) } pub fn from_arc(inner: Arc) -> Self { Self { inner, accept_compression_encodings: Default::default(), send_compression_encodings: Default::default(), max_decoding_message_size: None, max_encoding_message_size: None, } } pub fn with_interceptor( inner: T, interceptor: F, ) -> InterceptedService where F: tonic::service::Interceptor, { InterceptedService::new(Self::new(inner), interceptor) } /// Enable decompressing requests with the given encoding. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.accept_compression_encodings.enable(encoding); self } /// Compress responses with the given encoding, if the client supports it. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.send_compression_encodings.enable(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.max_decoding_message_size = Some(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.max_encoding_message_size = Some(limit); self } } impl tonic::codegen::Service> for UtilsServer where T: Utils, B: Body + std::marker::Send + 'static, B::Error: Into + std::marker::Send + 'static, { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; fn poll_ready( &mut self, _cx: &mut Context<'_>, ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { match req.uri().path() { "/pactus.Utils/SignMessageWithPrivateKey" => { #[allow(non_camel_case_types)] struct SignMessageWithPrivateKeySvc(pub Arc); impl< T: Utils, > tonic::server::UnaryService< super::SignMessageWithPrivateKeyRequest, > for SignMessageWithPrivateKeySvc { type Response = super::SignMessageWithPrivateKeyResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request< super::SignMessageWithPrivateKeyRequest, >, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::sign_message_with_private_key(&inner, request) .await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = SignMessageWithPrivateKeySvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Utils/VerifyMessage" => { #[allow(non_camel_case_types)] struct VerifyMessageSvc(pub Arc); impl< T: Utils, > tonic::server::UnaryService for VerifyMessageSvc { type Response = super::VerifyMessageResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::verify_message(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = VerifyMessageSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Utils/PublicKeyAggregation" => { #[allow(non_camel_case_types)] struct PublicKeyAggregationSvc(pub Arc); impl< T: Utils, > tonic::server::UnaryService for PublicKeyAggregationSvc { type Response = super::PublicKeyAggregationResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::public_key_aggregation(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = PublicKeyAggregationSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Utils/SignatureAggregation" => { #[allow(non_camel_case_types)] struct SignatureAggregationSvc(pub Arc); impl< T: Utils, > tonic::server::UnaryService for SignatureAggregationSvc { type Response = super::SignatureAggregationResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::signature_aggregation(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = SignatureAggregationSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } _ => { Box::pin(async move { let mut response = http::Response::new( tonic::body::Body::default(), ); let headers = response.headers_mut(); headers .insert( tonic::Status::GRPC_STATUS, (tonic::Code::Unimplemented as i32).into(), ); headers .insert( http::header::CONTENT_TYPE, tonic::metadata::GRPC_CONTENT_TYPE, ); Ok(response) }) } } } } impl Clone for UtilsServer { fn clone(&self) -> Self { let inner = self.inner.clone(); Self { inner, accept_compression_encodings: self.accept_compression_encodings, send_compression_encodings: self.send_compression_encodings, max_decoding_message_size: self.max_decoding_message_size, max_encoding_message_size: self.max_encoding_message_size, } } } /// Generated gRPC service name pub const SERVICE_NAME: &str = "pactus.Utils"; impl tonic::server::NamedService for UtilsServer { const NAME: &'static str = SERVICE_NAME; } } /// Generated client implementations. pub mod wallet_client { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; use tonic::codegen::http::Uri; #[derive(Debug, Clone)] pub struct WalletClient { inner: tonic::client::Grpc, } impl WalletClient { /// Attempt to create a new client by connecting to a given endpoint. pub async fn connect(dst: D) -> Result where D: TryInto, D::Error: Into, { let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; Ok(Self::new(conn)) } } impl WalletClient where T: tonic::client::GrpcService, T::Error: Into, T::ResponseBody: Body + std::marker::Send + 'static, ::Error: Into + std::marker::Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_origin(inner: T, origin: Uri) -> Self { let inner = tonic::client::Grpc::with_origin(inner, origin); Self { inner } } pub fn with_interceptor( inner: T, interceptor: F, ) -> WalletClient> where F: tonic::service::Interceptor, T::ResponseBody: Default, T: tonic::codegen::Service< http::Request, Response = http::Response< >::ResponseBody, >, >, , >>::Error: Into + std::marker::Send + std::marker::Sync, { WalletClient::new(InterceptedService::new(inner, interceptor)) } /// Compress requests with the given encoding. /// /// This requires the server to support it otherwise it might respond with an /// error. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.send_compressed(encoding); self } /// Enable decompressing responses. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.inner = self.inner.accept_compressed(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_decoding_message_size(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.inner = self.inner.max_encoding_message_size(limit); self } pub async fn create_wallet( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/CreateWallet", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "CreateWallet")); self.inner.unary(req, path, codec).await } pub async fn restore_wallet( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/RestoreWallet", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "RestoreWallet")); self.inner.unary(req, path, codec).await } pub async fn load_wallet( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static("/pactus.Wallet/LoadWallet"); let mut req = request.into_request(); req.extensions_mut().insert(GrpcMethod::new("pactus.Wallet", "LoadWallet")); self.inner.unary(req, path, codec).await } pub async fn unload_wallet( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/UnloadWallet", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "UnloadWallet")); self.inner.unary(req, path, codec).await } pub async fn list_wallets( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/ListWallets", ); let mut req = request.into_request(); req.extensions_mut().insert(GrpcMethod::new("pactus.Wallet", "ListWallets")); self.inner.unary(req, path, codec).await } pub async fn get_wallet_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetWalletInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetWalletInfo")); self.inner.unary(req, path, codec).await } pub async fn update_password( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/UpdatePassword", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "UpdatePassword")); self.inner.unary(req, path, codec).await } pub async fn get_total_balance( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetTotalBalance", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetTotalBalance")); self.inner.unary(req, path, codec).await } pub async fn get_total_stake( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetTotalStake", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetTotalStake")); self.inner.unary(req, path, codec).await } pub async fn get_validator_address( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetValidatorAddress", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetValidatorAddress")); self.inner.unary(req, path, codec).await } pub async fn get_address_info( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetAddressInfo", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetAddressInfo")); self.inner.unary(req, path, codec).await } pub async fn set_address_label( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/SetAddressLabel", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "SetAddressLabel")); self.inner.unary(req, path, codec).await } pub async fn get_new_address( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetNewAddress", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetNewAddress")); self.inner.unary(req, path, codec).await } pub async fn list_addresses( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/ListAddresses", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "ListAddresses")); self.inner.unary(req, path, codec).await } pub async fn sign_message( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/SignMessage", ); let mut req = request.into_request(); req.extensions_mut().insert(GrpcMethod::new("pactus.Wallet", "SignMessage")); self.inner.unary(req, path, codec).await } pub async fn sign_raw_transaction( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/SignRawTransaction", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "SignRawTransaction")); self.inner.unary(req, path, codec).await } pub async fn list_transactions( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/ListTransactions", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "ListTransactions")); self.inner.unary(req, path, codec).await } pub async fn set_default_fee( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/SetDefaultFee", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "SetDefaultFee")); self.inner.unary(req, path, codec).await } pub async fn get_mnemonic( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetMnemonic", ); let mut req = request.into_request(); req.extensions_mut().insert(GrpcMethod::new("pactus.Wallet", "GetMnemonic")); self.inner.unary(req, path, codec).await } pub async fn get_private_key( &mut self, request: impl tonic::IntoRequest, ) -> std::result::Result< tonic::Response, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::unknown( format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic_prost::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/pactus.Wallet/GetPrivateKey", ); let mut req = request.into_request(); req.extensions_mut() .insert(GrpcMethod::new("pactus.Wallet", "GetPrivateKey")); self.inner.unary(req, path, codec).await } } } /// Generated server implementations. pub mod wallet_server { #![allow( unused_variables, dead_code, missing_docs, clippy::wildcard_imports, clippy::let_unit_value, )] use tonic::codegen::*; /// Generated trait containing gRPC methods that should be implemented for use with WalletServer. #[async_trait] pub trait Wallet: std::marker::Send + std::marker::Sync + 'static { async fn create_wallet( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn restore_wallet( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn load_wallet( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn unload_wallet( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn list_wallets( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_wallet_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn update_password( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_total_balance( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_total_stake( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_validator_address( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_address_info( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn set_address_label( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_new_address( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn list_addresses( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn sign_message( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn sign_raw_transaction( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn list_transactions( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn set_default_fee( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_mnemonic( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; async fn get_private_key( &self, request: tonic::Request, ) -> std::result::Result< tonic::Response, tonic::Status, >; } #[derive(Debug)] pub struct WalletServer { inner: Arc, accept_compression_encodings: EnabledCompressionEncodings, send_compression_encodings: EnabledCompressionEncodings, max_decoding_message_size: Option, max_encoding_message_size: Option, } impl WalletServer { pub fn new(inner: T) -> Self { Self::from_arc(Arc::new(inner)) } pub fn from_arc(inner: Arc) -> Self { Self { inner, accept_compression_encodings: Default::default(), send_compression_encodings: Default::default(), max_decoding_message_size: None, max_encoding_message_size: None, } } pub fn with_interceptor( inner: T, interceptor: F, ) -> InterceptedService where F: tonic::service::Interceptor, { InterceptedService::new(Self::new(inner), interceptor) } /// Enable decompressing requests with the given encoding. #[must_use] pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { self.accept_compression_encodings.enable(encoding); self } /// Compress responses with the given encoding, if the client supports it. #[must_use] pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { self.send_compression_encodings.enable(encoding); self } /// Limits the maximum size of a decoded message. /// /// Default: `4MB` #[must_use] pub fn max_decoding_message_size(mut self, limit: usize) -> Self { self.max_decoding_message_size = Some(limit); self } /// Limits the maximum size of an encoded message. /// /// Default: `usize::MAX` #[must_use] pub fn max_encoding_message_size(mut self, limit: usize) -> Self { self.max_encoding_message_size = Some(limit); self } } impl tonic::codegen::Service> for WalletServer where T: Wallet, B: Body + std::marker::Send + 'static, B::Error: Into + std::marker::Send + 'static, { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; fn poll_ready( &mut self, _cx: &mut Context<'_>, ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { match req.uri().path() { "/pactus.Wallet/CreateWallet" => { #[allow(non_camel_case_types)] struct CreateWalletSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for CreateWalletSvc { type Response = super::CreateWalletResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::create_wallet(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = CreateWalletSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/RestoreWallet" => { #[allow(non_camel_case_types)] struct RestoreWalletSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for RestoreWalletSvc { type Response = super::RestoreWalletResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::restore_wallet(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = RestoreWalletSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/LoadWallet" => { #[allow(non_camel_case_types)] struct LoadWalletSvc(pub Arc); impl tonic::server::UnaryService for LoadWalletSvc { type Response = super::LoadWalletResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::load_wallet(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = LoadWalletSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/UnloadWallet" => { #[allow(non_camel_case_types)] struct UnloadWalletSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for UnloadWalletSvc { type Response = super::UnloadWalletResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::unload_wallet(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = UnloadWalletSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/ListWallets" => { #[allow(non_camel_case_types)] struct ListWalletsSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for ListWalletsSvc { type Response = super::ListWalletsResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::list_wallets(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = ListWalletsSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetWalletInfo" => { #[allow(non_camel_case_types)] struct GetWalletInfoSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetWalletInfoSvc { type Response = super::GetWalletInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_wallet_info(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetWalletInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/UpdatePassword" => { #[allow(non_camel_case_types)] struct UpdatePasswordSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for UpdatePasswordSvc { type Response = super::UpdatePasswordResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::update_password(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = UpdatePasswordSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetTotalBalance" => { #[allow(non_camel_case_types)] struct GetTotalBalanceSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetTotalBalanceSvc { type Response = super::GetTotalBalanceResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_total_balance(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetTotalBalanceSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetTotalStake" => { #[allow(non_camel_case_types)] struct GetTotalStakeSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetTotalStakeSvc { type Response = super::GetTotalStakeResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_total_stake(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetTotalStakeSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetValidatorAddress" => { #[allow(non_camel_case_types)] struct GetValidatorAddressSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetValidatorAddressSvc { type Response = super::GetValidatorAddressResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_validator_address(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetValidatorAddressSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetAddressInfo" => { #[allow(non_camel_case_types)] struct GetAddressInfoSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetAddressInfoSvc { type Response = super::GetAddressInfoResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_address_info(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetAddressInfoSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/SetAddressLabel" => { #[allow(non_camel_case_types)] struct SetAddressLabelSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for SetAddressLabelSvc { type Response = super::SetAddressLabelResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::set_address_label(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = SetAddressLabelSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetNewAddress" => { #[allow(non_camel_case_types)] struct GetNewAddressSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetNewAddressSvc { type Response = super::GetNewAddressResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_new_address(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetNewAddressSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/ListAddresses" => { #[allow(non_camel_case_types)] struct ListAddressesSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for ListAddressesSvc { type Response = super::ListAddressesResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::list_addresses(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = ListAddressesSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/SignMessage" => { #[allow(non_camel_case_types)] struct SignMessageSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for SignMessageSvc { type Response = super::SignMessageResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::sign_message(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = SignMessageSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/SignRawTransaction" => { #[allow(non_camel_case_types)] struct SignRawTransactionSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for SignRawTransactionSvc { type Response = super::SignRawTransactionResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::sign_raw_transaction(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = SignRawTransactionSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/ListTransactions" => { #[allow(non_camel_case_types)] struct ListTransactionsSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for ListTransactionsSvc { type Response = super::ListTransactionsResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::list_transactions(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = ListTransactionsSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/SetDefaultFee" => { #[allow(non_camel_case_types)] struct SetDefaultFeeSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for SetDefaultFeeSvc { type Response = super::SetDefaultFeeResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::set_default_fee(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = SetDefaultFeeSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetMnemonic" => { #[allow(non_camel_case_types)] struct GetMnemonicSvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetMnemonicSvc { type Response = super::GetMnemonicResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_mnemonic(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetMnemonicSvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } "/pactus.Wallet/GetPrivateKey" => { #[allow(non_camel_case_types)] struct GetPrivateKeySvc(pub Arc); impl< T: Wallet, > tonic::server::UnaryService for GetPrivateKeySvc { type Response = super::GetPrivateKeyResponse; type Future = BoxFuture< tonic::Response, tonic::Status, >; fn call( &mut self, request: tonic::Request, ) -> Self::Future { let inner = Arc::clone(&self.0); let fut = async move { ::get_private_key(&inner, request).await }; Box::pin(fut) } } let accept_compression_encodings = self.accept_compression_encodings; let send_compression_encodings = self.send_compression_encodings; let max_decoding_message_size = self.max_decoding_message_size; let max_encoding_message_size = self.max_encoding_message_size; let inner = self.inner.clone(); let fut = async move { let method = GetPrivateKeySvc(inner); let codec = tonic_prost::ProstCodec::default(); let mut grpc = tonic::server::Grpc::new(codec) .apply_compression_config( accept_compression_encodings, send_compression_encodings, ) .apply_max_message_size_config( max_decoding_message_size, max_encoding_message_size, ); let res = grpc.unary(method, req).await; Ok(res) }; Box::pin(fut) } _ => { Box::pin(async move { let mut response = http::Response::new( tonic::body::Body::default(), ); let headers = response.headers_mut(); headers .insert( tonic::Status::GRPC_STATUS, (tonic::Code::Unimplemented as i32).into(), ); headers .insert( http::header::CONTENT_TYPE, tonic::metadata::GRPC_CONTENT_TYPE, ); Ok(response) }) } } } } impl Clone for WalletServer { fn clone(&self) -> Self { let inner = self.inner.clone(); Self { inner, accept_compression_encodings: self.accept_compression_encodings, send_compression_encodings: self.send_compression_encodings, max_decoding_message_size: self.max_decoding_message_size, max_encoding_message_size: self.max_encoding_message_size, } } } /// Generated gRPC service name pub const SERVICE_NAME: &str = "pactus.Wallet"; impl tonic::server::NamedService for WalletServer { const NAME: &'static str = SERVICE_NAME; } } ================================================ FILE: www/grpc/middleware.go ================================================ package grpc import ( "context" "runtime/debug" rec "github.com/grpc-ecosystem/go-grpc-middleware/recovery" "github.com/pactus-project/pactus/util/htpasswd" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func BasicAuth(storedCredential string) grpc.UnaryServerInterceptor { return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) ( any, error, ) { user, password, err := htpasswd.ExtractBasicAuthFromContext(ctx) if err != nil { return nil, status.Error(codes.Unauthenticated, "failed to extract basic auth from header") } if err := htpasswd.CompareBasicAuth(storedCredential, user, password); err != nil { return nil, status.Error(codes.Unauthenticated, "username or password is invalid") } return handler(ctx, req) } } func (s *Server) Recovery() grpc.UnaryServerInterceptor { recovery := func(p any) (err error) { err = status.Errorf(codes.Unknown, "%v", p) stackTrace := debug.Stack() s.logger.Error( "recovery panic triggered in grpc server", "error", err, "stacktrace", string(stackTrace), ) return err } opts := []rec.Option{ rec.WithRecoveryHandler(recovery), } return rec.UnaryServerInterceptor(opts...) } ================================================ FILE: www/grpc/middleware_test.go ================================================ package grpc import ( "context" "encoding/base64" "testing" "github.com/stretchr/testify/assert" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // mockUnaryHandler simulates a gRPC method handler. func mockUnaryHandler(_ context.Context, _ any) (any, error) { return "response", nil } func mockUnaryPanicHandler(_ context.Context, _ any) (any, error) { panic("panic happen!!!") } func TestBasicAuth(t *testing.T) { auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("user:password")) invalidAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("invalid:invalid")) malformedAuth := "Malformed" tests := []struct { name string authHeader string expectedError codes.Code }{ { name: "ValidCredentials", authHeader: auth, expectedError: codes.OK, }, { name: "InvalidCredentials", authHeader: invalidAuth, expectedError: codes.Unauthenticated, }, { name: "NoMetadata", authHeader: "", expectedError: codes.Unauthenticated, }, { name: "MalformedAuthHeader", authHeader: malformedAuth, expectedError: codes.Unauthenticated, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := t.Context() if tt.authHeader != "" { md := metadata.New(map[string]string{"authorization": tt.authHeader}) ctx = metadata.NewIncomingContext(ctx, md) } interceptor := BasicAuth("user:$2y$10$5Kjd955BDWLouqckHzBjKuCF6hFOUD61lhm8QpjDVHTUwMIrYUdq2") _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, mockUnaryHandler) got, want := status.Code(err), tt.expectedError assert.Equal(t, want, got) }) } } func TestGrpcRecovery(t *testing.T) { s := setup(t, nil) interceptor := s.server.Recovery() _, err := interceptor(t.Context(), nil, &grpc.UnaryServerInfo{}, mockUnaryPanicHandler) assert.Equal(t, codes.Unknown, status.Code(err)) } ================================================ FILE: www/grpc/network.go ================================================ package grpc import ( "context" "time" "github.com/fxamacker/cbor/v2" "github.com/pactus-project/pactus/sync/peerset/peer" "github.com/pactus-project/pactus/sync/peerset/peer/metric" "github.com/pactus-project/pactus/version" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) type networkServer struct { *Server } func newNetworkServer(server *Server) *networkServer { return &networkServer{ Server: server, } } func (s *networkServer) GetNodeInfo(_ context.Context, _ *pactus.GetNodeInfoRequest, ) (*pactus.GetNodeInfoResponse, error) { peerSet := s.sync.PeerSet() clockOffset, err := s.sync.ClockOffset() if err != nil { s.logger.Warn("failed to get clock offset", "err", err) } resp := &pactus.GetNodeInfoResponse{ NetworkName: s.net.Name(), Moniker: s.sync.Moniker(), Agent: version.NodeAgent.String(), PeerId: s.sync.SelfID().String(), Reachability: s.net.ReachabilityStatus(), LocalAddrs: s.net.HostAddrs(), StartedAt: uint64(peerSet.StartedAt().Unix()), CurrentTime: uint64(time.Now().Unix()), Protocols: s.net.Protocols(), Services: int32(s.sync.Services()), ServicesNames: s.sync.Services().String(), ClockOffset: clockOffset.Seconds(), ConnectionInfo: &pactus.ConnectionInfo{ Connections: uint64(s.net.NumConnectedPeers()), InboundConnections: uint64(s.net.NumInbound()), OutboundConnections: uint64(s.net.NumOutbound()), }, ZmqPublishers: make([]*pactus.ZMQPublisherInfo, 0), } for _, publisher := range s.zmqPublishers { resp.ZmqPublishers = append(resp.ZmqPublishers, &pactus.ZMQPublisherInfo{ Topic: publisher.TopicName(), Address: publisher.Address(), Hwm: int32(publisher.HWM()), }) } return resp, nil } func (s *networkServer) GetNetworkInfo(_ context.Context, _ *pactus.GetNetworkInfoRequest, ) (*pactus.GetNetworkInfoResponse, error) { peerSet := s.sync.PeerSet() var count uint32 peerSet.IteratePeers(func(p *peer.Peer) bool { if p.Status.IsConnectedOrKnown() { count++ } return false }) return &pactus.GetNetworkInfoResponse{ NetworkName: s.net.Name(), ConnectedPeersCount: count, MetricInfo: metricToProto(peerSet.Metric()), }, nil } func (s *networkServer) ListPeers(_ context.Context, req *pactus.ListPeersRequest, ) (*pactus.ListPeersResponse, error) { peerSet := s.sync.PeerSet() peerInfos := make([]*pactus.PeerInfo, 0, peerSet.Len()) peerSet.IteratePeers(func(peer *peer.Peer) bool { if !req.IncludeDisconnected && !peer.Status.IsConnectedOrKnown() { return false } peerInfo := new(pactus.PeerInfo) peerInfos = append(peerInfos, peerInfo) data, err := cbor.Marshal(peer.Agent) if err != nil { s.logger.Error("couldn't marshal agent", "error", err) return false } peerInfo.Agent = string(data) peerInfo.PeerId = peer.PeerID.String() peerInfo.Moniker = peer.Moniker peerInfo.Agent = peer.Agent peerInfo.Address = peer.Address peerInfo.Direction = pactus.Direction(peer.Direction) peerInfo.Services = uint32(peer.Services) peerInfo.Height = uint32(peer.Height) peerInfo.Protocols = peer.Protocols peerInfo.Status = int32(peer.Status) peerInfo.LastSent = peer.LastSent.Unix() peerInfo.LastReceived = peer.LastReceived.Unix() peerInfo.LastBlockHash = peer.LastBlockHash.String() peerInfo.TotalSessions = int32(peer.TotalSessions) peerInfo.CompletedSessions = int32(peer.CompletedSessions) peerInfo.OutboundHelloSent = peer.OutboundHelloSent peerInfo.MetricInfo = metricToProto(peer.Metric) for _, key := range peer.ConsensusKeys { peerInfo.ConsensusKeys = append(peerInfo.ConsensusKeys, key.String()) peerInfo.ConsensusAddresses = append(peerInfo.ConsensusAddresses, key.ValidatorAddress().String()) } return false }) return &pactus.ListPeersResponse{Peers: peerInfos}, nil } func metricToProto(metric metric.Metric) *pactus.MetricInfo { metricInfo := &pactus.MetricInfo{ TotalInvalid: &pactus.CounterInfo{ Bytes: uint64(metric.TotalInvalid.Bytes), Bundles: uint64(metric.TotalInvalid.Bundles), }, TotalSent: &pactus.CounterInfo{ Bytes: uint64(metric.TotalSent.Bytes), Bundles: uint64(metric.TotalSent.Bundles), }, TotalReceived: &pactus.CounterInfo{ Bytes: uint64(metric.TotalReceived.Bytes), Bundles: uint64(metric.TotalReceived.Bundles), }, } metricInfo.MessageSent = make(map[int32]*pactus.CounterInfo) for msgType, counter := range metric.MessageSent { metricInfo.MessageSent[int32(msgType)] = &pactus.CounterInfo{ Bytes: uint64(counter.Bytes), Bundles: uint64(counter.Bundles), } } metricInfo.MessageReceived = make(map[int32]*pactus.CounterInfo) for msgType, counter := range metric.MessageReceived { metricInfo.MessageReceived[int32(msgType)] = &pactus.CounterInfo{ Bytes: uint64(counter.Bytes), Bundles: uint64(counter.Bundles), } } return metricInfo } func (*networkServer) Ping(_ context.Context, _ *pactus.PingRequest, ) (*pactus.PingResponse, error) { // Simply return an empty response for latency measurement return &pactus.PingResponse{}, nil } ================================================ FILE: www/grpc/network_test.go ================================================ package grpc import ( "testing" lp2ppeer "github.com/libp2p/go-libp2p/core/peer" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/version" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetNetworkInfo(t *testing.T) { td := setup(t, nil) client := td.networkClient(t) res, err := client.GetNetworkInfo(t.Context(), &pactus.GetNetworkInfoRequest{}) require.NoError(t, err) assert.NotNil(t, res) assert.NotEmpty(t, res.NetworkName) } func TestListPeers(t *testing.T) { td := setup(t, nil) client := td.networkClient(t) res, err := client.ListPeers(t.Context(), &pactus.ListPeersRequest{IncludeDisconnected: true}) require.NoError(t, err) assert.Len(t, res.Peers, 2) for _, peer := range res.Peers { assert.NotEmpty(t, peer.PeerId) require.NoError(t, err) pid, _ := lp2ppeer.Decode(peer.PeerId) pp := td.mockSync.PeerSet().GetPeer(pid) assert.Equal(t, peer.Agent, pp.Agent) assert.Equal(t, peer.Moniker, pp.Moniker) assert.Equal(t, types.Height(peer.Height), pp.Height) assert.NotEmpty(t, pp.ConsensusKeys) for _, key := range pp.ConsensusKeys { assert.Contains(t, peer.ConsensusKeys, key.String()) } } } func TestGetNodeInfo(t *testing.T) { td := setup(t, nil) client := td.networkClient(t) res, err := client.GetNodeInfo(t.Context(), &pactus.GetNodeInfoRequest{}) require.NoError(t, err) assert.Equal(t, version.NodeAgent.String(), res.Agent) assert.Equal(t, td.mockSync.SelfID().String(), res.PeerId) assert.Equal(t, "test-moniker", res.Moniker) assert.Equal(t, "zmq_address", res.ZmqPublishers[0].Address) assert.Equal(t, "zmq_topic", res.ZmqPublishers[0].Topic) assert.Equal(t, int32(100), res.ZmqPublishers[0].Hwm) } func TestPing(t *testing.T) { conf := testConfig() td := setup(t, conf) client := td.networkClient(t) t.Run("Should return empty response for ping", func(t *testing.T) { res, err := client.Ping(t.Context(), &pactus.PingRequest{}) require.NoError(t, err) assert.NotNil(t, res) assert.IsType(t, &pactus.PingResponse{}, res) }) t.Run("Should handle multiple ping requests", func(t *testing.T) { // Test multiple consecutive pings to ensure consistency for i := 0; i < 5; i++ { res, err := client.Ping(t.Context(), &pactus.PingRequest{}) require.NoError(t, err) assert.NotNil(t, res) } }) } ================================================ FILE: www/grpc/proto/.clang-format ================================================ BasedOnStyle: Google ColumnLimit: 120 ================================================ FILE: www/grpc/proto/blockchain.proto ================================================ syntax = "proto3"; package pactus; import "transaction.proto"; option go_package = "github.com/pactus-project/pactus/www/grpc/pactus"; option java_package = "pactus"; // Blockchain service defines RPC methods for interacting with the blockchain. service Blockchain { // GetBlock retrieves information about a block based on the provided request parameters. rpc GetBlock(GetBlockRequest) returns (GetBlockResponse); // GetBlockHash retrieves the hash of a block at the specified height. rpc GetBlockHash(GetBlockHashRequest) returns (GetBlockHashResponse); // GetBlockHeight retrieves the height of a block with the specified hash. rpc GetBlockHeight(GetBlockHeightRequest) returns (GetBlockHeightResponse); // GetBlockchainInfo retrieves general information about the blockchain. rpc GetBlockchainInfo(GetBlockchainInfoRequest) returns (GetBlockchainInfoResponse); // GetCommitteeInfo retrieves information about the current committee. rpc GetCommitteeInfo(GetCommitteeInfoRequest) returns (GetCommitteeInfoResponse); // GetConsensusInfo retrieves information about the consensus instances. rpc GetConsensusInfo(GetConsensusInfoRequest) returns (GetConsensusInfoResponse); // GetAccount retrieves information about an account based on the provided address. rpc GetAccount(GetAccountRequest) returns (GetAccountResponse); // GetValidator retrieves information about a validator based on the provided address. rpc GetValidator(GetValidatorRequest) returns (GetValidatorResponse); // GetValidatorByNumber retrieves information about a validator based on the provided number. rpc GetValidatorByNumber(GetValidatorByNumberRequest) returns (GetValidatorResponse); // GetValidatorAddresses retrieves a list of all validator addresses. rpc GetValidatorAddresses(GetValidatorAddressesRequest) returns (GetValidatorAddressesResponse); // GetPublicKey retrieves the public key of an account based on the provided address. rpc GetPublicKey(GetPublicKeyRequest) returns (GetPublicKeyResponse); // GetTxPoolContent retrieves current transactions in the transaction pool. rpc GetTxPoolContent(GetTxPoolContentRequest) returns (GetTxPoolContentResponse); } // Request message for retrieving account information. message GetAccountRequest { // The address of the account to retrieve information for. string address = 1; } // Response message contains account information. message GetAccountResponse { // Detailed information about the account. AccountInfo account = 1; } // Request message for retrieving validator addresses. message GetValidatorAddressesRequest { } // Response message contains list of validator addresses. message GetValidatorAddressesResponse { // List of validator addresses. repeated string addresses = 1; } // Request message for retrieving validator information by address. message GetValidatorRequest { // The address of the validator to retrieve information for. string address = 1; } // Request message for retrieving validator information by number. message GetValidatorByNumberRequest { // The unique number of the validator to retrieve information for. int32 number = 1; } // Response message contains validator information. message GetValidatorResponse { // Detailed information about the validator. ValidatorInfo validator = 1; } // Request message for retrieving public key by address. message GetPublicKeyRequest { // The address for which to retrieve the public key. string address = 1; } // Response message contains public key information. message GetPublicKeyResponse { // The public key associated with the provided address. string public_key = 1; } // Request message for retrieving block information based on height and verbosity level. message GetBlockRequest { // The height of the block to retrieve. uint32 height = 1; // The verbosity level for block information. BlockVerbosity verbosity = 2; } // Response message contains block information. message GetBlockResponse { // The height of the block. uint32 height = 1; // The hash of the block. string hash = 2; // Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA. string data = 3; // The timestamp of the block. uint32 block_time = 4; // Header information of the block. BlockHeaderInfo header = 5; // Certificate information of the previous block. CertificateInfo prev_cert = 6; // List of transactions in the block, available when verbosity level is set to // BLOCK_VERBOSITY_TRANSACTIONS. repeated TransactionInfo txs = 7; } // Request message for retrieving block hash by height. message GetBlockHashRequest { // The height of the block to retrieve the hash for. uint32 height = 1; } // Response message contains block hash. message GetBlockHashResponse { // The hash of the block. string hash = 1; } // Request message for retrieving block height by hash. message GetBlockHeightRequest { // The hash of the block to retrieve the height for. string hash = 1; } // Response message contains block height. message GetBlockHeightResponse { // The height of the block. uint32 height = 1; } // Request message for retrieving blockchain information. message GetBlockchainInfoRequest { } // Response message contains general blockchain information. message GetBlockchainInfoResponse { // The height of the last block in the blockchain. uint32 last_block_height = 1; // The hash of the last block in the blockchain. string last_block_hash = 2; // The timestamp of the last block in Unix format. int64 last_block_time = 10; // The total number of accounts in the blockchain. int32 total_accounts = 3; // The total number of validators in the blockchain. int32 total_validators = 4; // The number of active (not unbonded) validators in the blockchain. int32 active_validators = 12; // The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. int64 total_power = 5; // The power of the committee. int64 committee_power = 6; // If the blocks are subject to pruning. bool is_pruned = 8; // Lowest-height block stored (only present if pruning is enabled) uint32 pruning_height = 9; // Indicates whether this node participates in consensus: true if at least one // of its running validators is a member of the current committee. bool in_committee = 13; // The number of validators in the current committee. int32 committee_size = 14; // Average availability score of validators with stake, in percentage (0-100). double average_score = 15; } // Request message for retrieving committee information. message GetCommitteeInfoRequest { } // Response message contains committee information. message GetCommitteeInfoResponse { // The number of validators in the committee. int32 committee_size = 1; // The power of the committee. int64 committee_power = 2; // The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC. int64 total_power = 3; // List of committee validators. repeated ValidatorInfo validators = 4; // Map of protocol versions and their percentages in the committee. map protocol_versions = 5; } // Request message for retrieving consensus information. message GetConsensusInfoRequest { } // Response message contains consensus information. message GetConsensusInfoResponse { // The proposal of the consensus info. ProposalInfo proposal = 1; // List of consensus instances. repeated ConsensusInfo instances = 2; } // Request message for retrieving transactions in the transaction pool. message GetTxPoolContentRequest { // The type of transactions to retrieve from the transaction pool. 0 means all types. PayloadType payload_type = 1; } // Response message contains transactions in the transaction pool. message GetTxPoolContentResponse { // List of transactions currently in the pool. repeated TransactionInfo txs = 1; } // Message contains information about a validator. message ValidatorInfo { // The hash of the validator. string hash = 1; // The serialized data of the validator. string data = 2; // The public key of the validator. string public_key = 3; // The unique number assigned to the validator. int32 number = 4; // The stake of the validator in NanoPAC. int64 stake = 5; // The height at which the validator last bonded. uint32 last_bonding_height = 6; // The height at which the validator last participated in sortition. uint32 last_sortition_height = 7; // The height at which the validator will unbond. uint32 unbonding_height = 8; // The address of the validator. string address = 9; // The availability score of the validator. double availability_score = 10; // The protocol version of the validator. int32 protocol_version = 11; // Whether the validator is delegated. bool is_delegated = 12; // The address of the stake owner of the validator. string delegate_owner = 13; // The share of the stake owner of the validator. int64 delegate_share = 14; // The expiry of the stake owner of the validator. uint32 delegate_expiry = 15; } // Message contains information about an account. message AccountInfo { // The hash of the account. string hash = 1; // The serialized data of the account. string data = 2; // The unique number assigned to the account. int32 number = 3; // The balance of the account in NanoPAC. int64 balance = 4; // The address of the account. string address = 5; } // Message contains information about the header of a block. message BlockHeaderInfo { // The version of the block. int32 version = 1; // The hash of the previous block. string prev_block_hash = 2; // The state root hash of the blockchain. string state_root = 3; // The sortition seed of the block. string sortition_seed = 4; // The address of the proposer of the block. string proposer_address = 5; } // Message contains information about a certificate. message CertificateInfo { // The hash of the certificate. string hash = 1; // The round of the certificate. int32 round = 2; // List of committers in the certificate. repeated int32 committers = 3; // List of absentees in the certificate. repeated int32 absentees = 4; // The signature of the certificate. string signature = 5; } // Message contains information about a vote. message VoteInfo { // The type of the vote. VoteType type = 1; // The address of the voter. string voter = 2; // The hash of the block being voted on. string block_hash = 3; // The consensus round of the vote. int32 round = 4; // The change-proposer round of the vote. int32 cp_round = 5; // The change-proposer value of the vote. int32 cp_value = 6; } // Message contains information about a consensus instance. message ConsensusInfo { // The address of the consensus instance. string address = 1; // Indicates whether the consensus instance is active and part of the committee. bool active = 2; // The height of the consensus instance. uint32 height = 3; // The round of the consensus instance. int32 round = 4; // List of votes in the consensus instance. repeated VoteInfo votes = 5; } // Message contains information about a proposal. message ProposalInfo { // The height of the proposal. uint32 height = 1; // The round of the proposal. int32 round = 2; // The block data of the proposal. string block_data = 3; // The signature of the proposal, signed by the proposer. string signature = 4; } // Enumeration for verbosity levels when requesting block information. enum BlockVerbosity { // Request only block data. BLOCK_VERBOSITY_DATA = 0; // Request block information and transaction IDs. BLOCK_VERBOSITY_INFO = 1; // Request block information and detailed transaction data. BLOCK_VERBOSITY_TRANSACTIONS = 2; } // Enumeration for types of votes. enum VoteType { // Unspecified vote type. VOTE_TYPE_UNSPECIFIED = 0; // Prepare vote type. VOTE_TYPE_PREPARE = 1; // Precommit vote type. VOTE_TYPE_PRECOMMIT = 2; // Change-proposer:pre-vote vote type. VOTE_TYPE_CP_PRE_VOTE = 3; // Change-proposer:main-vote vote type. VOTE_TYPE_CP_MAIN_VOTE = 4; // Change-proposer:decided vote type. VOTE_TYPE_CP_DECIDED = 5; } ================================================ FILE: www/grpc/proto/network.proto ================================================ syntax = "proto3"; package pactus; option go_package = "github.com/pactus-project/pactus/www/grpc/pactus"; option java_package = "pactus"; // Direction represents the connection direction between peers. enum Direction { // Unknown direction (default value). DIRECTION_UNKNOWN = 0; // Inbound connection - peer connected to us. DIRECTION_INBOUND = 1; // Outbound connection - we connected to peer. DIRECTION_OUTBOUND = 2; } // Network service provides RPCs for retrieving information about the network. service Network { // GetNetworkInfo retrieves information about the overall network. rpc GetNetworkInfo(GetNetworkInfoRequest) returns (GetNetworkInfoResponse); // ListPeers lists all peers in the network. rpc ListPeers(ListPeersRequest) returns (ListPeersResponse); // GetNodeInfo retrieves information about a specific node in the network. rpc GetNodeInfo(GetNodeInfoRequest) returns (GetNodeInfoResponse); // Ping provides a simple connectivity test and latency measurement. rpc Ping(PingRequest) returns (PingResponse); } // Request message for retrieving overall network information. message GetNetworkInfoRequest { } // Response message contains information about the overall network. message GetNetworkInfoResponse { // Name of the P2P network. string network_name = 1; // Number of connected peers. uint32 connected_peers_count = 2; // Metrics related to node activity. MetricInfo metric_info = 4; } // Request message for listing peers. message ListPeersRequest { // If true, includes disconnected peers (default: connected peers only). bool include_disconnected = 1; } // Response message for listing peers. message ListPeersResponse { // List of peers. repeated PeerInfo peers = 1; } // Request message for retrieving information of the node. message GetNodeInfoRequest { } // Response message contains information about a specific node in the network. message GetNodeInfoResponse { // Moniker or Human-readable name identifying this node in the network. string moniker = 1; // Version and agent details of the node. string agent = 2; // Peer ID of the node. string peer_id = 3; // Unix timestamp when the node was started (UTC). uint64 started_at = 4; // Reachability status of the node. string reachability = 5; // Bitfield representing the services provided by the node. int32 services = 6; // Names of services provided by the node. string services_names = 7; // List of addresses associated with the node. repeated string local_addrs = 8; // List of protocols supported by the node. repeated string protocols = 9; // Offset between the node's clock and the network's clock (in seconds). double clock_offset = 13; // Information about the node's connections. ConnectionInfo connection_info = 14; // List of active ZeroMQ publishers. repeated ZMQPublisherInfo zmq_publishers = 15; // Current Unix timestamp of the node (UTC). uint64 current_time = 16; // Name of the P2P network. string network_name = 17; } // ZMQPublisherInfo contains information about a ZeroMQ publisher. message ZMQPublisherInfo { // The topic associated with the publisher. string topic = 1; // The address of the publisher. string address = 2; // The high-water mark (HWM) for the publisher, indicating the // maximum number of messages to queue before dropping older ones. int32 hwm = 3; } // PeerInfo contains information about a peer in the network. message PeerInfo { // Current status of the peer (e.g., connected, disconnected). int32 status = 1; // Moniker or Human-Readable name of the peer. string moniker = 2; // Version and agent details of the peer. string agent = 3; // Peer ID of the peer in P2P network. string peer_id = 4; // List of consensus keys used by the peer. repeated string consensus_keys = 5; // List of consensus addresses used by the peer. repeated string consensus_addresses = 6; // Bitfield representing the services provided by the peer. uint32 services = 7; // Hash of the last block the peer knows. string last_block_hash = 8; // Blockchain height of the peer. uint32 height = 9; // Unix timestamp of the last bundle sent to the peer (UTC). int64 last_sent = 10; // Unix timestamp of the last bundle received from the peer (UTC). int64 last_received = 11; // Network address of the peer. string address = 12; // Connection direction (e.g., inbound, outbound). Direction direction = 13; // List of protocols supported by the peer. repeated string protocols = 14; // Total download sessions with the peer. int32 total_sessions = 15; // Completed download sessions with the peer. int32 completed_sessions = 16; // Metrics related to peer activity. MetricInfo metric_info = 17; // Whether the hello message was sent from the outbound connection. bool outbound_hello_sent = 18; } // ConnectionInfo contains information about the node's connections. message ConnectionInfo { // Total number of connections. uint64 connections = 1; // Number of inbound connections. uint64 inbound_connections = 2; // Number of outbound connections. uint64 outbound_connections = 3; } // MetricInfo contains metrics data regarding network activity. message MetricInfo { // Total number of invalid bundles. CounterInfo total_invalid = 1; // Total number of bundles sent. CounterInfo total_sent = 2; // Total number of bundles received. CounterInfo total_received = 3; // Number of sent bundles categorized by message type. map message_sent = 4; // Number of received bundles categorized by message type. map message_received = 5; } // CounterInfo holds counter data regarding byte and bundle counts. message CounterInfo { // Total number of bytes. uint64 bytes = 1; // Total number of bundles. uint64 bundles = 2; } // Request message for ping - intentionally empty for measuring round-trip time. message PingRequest { // Empty request payload for measuring round-trip time } // Response message for ping - intentionally empty for measuring round-trip time. message PingResponse { // Empty response payload for measuring round-trip time } ================================================ FILE: www/grpc/proto/transaction.proto ================================================ syntax = "proto3"; package pactus; option go_package = "github.com/pactus-project/pactus/www/grpc/pactus"; option java_package = "pactus"; // Transaction service defines various RPC methods for interacting with transactions. service Transaction { // GetTransaction retrieves transaction details based on the provided request parameters. rpc GetTransaction(GetTransactionRequest) returns (GetTransactionResponse); // CalculateFee calculates the transaction fee based on the specified amount and payload type. rpc CalculateFee(CalculateFeeRequest) returns (CalculateFeeResponse); // BroadcastTransaction broadcasts a signed transaction to the network. rpc BroadcastTransaction(BroadcastTransactionRequest) returns (BroadcastTransactionResponse); // GetRawTransferTransaction retrieves raw details of a transfer transaction. rpc GetRawTransferTransaction(GetRawTransferTransactionRequest) returns (GetRawTransactionResponse); // GetRawBondTransaction retrieves raw details of a bond transaction. rpc GetRawBondTransaction(GetRawBondTransactionRequest) returns (GetRawTransactionResponse); // GetRawUnbondTransaction retrieves raw details of an unbond transaction. rpc GetRawUnbondTransaction(GetRawUnbondTransactionRequest) returns (GetRawTransactionResponse); // GetRawWithdrawTransaction retrieves raw details of a withdraw transaction. rpc GetRawWithdrawTransaction(GetRawWithdrawTransactionRequest) returns (GetRawTransactionResponse); // GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction. rpc GetRawBatchTransferTransaction(GetRawBatchTransferTransactionRequest) returns (GetRawTransactionResponse); // DecodeRawTransaction accepts raw transaction and returns decoded transaction. rpc DecodeRawTransaction(DecodeRawTransactionRequest) returns (DecodeRawTransactionResponse); // CheckTransaction checks if the transaction is valid and can be included in the blockchain. rpc CheckTransaction(CheckTransactionRequest) returns (CheckTransactionResponse); } // Request message for retrieving transaction details. message GetTransactionRequest { // The unique ID of the transaction to retrieve. string id = 1; // The verbosity level for transaction details. TransactionVerbosity verbosity = 2; } // Response message contains details of a transaction. message GetTransactionResponse { // The height of the block containing the transaction. uint32 block_height = 1; // The UNIX timestamp of the block containing the transaction. uint32 block_time = 2; // Detailed information about the transaction. TransactionInfo transaction = 3; } // Request message for calculating transaction fee. message CalculateFeeRequest { // The amount involved in the transaction, specified in NanoPAC. int64 amount = 1; // The type of transaction payload. PayloadType payload_type = 2; // Indicates if the amount should be fixed and include the fee. bool fixed_amount = 3; } // Response message contains the calculated transaction fee. message CalculateFeeResponse { // The calculated amount in NanoPAC. int64 amount = 1; // The calculated transaction fee in NanoPAC. int64 fee = 2; } // Request message for broadcasting a signed transaction to the network. message BroadcastTransactionRequest { // The signed raw transaction data to be broadcasted. string signed_raw_transaction = 1; } // Response message contains the ID of the broadcasted transaction. message BroadcastTransactionResponse { // The unique ID of the broadcasted transaction. string id = 1; } // Request message for retrieving raw details of a transfer transaction. message GetRawTransferTransactionRequest { // The lock time for the transaction. If not set, defaults to the last block height. uint32 lock_time = 1; // The sender's account address. string sender = 2; // The receiver's account address. string receiver = 3; // The amount to be transferred, specified in NanoPAC. Must be greater than 0. int64 amount = 4; // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. int64 fee = 5; // A memo string for the transaction. string memo = 6; } // Request message for retrieving raw details of a bond transaction. message GetRawBondTransactionRequest { // The lock time for the transaction. If not set, defaults to the last block height. uint32 lock_time = 1; // The sender's account address. string sender = 2; // The receiver's validator address. string receiver = 3; // The stake amount in NanoPAC. Must be greater than 0. int64 stake = 4; // The public key of the validator. // Optional, but required when registering a new validator.; string public_key = 5; // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. int64 fee = 6; // A memo string for the transaction. string memo = 7; // The address of the delegate owner. // Optional, but required when registering a new validator with delegation.; string delegate_owner = 8; // The share percentage for the delegate owner. // Optional, but required when registering a new validator with delegation.; // Must be between 0 and 0.7 PAC in nano PAC. int64 delegate_share = 9; // The expiry height for the delegate relationship. // Optional, but required when registering a new validator with delegation.; uint32 delegate_expiry = 10; } // Request message for retrieving raw details of an unbond transaction. message GetRawUnbondTransactionRequest { // The lock time for the transaction. If not set, defaults to the last block height. uint32 lock_time = 1; // The address of the validator to unbond from. string validator_address = 2; // A memo string for the transaction. string memo = 3; // The address of the delegate owner. // Optional, but required when the validator is a delegated validator.; string delegate_owner = 4; } // Request message for retrieving raw details of a withdraw transaction. message GetRawWithdrawTransactionRequest { // The lock time for the transaction. If not set, defaults to the last block height. uint32 lock_time = 1; // The address of the validator to withdraw from. string validator_address = 2; // The address of the account to withdraw to. string account_address = 3; // The withdrawal amount in NanoPAC. Must be greater than 0. int64 amount = 4; // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. int64 fee = 5; // A memo string for the transaction. string memo = 6; } // Request message for retrieving raw details of a batch transfer transaction. message GetRawBatchTransferTransactionRequest { // The lock time for the transaction. If not set, defaults to the last block height. uint32 lock_time = 1; // The sender's account address. string sender = 2; // The list of recipients with their amounts. Minimum 2 recipients required. repeated Recipient recipients = 3; // The transaction fee in NanoPAC. If not set, it is set to the estimated fee. int64 fee = 4; // A memo string for the transaction. string memo = 5; } // Response message contains raw transaction data. message GetRawTransactionResponse { // The raw transaction data in hexadecimal format. string raw_transaction = 1; // The unique ID of the transaction. string id = 2; } // Payload for a transfer transaction. message PayloadTransfer { // The sender's address. string sender = 1; // The receiver's address. string receiver = 2; // The amount to be transferred in NanoPAC. int64 amount = 3; } // Payload for a bond transaction. message PayloadBond { // The sender's address. string sender = 1; // The receiver's address. string receiver = 2; // The stake amount in NanoPAC. int64 stake = 3; // The public key of the validator. string public_key = 4; // Indicates whether the bond transaction is a delegation. bool is_delegated = 5; // The address of the delegate owner. // Optional, but required when registering a new validator with delegation.; string delegate_owner = 6; // The share percentage for the delegate owner. // Optional, but required when registering a new validator with delegation.; // Must be between 0 and 0.7 PAC in nano PAC. int64 delegate_share = 7; // The expiry height for the delegate relationship. // Optional, but required when registering a new validator with delegation.; uint32 delegate_expiry = 8; } // Payload for a sortition transaction. message PayloadSortition { // The validator address associated with the sortition proof. string address = 1; // The proof for the sortition. string proof = 2; } // Payload for an unbond transaction. message PayloadUnbond { // The address of the validator to unbond from. string validator = 1; // The address of the delegate owner. // Optional, but required when the validator is a delegated validator.; string delegate_owner = 2; } // Payload for a withdraw transaction. message PayloadWithdraw { // The address of the validator to withdraw from. string validator_address = 1; // The address of the account to withdraw to. string account_address = 2; // The withdrawal amount in NanoPAC. int64 amount = 3; } // Payload for a batch transfer transaction. message PayloadBatchTransfer { // The sender's address. string sender = 1; // The list of recipients with their amounts. repeated Recipient recipients = 2; } // Recipient is receiver with amount. message Recipient { // The receiver's address. string receiver = 1; // The amount in NanoPAC. int64 amount = 2; } // Information about a transaction. message TransactionInfo { // The unique ID of the transaction. string id = 1; // The raw transaction data in hexadecimal format. string data = 2; // The version of the transaction. int32 version = 3; // The lock time for the transaction. uint32 lock_time = 4; // The value of the transaction in NanoPAC. int64 value = 5; // The fee for the transaction in NanoPAC. int64 fee = 6; // The type of transaction payload. PayloadType payload_type = 7; // Transaction payload. oneof payload { // Transfer transaction payload. PayloadTransfer transfer = 30; // Bond transaction payload. PayloadBond bond = 31; // Sortition transaction payload. PayloadSortition sortition = 32; // Unbond transaction payload. PayloadUnbond unbond = 33; // Withdraw transaction payload. PayloadWithdraw withdraw = 34; // Batch Transfer transaction payload. PayloadBatchTransfer batch_transfer = 35; } // A memo string for the transaction. string memo = 8; // The public key associated with the transaction. string public_key = 9; // The signature for the transaction. string signature = 10; // The block height containing the transaction. // A value of zero means the transaction is unconfirmed and may still in the transaction pool. uint32 block_height = 11; // Indicates whether the transaction is confirmed. bool confirmed = 12; // The number of blocks that have been added to the chain after this transaction was included in a block. // A value of zero means the transaction is unconfirmed and may still in the transaction pool. int32 confirmations = 13; } // Enumeration for different types of transaction payloads. enum PayloadType { // Unspecified payload type. PAYLOAD_TYPE_UNSPECIFIED = 0; // Transfer payload type. PAYLOAD_TYPE_TRANSFER = 1; // Bond payload type. PAYLOAD_TYPE_BOND = 2; // Sortition payload type. PAYLOAD_TYPE_SORTITION = 3; // Unbond payload type. PAYLOAD_TYPE_UNBOND = 4; // Withdraw payload type. PAYLOAD_TYPE_WITHDRAW = 5; // Batch transfer payload type. PAYLOAD_TYPE_BATCH_TRANSFER = 6; } // Enumeration for verbosity levels when requesting transaction details. enum TransactionVerbosity { // Request transaction data only. TRANSACTION_VERBOSITY_DATA = 0; // Request detailed transaction information. TRANSACTION_VERBOSITY_INFO = 1; } // Request message for decoding a raw transaction. message DecodeRawTransactionRequest { // The raw transaction data in hexadecimal format. string raw_transaction = 1; } // Response message contains the decoded transaction. message DecodeRawTransactionResponse { // The decoded transaction information. TransactionInfo transaction = 1; } // Request message for checking a transaction. message CheckTransactionRequest { // The raw transaction data to be checked. string raw_transaction = 1; } // Response message contains the result of the transaction check. message CheckTransactionResponse { // Indicates whether the transaction is valid. bool is_valid = 1; // An error message if the transaction is invalid. // Empty if the transaction is valid. string error_message = 2; } ================================================ FILE: www/grpc/proto/utils.proto ================================================ syntax = "proto3"; package pactus; option go_package = "github.com/pactus-project/pactus/www/grpc/pactus"; option java_package = "pactus"; // Utils service defines RPC methods for utility functions such as message // signing, verification, and other cryptographic operations. service Utils { // SignMessageWithPrivateKey signs a message with the provided private key. rpc SignMessageWithPrivateKey(SignMessageWithPrivateKeyRequest) returns (SignMessageWithPrivateKeyResponse); // VerifyMessage verifies a signature against the public key and message. rpc VerifyMessage(VerifyMessageRequest) returns (VerifyMessageResponse); // PublicKeyAggregation aggregates multiple BLS public keys into a single key. rpc PublicKeyAggregation(PublicKeyAggregationRequest) returns (PublicKeyAggregationResponse); // SignatureAggregation aggregates multiple BLS signatures into a single signature. rpc SignatureAggregation(SignatureAggregationRequest) returns (SignatureAggregationResponse); } // Request message for signing a message with a private key. message SignMessageWithPrivateKeyRequest { // The private key to sign the message. string private_key = 1; // The message content to be signed. string message = 2; } // Response message contains the signature generated from the message. message SignMessageWithPrivateKeyResponse { // The resulting signature in hexadecimal format. string signature = 1; } // Request message for verifying a message signature. message VerifyMessageRequest { // The original message content that was signed. string message = 1; // The signature to verify in hexadecimal format. string signature = 2; // The public key of the signer. string public_key = 3; } // Response message contains the verification result. message VerifyMessageResponse { // Boolean indicating whether the signature is valid for the given message and public key. bool is_valid = 1; } // Request message for aggregating multiple BLS public keys. message PublicKeyAggregationRequest { // List of BLS public keys to be aggregated. repeated string public_keys = 1; } // Response message contains the aggregated BLS public key result. message PublicKeyAggregationResponse { // The aggregated BLS public key. string public_key = 1; // The blockchain address derived from the aggregated public key. string address = 2; } // Request message for aggregating multiple BLS signatures. message SignatureAggregationRequest { // List of BLS signatures to be aggregated. repeated string signatures = 1; } // Response message contains the aggregated BLS signature. message SignatureAggregationResponse { // The aggregated BLS signature in hexadecimal format. string signature = 1; } ================================================ FILE: www/grpc/proto/wallet.proto ================================================ syntax = "proto3"; package pactus; import "transaction.proto"; option go_package = "github.com/pactus-project/pactus/www/grpc/pactus"; option java_package = "pactus"; // Wallet service provides RPC methods for wallet management operations. service Wallet { // CreateWallet creates a new wallet with the specified parameters. rpc CreateWallet(CreateWalletRequest) returns (CreateWalletResponse); // RestoreWallet restores an existing wallet with the given mnemonic. rpc RestoreWallet(RestoreWalletRequest) returns (RestoreWalletResponse); // LoadWallet loads an existing wallet with the given name. // deprecated: It will be removed in a future version. rpc LoadWallet(LoadWalletRequest) returns (LoadWalletResponse); // UnloadWallet unloads a currently loaded wallet with the specified name. // deprecated: It will be removed in a future version. rpc UnloadWallet(UnloadWalletRequest) returns (UnloadWalletResponse); // ListWallets returns a list of all available wallets. rpc ListWallets(ListWalletsRequest) returns (ListWalletsResponse); // GetWalletInfo returns detailed information about a specific wallet. rpc GetWalletInfo(GetWalletInfoRequest) returns (GetWalletInfoResponse); // UpdatePassword updates the password of an existing wallet. rpc UpdatePassword(UpdatePasswordRequest) returns (UpdatePasswordResponse); // GetTotalBalance returns the total available balance of the wallet. rpc GetTotalBalance(GetTotalBalanceRequest) returns (GetTotalBalanceResponse); // GetTotalStake returns the total stake amount in the wallet. rpc GetTotalStake(GetTotalStakeRequest) returns (GetTotalStakeResponse); // GetValidatorAddress retrieves the validator address associated with a public key. // Deprecated: Will move into utils. rpc GetValidatorAddress(GetValidatorAddressRequest) returns (GetValidatorAddressResponse); // GetAddressInfo returns detailed information about a specific address. rpc GetAddressInfo(GetAddressInfoRequest) returns (GetAddressInfoResponse); // SetAddressLabel sets or updates the label for a given address. rpc SetAddressLabel(SetAddressLabelRequest) returns (SetAddressLabelResponse); // GetNewAddress generates a new address for the specified wallet. rpc GetNewAddress(GetNewAddressRequest) returns (GetNewAddressResponse); // ListAddresses returns all addresses in the specified wallet. rpc ListAddresses(ListAddressesRequest) returns (ListAddressesResponse); // SignMessage signs an arbitrary message using a wallet's private key. rpc SignMessage(SignMessageRequest) returns (SignMessageResponse); // SignRawTransaction signs a raw transaction for a specified wallet. rpc SignRawTransaction(SignRawTransactionRequest) returns (SignRawTransactionResponse); // ListTransactions returns a list of transactions for a wallet, // optionally filtered by a specific address, with pagination support. rpc ListTransactions(ListTransactionsRequest) returns (ListTransactionsResponse); // SetDefaultFee sets the default fee for the wallet. rpc SetDefaultFee(SetDefaultFeeRequest) returns (SetDefaultFeeResponse); // GetMnemonic returns the mnemonic (seed phrase) for the wallet. rpc GetMnemonic(GetMnemonicRequest) returns (GetMnemonicResponse); // GetPrivateKey returns the private key for a given address. rpc GetPrivateKey(GetPrivateKeyRequest) returns (GetPrivateKeyResponse); } // AddressType defines different types of blockchain addresses. enum AddressType { // Treasury address type. // Should not be used to generate new addresses. ADDRESS_TYPE_TREASURY = 0; // Validator address type used for validator nodes. ADDRESS_TYPE_VALIDATOR = 1; // Account address type with BLS signature scheme. ADDRESS_TYPE_BLS_ACCOUNT = 2; // Account address type with Ed25519 signature scheme. // Note: Generating a new Ed25519 address requires the wallet password. ADDRESS_TYPE_ED25519_ACCOUNT = 3; } // AddressInfo contains detailed information about a wallet address. message AddressInfo { // The address string. string address = 1; // The public key associated with the address. string public_key = 2; // A human-readable label associated with the address. string label = 3; // The Hierarchical Deterministic (HD) path of the address within the wallet. string path = 4; } // Request message for generating a new wallet address. message GetNewAddressRequest { // The name of the wallet to generate a new address. string wallet_name = 1; // The type of address to generate. AddressType address_type = 2; // A label for the new address. string label = 3; // Password for the new address. It's required when address_type is Ed25519 type. string password = 4; } // Response message contains newly generated address information. message GetNewAddressResponse { // The name of the wallet where address was generated. string wallet_name = 1; // Detailed information about the new address. AddressInfo addr = 2; } // Request message for restoring a wallet from mnemonic (seed phrase). message RestoreWalletRequest { // The name for the restored wallet. string wallet_name = 1; // The mnemonic (seed phrase) for wallet recovery. string mnemonic = 2; // Password to secure the restored wallet. string password = 3; } // Response message confirming wallet restoration. message RestoreWalletResponse { // The name of the restored wallet. string wallet_name = 1; } // Request message for creating a new wallet. message CreateWalletRequest { // The name for the new wallet. string wallet_name = 1; // Password to secure the new wallet. string password = 2; } // Response message contains wallet recovery mnemonic (seed phrase). message CreateWalletResponse { // The name for the new wallet. string wallet_name = 1; // The mnemonic (seed phrase) for wallet recovery. string mnemonic = 2; } // Request message for loading an existing wallet. // Deprecated: It will be removed in a future version. message LoadWalletRequest { // The name of the wallet to load. string wallet_name = 1; } // Response message confirming wallet loaded. // Deprecated: It will be removed in a future version. message LoadWalletResponse { // The name of the loaded wallet. string wallet_name = 1; } // Request message for unloading a wallet. // Deprecated: It will be removed in a future version. message UnloadWalletRequest { // The name of the wallet to unload. string wallet_name = 1; } // Response message confirming wallet unloading. // Deprecated: It will be removed in a future version. message UnloadWalletResponse { // The name of the unloaded wallet. string wallet_name = 1; } // Request message for obtaining the validator address associated with a public key. message GetValidatorAddressRequest { // The public key of the validator. string public_key = 1; } // Response message containing the validator address corresponding to a public key. message GetValidatorAddressResponse { // The validator address associated with the public key. string address = 1; } // Request message for signing a raw transaction. message SignRawTransactionRequest { // The name of the wallet used for signing. string wallet_name = 1; // The raw transaction data to be signed. string raw_transaction = 2; // Wallet password required for signing. string password = 3; } // Response message contains the transaction ID and signed raw transaction. message SignRawTransactionResponse { // The ID of the signed transaction. string transaction_id = 1; // The signed raw transaction data. string signed_raw_transaction = 2; } // Request message for obtaining the total available balance of a wallet. message GetTotalBalanceRequest { // The name of the wallet to get the total balance. string wallet_name = 1; } // Response message contains the total available balance of the wallet. message GetTotalBalanceResponse { // The name of the queried wallet. string wallet_name = 1; // The total balance of the wallet in NanoPAC. int64 total_balance = 2; } // Request message to sign an arbitrary message. message SignMessageRequest { // The name of the wallet to sign with. string wallet_name = 1; // Wallet password required for signing. string password = 2; // The address whose private key should be used for signing the message. string address = 3; // The arbitrary message to be signed. string message = 4; } // Response message contains message signature. message SignMessageResponse { // The signature in hexadecimal format. string signature = 1; } // Request message for obtaining the total stake of a wallet. message GetTotalStakeRequest { // The name of the wallet to get the total stake. string wallet_name = 1; } // Response message contains the total stake of the wallet. message GetTotalStakeResponse { // The name of the queried wallet. string wallet_name = 1; // The total stake amount in NanoPAC. int64 total_stake = 2; } // Request message for getting address information. message GetAddressInfoRequest { // The name of the wallet containing the address. string wallet_name = 1; // The address to query. string address = 2; } // Response message contains address details. message GetAddressInfoResponse { // The name of the wallet containing the address. string wallet_name = 1; // Detailed information about the address. AddressInfo addr = 2; } // Request message for setting address label. message SetAddressLabelRequest { // The name of the wallet containing the address. string wallet_name = 1; // Wallet password required for modification. string password = 2; // The address to label. string address = 3; // The new label for the address. string label = 4; } // Response message for updated address label. message SetAddressLabelResponse { // The name of the wallet where the address label was updated. string wallet_name = 1; // The address where the label was updated. string address = 2; // The new label for the address. string label = 3; } // Request message for listing wallets. message ListWalletsRequest { } // Response message contains wallet names. message ListWalletsResponse { // Array of wallet names. repeated string wallets = 1; } // Request message for getting wallet information. message GetWalletInfoRequest { // The name of the wallet to query. string wallet_name = 1; } // Response message contains wallet details. message GetWalletInfoResponse { // The name of the wallet. string wallet_name = 1; // The wallet format version. int32 version = 2; // The network the wallet is connected to (e.g., mainnet, testnet). string network = 3; // Indicates if the wallet is encrypted. bool encrypted = 4; // A unique identifier of the wallet. string uuid = 5; // Unix timestamp of wallet creation. int64 created_at = 6; // The default fee of the wallet. int64 default_fee = 7; // The storage driver used by the wallet (e.g., SQLite, Legacy JSON ). string driver = 8; // Path to the wallet file or storage location. string path = 9; } // Request message for listing wallet addresses. message ListAddressesRequest { // The name of the queried wallet. string wallet_name = 1; // Filter addresses by their types. If empty, all address types are included. repeated AddressType address_types = 2; } // Response message contains wallet addresses. message ListAddressesResponse { // The name of the queried wallet. string wallet_name = 1; // List of all addresses in the wallet with their details. repeated AddressInfo addrs = 2; } // Request message for updating wallet password. message UpdatePasswordRequest { // The name of the wallet whose password will be updated. string wallet_name = 1; // The current wallet password. string old_password = 2; // The new wallet password. string new_password = 3; } // Response message confirming wallet password update. message UpdatePasswordResponse { // The name of the wallet whose password was updated. string wallet_name = 1; } // TxDirection indicates the direction of a transaction relative to the wallet. enum TxDirection { // include both incoming and outgoing transactions. TX_DIRECTION_ANY = 0; // Include only incoming transactions where the wallet receives funds. TX_DIRECTION_INCOMING = 1; // Include only outgoing transactions where the wallet sends funds. TX_DIRECTION_OUTGOING = 2; } // TransactionStatus defines the status of a transaction. enum TransactionStatus { // Pending status for transactions in the mempool. TRANSACTION_STATUS_PENDING = 0; // Confirmed status for transactions included in a block. TRANSACTION_STATUS_CONFIRMED = 1; // Failed status for transactions that were not successful. TRANSACTION_STATUS_FAILED = -1; } // WalletTransactionInfo contains information about a transaction in a wallet. message WalletTransactionInfo { // A sequence number for the transaction in the wallet. int64 no = 1; // The unique ID of the transaction. string tx_id = 2; // The sender's address. string sender = 3; // The receiver's address. string receiver = 4; // The direction of the transaction relative to the wallet. TxDirection direction = 5; // The amount involved in the transaction in NanoPAC. int64 amount = 6; // The transaction fee in NanoPAC. int64 fee = 7; // A memo string for the transaction. string memo = 8; // The current status of the transaction. TransactionStatus status = 9; // The block height containing the transaction. uint32 block_height = 10; // The type of transaction payload. PayloadType payload_type = 11; // The raw transaction data. bytes data = 12; // A comment associated with the transaction in the wallet. string comment = 13; // Unix timestamp of when the transaction was created. int64 created_at = 14; // Unix timestamp of when the transaction was last updated. int64 updated_at = 15; } // Request message for listing transactions of a wallet, optionally filtered by a specific address. message ListTransactionsRequest { // The name of the wallet to query transactions for. string wallet_name = 1; // Optional: The address to filter transactions. // If empty or set to '*', transactions for all addresses in the wallet are included. string address = 2; // Filter transactions by direction relative to the wallet. // Defaults to any direction if not set. TxDirection direction = 3; // Optional: The maximum number of transactions to return. // Defaults to 10 if not set. int32 count = 4; // Optional: The number of transactions to skip (for pagination). // Defaults to 0 if not set. int32 skip = 5; } // Response message containing a list of transactions. message ListTransactionsResponse { // The name of the wallet queried. string wallet_name = 1; // List of transactions for the wallet, filtered by the specified address if provided. repeated WalletTransactionInfo txs = 2; } // Request message for setting default fee. message SetDefaultFeeRequest { // The name of the wallet to set the default fee. string wallet_name = 1; // The default fee amount in NanoPAC. int64 amount = 2; } // Response message for updated default fee. message SetDefaultFeeResponse { // The name of the wallet where the default fee was updated. string wallet_name = 1; } // Request message for getting mnemonic. message GetMnemonicRequest { // The name of the wallet to get the mnemonic. string wallet_name = 1; // Wallet password. string password = 2; } // Response message contains mnemonic. message GetMnemonicResponse { // The mnemonic (seed phrase). string mnemonic = 1; } // Request message for getting private key. message GetPrivateKeyRequest { // The name of the wallet containing the address. string wallet_name = 1; // Wallet password. string password = 2; // The address to get the private key. string address = 3; } // Response message contains private key. message GetPrivateKeyResponse { // The private key in hexadecimal format. string private_key = 1; } ================================================ FILE: www/grpc/server.go ================================================ package grpc import ( "context" "net" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" wltmgr "github.com/pactus-project/pactus/wallet/manager" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/pactus-project/pactus/www/zmq" "google.golang.org/grpc" ) type Server struct { ctx context.Context config *Config listener net.Listener server *grpc.Server address string state state.Facade net network.Network sync sync.Synchronizer consMgr consmgr.ManagerReader walletMgr wltmgr.IManager zmqPublishers []zmq.Publisher logger *logger.SubLogger } func NewServer(ctx context.Context, conf *Config, state state.Facade, sync sync.Synchronizer, network network.Network, consMgr consmgr.ManagerReader, walletMgr wltmgr.IManager, zmqPublishers []zmq.Publisher, ) *Server { return &Server{ ctx: ctx, config: conf, state: state, sync: sync, net: network, consMgr: consMgr, walletMgr: walletMgr, zmqPublishers: zmqPublishers, logger: logger.NewSubLogger("_grpc", nil), } } func (s *Server) Address() string { return s.address } func (s *Server) StartServer() error { if !s.config.Enable { return nil } listener, err := util.NetworkListen(s.ctx, "tcp", s.config.Listen) if err != nil { return err } return s.startListening(listener) } func (s *Server) startListening(listener net.Listener) error { opts := make([]grpc.UnaryServerInterceptor, 0) if s.config.BasicAuth != "" { opts = append(opts, BasicAuth(s.config.BasicAuth)) } opts = append(opts, s.Recovery()) grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor(opts...)) blockchainServer := newBlockchainServer(s) transactionServer := newTransactionServer(s) networkServer := newNetworkServer(s) utilServer := newUtilsServer(s) pactus.RegisterBlockchainServer(grpcServer, blockchainServer) pactus.RegisterTransactionServer(grpcServer, transactionServer) pactus.RegisterNetworkServer(grpcServer, networkServer) pactus.RegisterUtilsServer(grpcServer, utilServer) if s.config.EnableWallet { walletServer := newWalletServer(s, s.walletMgr) pactus.RegisterWalletServer(grpcServer, walletServer) } s.listener = listener s.address = listener.Addr().String() s.server = grpcServer go func() { s.logger.Info("gRPC server start listening", "address", listener.Addr()) if err := s.server.Serve(listener); err != nil { s.logger.Debug("error on gRPC server", "error", err) } }() return nil } func (s *Server) StopServer() { if s.server != nil { s.server.Stop() _ = s.listener.Close() } } ================================================ FILE: www/grpc/server_test.go ================================================ package grpc import ( "context" "net" "testing" "github.com/pactus-project/pactus/consensus" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/testsuite" wltmgr "github.com/pactus-project/pactus/wallet/manager" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/pactus-project/pactus/www/zmq" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/test/bufconn" ) type testData struct { *testsuite.TestSuite mockState *state.MockState mockSync *sync.MockSync consMocks []*consensus.MockConsensus mockConsMgr consmgr.Manager mockWalletMgr *wltmgr.MockIManager listener *bufconn.Listener server *Server } func testConfig() *Config { conf := DefaultConfig() return conf } func setup(t *testing.T, conf *Config) *testData { t.Helper() if conf == nil { conf = testConfig() } ts := testsuite.NewTestSuite(t) // for saving test wallets in temp directory t.Chdir(util.TempDirPath()) const bufSize = 1024 * 1024 listener := bufconn.Listen(bufSize) valKeys := []*bls.ValidatorKey{ts.RandValKey(), ts.RandValKey()} mockState := state.MockingState(ts) mockNet := network.MockingNetwork(ts, ts.RandPeerID()) mockSync := sync.MockingSync(ts) mockConsMgr, consMocks := consmgr.MockingManager(ts, mockState, valKeys) mockState.CommitTestBlocks(10) mockWalletMgr := wltmgr.NewMockIManager(ts.MockingController()) zmqPublishers := []zmq.Publisher{ zmq.MockingPublisher("zmq_address", "zmq_topic", 100), } server := NewServer(t.Context(), conf, mockState, mockSync, mockNet, mockConsMgr, mockWalletMgr, zmqPublishers, ) err := server.startListening(listener) require.NoError(t, err) return &testData{ TestSuite: ts, mockState: mockState, mockSync: mockSync, consMocks: consMocks, mockConsMgr: mockConsMgr, mockWalletMgr: mockWalletMgr, server: server, listener: listener, } } func (td *testData) StopServer() { td.server.StopServer() _ = td.listener.Close() } func (td *testData) bufDialer(context.Context, string) (net.Conn, error) { return td.listener.Dial() } func (td *testData) newClient(t *testing.T) *grpc.ClientConn { t.Helper() conn, err := grpc.NewClient("passthrough://bufnet", grpc.WithContextDialer(td.bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials())) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) td.StopServer() }) return conn } func (td *testData) blockchainClient(t *testing.T) pactus.BlockchainClient { t.Helper() return pactus.NewBlockchainClient(td.newClient(t)) } func (td *testData) networkClient(t *testing.T) pactus.NetworkClient { t.Helper() return pactus.NewNetworkClient(td.newClient(t)) } func (td *testData) transactionClient(t *testing.T) pactus.TransactionClient { t.Helper() return pactus.NewTransactionClient(td.newClient(t)) } func (td *testData) walletClient(t *testing.T) pactus.WalletClient { t.Helper() return pactus.NewWalletClient(td.newClient(t)) } func (td *testData) utilClient(t *testing.T) pactus.UtilsClient { t.Helper() return pactus.NewUtilsClient(td.newClient(t)) } ================================================ FILE: www/grpc/transaction.go ================================================ package grpc import ( "context" "encoding/hex" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util/logger" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type transactionServer struct { *Server } func newTransactionServer(server *Server) *transactionServer { return &transactionServer{ Server: server, } } func (s *transactionServer) GetTransaction(_ context.Context, req *pactus.GetTransactionRequest, ) (*pactus.GetTransactionResponse, error) { id, err := hash.FromString(req.Id) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid transaction ID: %v", err.Error()) } committedTx, err := s.state.CommittedTx(id) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "transaction not found") } res := &pactus.GetTransactionResponse{ BlockHeight: uint32(committedTx.Height), BlockTime: committedTx.BlockTime, } switch req.Verbosity { case pactus.TransactionVerbosity_TRANSACTION_VERBOSITY_DATA: res.Transaction = &pactus.TransactionInfo{ Id: committedTx.TxID.String(), Data: hex.EncodeToString(committedTx.Data), } case pactus.TransactionVerbosity_TRANSACTION_VERBOSITY_INFO: trx, err := committedTx.ToTx() if err != nil { return nil, status.Errorf(codes.Internal, "%s", err.Error()) } lastBlockHeight := s.state.LastBlockHeight() confirmations := int(lastBlockHeight) - int(committedTx.Height) res.Transaction = transactionToProto(trx, committedTx.Height, confirmations) } return res, nil } func (s *transactionServer) BroadcastTransaction(_ context.Context, req *pactus.BroadcastTransactionRequest, ) (*pactus.BroadcastTransactionResponse, error) { trx, err := tx.FromString(req.SignedRawTransaction) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "couldn't decode transaction: %v", err.Error()) } if err := s.state.AddPendingTxAndBroadcast(trx); err != nil { return nil, status.Errorf(codes.Canceled, "couldn't add to transaction pool: %v", err.Error()) } return &pactus.BroadcastTransactionResponse{ Id: trx.ID().String(), }, nil } func (s *transactionServer) CalculateFee(_ context.Context, req *pactus.CalculateFeeRequest, ) (*pactus.CalculateFeeResponse, error) { amt := amount.Amount(req.Amount) fee := s.state.CalculateFee(amt, payload.Type(req.PayloadType)) if req.FixedAmount { amt -= fee } return &pactus.CalculateFeeResponse{ Amount: amt.ToNanoPAC(), Fee: fee.ToNanoPAC(), }, nil } func (s *transactionServer) GetRawTransferTransaction(_ context.Context, req *pactus.GetRawTransferTransactionRequest, ) (*pactus.GetRawTransactionResponse, error) { sender, err := crypto.AddressFromString(req.Sender) if err != nil { return nil, err } receiver, err := crypto.AddressFromString(req.Receiver) if err != nil { return nil, err } amt := amount.Amount(req.Amount) fee := s.getFee(req.Fee, amt) lockTime := s.getLockTime(req.LockTime) transferTx := tx.NewTransferTx(lockTime, sender, receiver, amt, fee, tx.WithMemo(req.Memo)) rawTx, err := transferTx.Bytes() if err != nil { return nil, err } return &pactus.GetRawTransactionResponse{ RawTransaction: hex.EncodeToString(rawTx), }, nil } func (s *transactionServer) GetRawBondTransaction(_ context.Context, req *pactus.GetRawBondTransactionRequest, ) (*pactus.GetRawTransactionResponse, error) { sender, err := crypto.AddressFromString(req.Sender) if err != nil { return nil, err } receiver, err := crypto.AddressFromString(req.Receiver) if err != nil { return nil, err } var publicKey *bls.PublicKey if req.PublicKey != "" { publicKey, err = bls.PublicKeyFromString(req.PublicKey) if err != nil { return nil, err } } else { publicKey = nil } amt := amount.Amount(req.Stake) fee := s.getFee(req.Fee, amt) lockTime := s.getLockTime(req.LockTime) bondTx := tx.NewBondTx(lockTime, sender, receiver, publicKey, amt, fee, tx.WithMemo(req.Memo)) if req.DelegateOwner != "" { delegateOwner, err := crypto.AddressFromString(req.DelegateOwner) if err != nil { return nil, err } bondPld := bondTx.Payload().(*payload.BondPayload) bondPld.DelegateOwner = delegateOwner bondPld.DelegateShare = amount.Amount(req.DelegateShare) bondPld.DelegateExpiry = types.Height(req.DelegateExpiry) } rawTx, err := bondTx.Bytes() if err != nil { return nil, err } return &pactus.GetRawTransactionResponse{ RawTransaction: hex.EncodeToString(rawTx), }, nil } func (s *transactionServer) GetRawUnbondTransaction(_ context.Context, req *pactus.GetRawUnbondTransactionRequest, ) (*pactus.GetRawTransactionResponse, error) { validatorAddr, err := crypto.AddressFromString(req.ValidatorAddress) if err != nil { return nil, err } lockTime := s.getLockTime(req.LockTime) unbondTx := tx.NewUnbondTx(lockTime, validatorAddr, tx.WithMemo(req.Memo)) if req.DelegateOwner != "" { delegateOwner, err := crypto.AddressFromString(req.DelegateOwner) if err != nil { return nil, err } unbondPld := unbondTx.Payload().(*payload.UnbondPayload) unbondPld.DelegateOwner = delegateOwner } rawTx, err := unbondTx.Bytes() if err != nil { return nil, err } return &pactus.GetRawTransactionResponse{ RawTransaction: hex.EncodeToString(rawTx), }, nil } func (s *transactionServer) GetRawWithdrawTransaction(_ context.Context, req *pactus.GetRawWithdrawTransactionRequest, ) (*pactus.GetRawTransactionResponse, error) { validatorAddr, err := crypto.AddressFromString(req.ValidatorAddress) if err != nil { return nil, err } accountAddr, err := crypto.AddressFromString(req.AccountAddress) if err != nil { return nil, err } amt := amount.Amount(req.Amount) fee := s.getFee(req.Fee, amt) lockTime := s.getLockTime(req.LockTime) withdrawTx := tx.NewWithdrawTx(lockTime, validatorAddr, accountAddr, amt, fee, tx.WithMemo(req.Memo)) rawTx, err := withdrawTx.Bytes() if err != nil { return nil, err } return &pactus.GetRawTransactionResponse{ RawTransaction: hex.EncodeToString(rawTx), }, nil } func (s *transactionServer) GetRawBatchTransferTransaction(_ context.Context, req *pactus.GetRawBatchTransferTransactionRequest, ) (*pactus.GetRawTransactionResponse, error) { sender, err := crypto.AddressFromString(req.Sender) if err != nil { return nil, err } totalAmount := amount.Amount(0) recipients := make([]payload.BatchRecipient, 0, len(req.Recipients)) for _, recipient := range req.Recipients { receiver, err := crypto.AddressFromString(recipient.Receiver) if err != nil { return nil, err } amt := amount.Amount(recipient.Amount) recipients = append(recipients, payload.BatchRecipient{ To: receiver, Amount: amt, }) totalAmount += amt } fee := s.getFee(req.Fee, totalAmount) lockTime := s.getLockTime(req.LockTime) batchTransferTx := tx.NewBatchTransferTx(lockTime, sender, recipients, fee, tx.WithMemo(req.Memo)) rawTx, err := batchTransferTx.Bytes() if err != nil { return nil, err } return &pactus.GetRawTransactionResponse{ RawTransaction: hex.EncodeToString(rawTx), }, nil } func (s *transactionServer) getFee(f int64, amt amount.Amount) amount.Amount { fee := amount.Amount(f) if fee == 0 { fee = s.state.CalculateFee(amt, payload.TypeTransfer) } return fee } func (s *transactionServer) getLockTime(lockTime uint32) types.Height { if lockTime == 0 { return s.state.LastBlockHeight() } return types.Height(lockTime) } func transactionToProto(trx *tx.Tx, blockHeight types.Height, confirmations int) *pactus.TransactionInfo { trxInfo := &pactus.TransactionInfo{ Id: trx.ID().String(), Version: int32(trx.Version()), LockTime: uint32(trx.LockTime()), Fee: trx.Fee().ToNanoPAC(), Value: trx.Payload().Value().ToNanoPAC(), PayloadType: pactus.PayloadType(trx.Payload().Type()), Memo: trx.Memo(), BlockHeight: uint32(blockHeight), Confirmed: confirmations > 0, Confirmations: int32(confirmations), } if trx.PublicKey() != nil { trxInfo.PublicKey = trx.PublicKey().String() } if trx.Signature() != nil { trxInfo.Signature = trx.Signature().String() } switch trx.Payload().Type() { case payload.TypeTransfer: pld := trx.Payload().(*payload.TransferPayload) trxInfo.Payload = &pactus.TransactionInfo_Transfer{ Transfer: &pactus.PayloadTransfer{ Sender: pld.From.String(), Receiver: pld.To.String(), Amount: pld.Amount.ToNanoPAC(), }, } case payload.TypeBond: pld := trx.Payload().(*payload.BondPayload) publicKeyStr := "" if pld.PublicKey != nil { publicKeyStr = pld.PublicKey.String() } payload := &pactus.TransactionInfo_Bond{ Bond: &pactus.PayloadBond{ Sender: pld.From.String(), Receiver: pld.To.String(), Stake: pld.Stake.ToNanoPAC(), PublicKey: publicKeyStr, }, } // TODO: Cover me with tests if pld.IsDelegated() { payload.Bond.IsDelegated = true payload.Bond.DelegateOwner = pld.DelegateOwner.String() payload.Bond.DelegateShare = pld.DelegateShare.ToNanoPAC() payload.Bond.DelegateExpiry = uint32(pld.DelegateExpiry) } trxInfo.Payload = payload case payload.TypeSortition: pld := trx.Payload().(*payload.SortitionPayload) trxInfo.Payload = &pactus.TransactionInfo_Sortition{ Sortition: &pactus.PayloadSortition{ Address: pld.Validator.String(), Proof: hex.EncodeToString(pld.Proof[:]), }, } case payload.TypeUnbond: pld := trx.Payload().(*payload.UnbondPayload) payload := &pactus.TransactionInfo_Unbond{ Unbond: &pactus.PayloadUnbond{ Validator: pld.Validator.String(), }, } // TODO: Cover me with tests if pld.IsDelegated() { payload.Unbond.DelegateOwner = pld.DelegateOwner.String() } trxInfo.Payload = payload case payload.TypeWithdraw: pld := trx.Payload().(*payload.WithdrawPayload) trxInfo.Payload = &pactus.TransactionInfo_Withdraw{ Withdraw: &pactus.PayloadWithdraw{ ValidatorAddress: pld.From.String(), AccountAddress: pld.To.String(), Amount: pld.Amount.ToNanoPAC(), }, } case payload.TypeBatchTransfer: pld := trx.Payload().(*payload.BatchTransferPayload) recipients := make([]*pactus.Recipient, 0, len(pld.Recipients)) for _, recipient := range pld.Recipients { recipients = append(recipients, &pactus.Recipient{ Receiver: recipient.To.String(), Amount: recipient.Amount.ToNanoPAC(), }) } trxInfo.Payload = &pactus.TransactionInfo_BatchTransfer{ BatchTransfer: &pactus.PayloadBatchTransfer{ Sender: pld.From.String(), Recipients: recipients, }, } default: logger.Error("payload type not defined", "type", trx.Payload().Type()) } return trxInfo } func (*transactionServer) DecodeRawTransaction(_ context.Context, req *pactus.DecodeRawTransactionRequest, ) (*pactus.DecodeRawTransactionResponse, error) { trx, err := tx.FromString(req.RawTransaction) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "couldn't decode transaction: %v", err.Error()) } return &pactus.DecodeRawTransactionResponse{ Transaction: transactionToProto(trx, 0, 0), }, nil } func (s *transactionServer) CheckTransaction(_ context.Context, req *pactus.CheckTransactionRequest, ) (*pactus.CheckTransactionResponse, error) { trx, err := tx.FromString(req.RawTransaction) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "couldn't decode transaction: %v", err.Error()) } err = s.state.CheckTransaction(trx) if err != nil { return &pactus.CheckTransactionResponse{ IsValid: false, ErrorMessage: err.Error(), }, status.Errorf(codes.InvalidArgument, "couldn't decode transaction: %v", err.Error()) } return &pactus.CheckTransactionResponse{ IsValid: true, }, nil } ================================================ FILE: www/grpc/transaction_test.go ================================================ package grpc import ( "encoding/hex" "errors" "testing" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/tx" "github.com/pactus-project/pactus/types/tx/payload" "github.com/pactus-project/pactus/util/testsuite" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) func TestGetTransaction(t *testing.T) { td := setup(t, nil) client := td.transactionClient(t) blockHeight := td.RandHeight() valPubKey, _ := td.RandBLSKeyPair() textTrx := td.GenerateTestBondTx( testsuite.TransactionWithValidatorPublicKey(valPubKey)) testBlock, testCert := td.GenerateTestBlock(blockHeight, testsuite.BlockWithTransactions([]*tx.Tx{textTrx})) td.mockState.TestStore.SaveBlock(testBlock, testCert) t.Run("Should return transaction (verbosity: 0)", func(t *testing.T) { res, err := client.GetTransaction(t.Context(), &pactus.GetTransactionRequest{ Id: textTrx.ID().String(), Verbosity: pactus.TransactionVerbosity_TRANSACTION_VERBOSITY_DATA, }) require.NoError(t, err) assert.NotNil(t, res) assert.NotEmpty(t, res.Transaction) assert.Equal(t, uint32(blockHeight), res.BlockHeight) assert.Equal(t, textTrx.ID().String(), res.Transaction.Id) b, err := textTrx.Bytes() require.NoError(t, err) assert.Equal(t, hex.EncodeToString(b), res.Transaction.Data) assert.Nil(t, res.Transaction.Payload) }) t.Run("Should return transaction (verbosity: 1)", func(t *testing.T) { res, err := client.GetTransaction(t.Context(), &pactus.GetTransactionRequest{ Id: textTrx.ID().String(), Verbosity: pactus.TransactionVerbosity_TRANSACTION_VERBOSITY_INFO, }) pld := res.Transaction.Payload.(*pactus.TransactionInfo_Bond) require.NoError(t, err) assert.NotNil(t, res) assert.NotEmpty(t, res.Transaction) assert.Empty(t, res.Transaction.Data) assert.Equal(t, uint32(blockHeight), res.BlockHeight) assert.Equal(t, testBlock.Header().UnixTime(), res.BlockTime) assert.Equal(t, textTrx.ID().String(), res.Transaction.Id) assert.Equal(t, textTrx.Fee().ToNanoPAC(), res.Transaction.Fee) assert.Equal(t, textTrx.Memo(), res.Transaction.Memo) assert.Equal(t, textTrx.Payload().Type(), payload.Type(res.Transaction.PayloadType)) assert.Equal(t, uint32(textTrx.LockTime()), res.Transaction.LockTime) assert.Equal(t, textTrx.Signature().String(), res.Transaction.Signature) assert.Equal(t, textTrx.PublicKey().String(), res.Transaction.PublicKey) assert.Equal(t, textTrx.Payload().(*payload.BondPayload).Stake.ToNanoPAC(), pld.Bond.Stake) assert.Equal(t, textTrx.Payload().(*payload.BondPayload).From.String(), pld.Bond.Sender) assert.Equal(t, textTrx.Payload().(*payload.BondPayload).To.String(), pld.Bond.Receiver) assert.Equal(t, textTrx.Payload().(*payload.BondPayload).PublicKey.String(), pld.Bond.PublicKey) }) t.Run("Should return nil value because transaction id is invalid", func(t *testing.T) { res, err := client.GetTransaction(t.Context(), &pactus.GetTransactionRequest{Id: "invalid_id"}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Should return nil value because transaction doesn't exist", func(t *testing.T) { id := td.RandHash() res, err := client.GetTransaction(t.Context(), &pactus.GetTransactionRequest{Id: id.String()}) require.Error(t, err) assert.Nil(t, res) }) } func TestSendRawTransaction(t *testing.T) { td := setup(t, nil) client := td.transactionClient(t) t.Run("Should fail, invalid cbor", func(t *testing.T) { res, err := client.BroadcastTransaction(t.Context(), &pactus.BroadcastTransactionRequest{SignedRawTransaction: "00000000"}) require.Error(t, err) assert.Nil(t, res) }) trx := td.GenerateTestTransferTx() data, _ := trx.Bytes() t.Run("Should pass", func(t *testing.T) { td.mockState.MockTxPool.EXPECT().AppendTxAndBroadcast(gomock.Any()).Return(nil).Times(1) res, err := client.BroadcastTransaction(t.Context(), &pactus.BroadcastTransactionRequest{SignedRawTransaction: hex.EncodeToString(data)}) require.NoError(t, err) assert.NotNil(t, res) }) t.Run("Should fail and not broadcast", func(t *testing.T) { td.mockState.MockTxPool.EXPECT().AppendTxAndBroadcast(gomock.Any()).Return(errors.New("some error")).Times(1) res, err := client.BroadcastTransaction(t.Context(), &pactus.BroadcastTransactionRequest{SignedRawTransaction: hex.EncodeToString(data)}) require.Error(t, err) assert.Nil(t, res) }) } func TestGetRawTransaction(t *testing.T) { td := setup(t, nil) client := td.transactionClient(t) td.mockState.MockTxPool.EXPECT().EstimatedFee(gomock.Any(), gomock.Any()).Return(td.RandFee()).AnyTimes() t.Run("Transfer", func(t *testing.T) { amt := td.RandAmount() res, err := client.GetRawTransferTransaction(t.Context(), &pactus.GetRawTransferTransactionRequest{ Sender: td.RandAccAddress().String(), Receiver: td.RandAccAddress().String(), Amount: amt.ToNanoPAC(), Memo: td.RandString(32), }) require.NoError(t, err) assert.NotEmpty(t, res.RawTransaction) decodedTrx, err := tx.FromString(res.RawTransaction) require.NoError(t, err) expectedLockTime := td.mockState.LastBlockHeight() expectedFee := td.mockState.CalculateFee(amt, payload.TypeTransfer) assert.Equal(t, amt, decodedTrx.Payload().Value()) assert.Equal(t, expectedLockTime, decodedTrx.LockTime()) assert.Equal(t, expectedFee, decodedTrx.Fee()) }) t.Run("Batch Transfer", func(t *testing.T) { amt1 := td.RandAmount() amt2 := td.RandAmount() totalAmt := amt1 + amt2 res, err := client.GetRawBatchTransferTransaction(t.Context(), &pactus.GetRawBatchTransferTransactionRequest{ Sender: td.RandAccAddress().String(), Recipients: []*pactus.Recipient{ { Receiver: td.RandAccAddress().String(), Amount: amt1.ToNanoPAC(), }, { Receiver: td.RandAccAddress().String(), Amount: amt2.ToNanoPAC(), }, }, Memo: td.RandString(32), }, ) require.NoError(t, err) assert.NotEmpty(t, res.RawTransaction) decodedTrx, err := tx.FromString(res.RawTransaction) require.NoError(t, err) expectedLockTime := td.mockState.LastBlockHeight() expectedFee := td.mockState.CalculateFee(totalAmt, payload.TypeBatchTransfer) assert.Equal(t, totalAmt, decodedTrx.Payload().Value()) assert.Equal(t, expectedLockTime, decodedTrx.LockTime()) assert.Equal(t, expectedFee, decodedTrx.Fee()) }) t.Run("Bond with the Public Key", func(t *testing.T) { amt := td.RandAmount() pub, _ := td.RandBLSKeyPair() res, err := client.GetRawBondTransaction(t.Context(), &pactus.GetRawBondTransactionRequest{ Sender: td.RandAccAddress().String(), Receiver: td.RandValAddress().String(), Stake: amt.ToNanoPAC(), PublicKey: pub.String(), Memo: td.RandString(32), }) require.NoError(t, err) assert.NotEmpty(t, res.RawTransaction) decodedTrx, err := tx.FromString(res.RawTransaction) require.NoError(t, err) expectedLockTime := td.mockState.LastBlockHeight() expectedFee := td.mockState.CalculateFee(amt, payload.TypeBond) assert.Equal(t, amt, decodedTrx.Payload().Value()) assert.Equal(t, expectedLockTime, decodedTrx.LockTime()) assert.Equal(t, expectedFee, decodedTrx.Fee()) }) t.Run("Bond without the Public Key", func(t *testing.T) { amt := td.RandAmount() res, err := client.GetRawBondTransaction(t.Context(), &pactus.GetRawBondTransactionRequest{ Sender: td.RandAccAddress().String(), Receiver: td.RandValAddress().String(), Stake: amt.ToNanoPAC(), Memo: td.RandString(32), }) require.NoError(t, err) assert.NotEmpty(t, res.RawTransaction) decodedTrx, err := tx.FromString(res.RawTransaction) require.NoError(t, err) expectedLockTime := td.mockState.LastBlockHeight() expectedFee := td.mockState.CalculateFee(amt, payload.TypeBond) assert.Equal(t, amt, decodedTrx.Payload().Value()) assert.Equal(t, expectedLockTime, decodedTrx.LockTime()) assert.Equal(t, expectedFee, decodedTrx.Fee()) }) t.Run("Unbond", func(t *testing.T) { res, err := client.GetRawUnbondTransaction(t.Context(), &pactus.GetRawUnbondTransactionRequest{ ValidatorAddress: td.RandValAddress().String(), Memo: td.RandString(32), }) require.NoError(t, err) assert.NotEmpty(t, res.RawTransaction) decodedTrx, err := tx.FromString(res.RawTransaction) require.NoError(t, err) expectedLockTime := td.mockState.LastBlockHeight() assert.Zero(t, decodedTrx.Payload().Value()) assert.Equal(t, expectedLockTime, decodedTrx.LockTime()) assert.Zero(t, decodedTrx.Fee()) }) t.Run("Withdraw", func(t *testing.T) { amt := td.RandAmount() res, err := client.GetRawWithdrawTransaction(t.Context(), &pactus.GetRawWithdrawTransactionRequest{ ValidatorAddress: td.RandValAddress().String(), AccountAddress: td.RandAccAddress().String(), Amount: amt.ToNanoPAC(), Memo: td.RandString(32), }) require.NoError(t, err) assert.NotEmpty(t, res.RawTransaction) decodedTrx, err := tx.FromString(res.RawTransaction) require.NoError(t, err) expectedLockTime := td.mockState.LastBlockHeight() expectedFee := td.mockState.CalculateFee(amt, payload.TypeWithdraw) assert.Equal(t, amt, decodedTrx.Payload().Value()) assert.Equal(t, expectedLockTime, decodedTrx.LockTime()) assert.Equal(t, expectedFee, decodedTrx.Fee()) }) } func TestCalculateFee(t *testing.T) { td := setup(t, nil) client := td.transactionClient(t) expectedFee := td.RandFee() td.mockState.MockTxPool.EXPECT().EstimatedFee(gomock.Any(), gomock.Any()).Return(expectedFee).AnyTimes() t.Run("Not fixed amount", func(t *testing.T) { amt := td.RandAmount() res, err := client.CalculateFee(t.Context(), &pactus.CalculateFeeRequest{ Amount: amt.ToNanoPAC(), PayloadType: pactus.PayloadType_PAYLOAD_TYPE_TRANSFER, FixedAmount: false, }) require.NoError(t, err) assert.Equal(t, amt.ToNanoPAC(), res.Amount) assert.Equal(t, expectedFee.ToNanoPAC(), res.Fee) }) t.Run("Fixed amount", func(t *testing.T) { amt := td.RandAmount() res, err := client.CalculateFee(t.Context(), &pactus.CalculateFeeRequest{ Amount: amt.ToNanoPAC(), PayloadType: pactus.PayloadType_PAYLOAD_TYPE_TRANSFER, FixedAmount: true, }) require.NoError(t, err) assert.Equal(t, (amt - expectedFee).ToNanoPAC(), res.Amount) assert.Equal(t, expectedFee.ToNanoPAC(), res.Fee) }) t.Run("Insufficient amount to pay fee", func(t *testing.T) { amt := amount.Amount(0) res, err := client.CalculateFee(t.Context(), &pactus.CalculateFeeRequest{ Amount: amt.ToNanoPAC(), PayloadType: pactus.PayloadType_PAYLOAD_TYPE_TRANSFER, FixedAmount: true, }) require.NoError(t, err) assert.Negative(t, res.Amount) assert.Equal(t, expectedFee.ToNanoPAC(), res.Fee) }) } func TestDecodeRawTransaction(t *testing.T) { td := setup(t, nil) client := td.transactionClient(t) t.Run("Should decode valid raw transaction", func(t *testing.T) { trx := td.GenerateTestTransferTx() data, _ := trx.Bytes() res, err := client.DecodeRawTransaction(t.Context(), &pactus.DecodeRawTransactionRequest{RawTransaction: hex.EncodeToString(data)}) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, trx.ID().String(), res.Transaction.Id) assert.Equal(t, trx.Fee().ToNanoPAC(), res.Transaction.Fee) assert.Equal(t, trx.Memo(), res.Transaction.Memo) assert.Equal(t, trx.Payload().Type(), payload.Type(res.Transaction.PayloadType)) assert.Equal(t, uint32(trx.LockTime()), res.Transaction.LockTime) assert.Equal(t, trx.Signature().String(), res.Transaction.Signature) assert.Equal(t, trx.PublicKey().String(), res.Transaction.PublicKey) }) t.Run("Should fail to decode invalid raw transaction", func(t *testing.T) { res, err := client.DecodeRawTransaction(t.Context(), &pactus.DecodeRawTransactionRequest{RawTransaction: "invalid_raw_transaction"}) require.Error(t, err) assert.Nil(t, res) }) } ================================================ FILE: www/grpc/utils.go ================================================ package grpc import ( "context" "errors" "fmt" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/crypto/ed25519" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type utilServer struct { *Server } func newUtilsServer(server *Server) *utilServer { return &utilServer{ Server: server, } } func (u *utilServer) SignMessageWithPrivateKey(_ context.Context, req *pactus.SignMessageWithPrivateKeyRequest, ) (*pactus.SignMessageWithPrivateKeyResponse, error) { prvKey, err := u.privateKeyFromString(req.PrivateKey) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } sig := prvKey.Sign([]byte(req.Message)).String() return &pactus.SignMessageWithPrivateKeyResponse{ Signature: sig, }, nil } func (u *utilServer) VerifyMessage(_ context.Context, req *pactus.VerifyMessageRequest, ) (*pactus.VerifyMessageResponse, error) { pubKey, sig, err := u.publicKeyAndSigFromString(req.PublicKey, req.Signature) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } if err = pubKey.Verify([]byte(req.Message), sig); err == nil { return &pactus.VerifyMessageResponse{ IsValid: true, }, nil } return &pactus.VerifyMessageResponse{ IsValid: false, }, nil } func (*utilServer) PublicKeyAggregation(_ context.Context, req *pactus.PublicKeyAggregationRequest, ) (*pactus.PublicKeyAggregationResponse, error) { pubs := make([]*bls.PublicKey, len(req.PublicKeys)) for i, pubKey := range req.PublicKeys { p, err := bls.PublicKeyFromString(pubKey) if err != nil { return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("invalid public key %s", pubKey)) } pubs[i] = p } aggPub, err := bls.PublicKeyAggregate(pubs...) if err != nil { return nil, err } return &pactus.PublicKeyAggregationResponse{ PublicKey: aggPub.String(), Address: aggPub.AccountAddress().String(), }, nil } func (*utilServer) SignatureAggregation(_ context.Context, req *pactus.SignatureAggregationRequest, ) (*pactus.SignatureAggregationResponse, error) { sigs := make([]*bls.Signature, len(req.Signatures)) for i, sig := range req.Signatures { s, err := bls.SignatureFromString(sig) if err != nil { return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("invalid signature %s", sig)) } sigs[i] = s } aggSig, err := bls.SignatureAggregate(sigs...) if err != nil { return nil, err } return &pactus.SignatureAggregationResponse{ Signature: aggSig.String(), }, nil } func (*utilServer) privateKeyFromString(prvStr string) (crypto.PrivateKey, error) { blsPrv, err := bls.PrivateKeyFromString(prvStr) if err == nil { return blsPrv, nil } ed25519Prv, err := ed25519.PrivateKeyFromString(prvStr) if err == nil { return ed25519Prv, nil } return nil, errors.New("invalid Private Key") } func (*utilServer) publicKeyAndSigFromString(pubStr, sigStr string) (crypto.PublicKey, crypto.Signature, error) { blsPub, err := bls.PublicKeyFromString(pubStr) if err == nil { blsSig, err := bls.SignatureFromString(sigStr) if err != nil { return nil, nil, errors.New("invalid BLS signature") } return blsPub, blsSig, nil } ed25519Pub, err := ed25519.PublicKeyFromString(pubStr) if err == nil { ed25519Sig, err := ed25519.SignatureFromString(sigStr) if err != nil { return nil, nil, errors.New("invalid Ed25519 signature") } return ed25519Pub, ed25519Sig, nil } return nil, nil, errors.New("invalid Public Key") } ================================================ FILE: www/grpc/utils_test.go ================================================ package grpc import ( "testing" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/util/testsuite" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSignMessageWithPrivateKey(t *testing.T) { conf := testConfig() td := setup(t, conf) client := td.utilClient(t) msg := "pactus" prvStr := "SECRET1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQQJVK67" invalidPrvStr := "INVSECRET1PDRWTLP5PX0FAHDX39GXZJP7FKZFALML0D5U9TT9KVQHDUC99CMGQQJVK67" expectedSig := "923d67a8624cbb7972b29328e15ec76cc846076ccf00a9e94d991c677846f334ae4ba4551396fbcd6d1cab7593baf3b7" t.Run("", func(t *testing.T) { res, err := client.SignMessageWithPrivateKey(t.Context(), &pactus.SignMessageWithPrivateKeyRequest{ Message: msg, PrivateKey: prvStr, }) require.NoError(t, err) assert.Equal(t, expectedSig, res.Signature) }) t.Run("", func(t *testing.T) { res, err := client.SignMessageWithPrivateKey(t.Context(), &pactus.SignMessageWithPrivateKeyRequest{ Message: msg, PrivateKey: invalidPrvStr, }) require.Error(t, err) assert.Nil(t, res) }) } func TestSignMessageWithED25519PrivateKey(t *testing.T) { conf := testConfig() td := setup(t, conf) client := td.utilClient(t) msg := "pactus" prvStr := "SECRET1RYY62A96X25ZAL4DPL5Z63G83GCSFCCQ7K0CMQD3MFNLYK3A6R26QUUK3Y0" invalidPrvStr := "INVSECRET1RYY62A96X25ZAL4DPL5Z63G83GCSFCCQ7K0CMQD3MFNLYK3A6R26QUUK3Y0" expectedSig := "361aaa09c408bfcf7e79dd90c583eeeaefe7c732ca5643cfb2ea7a6d22105b874a412080" + "525a855bbd5df94110a7d0083d6e386e016ecf8b7f522c339f79d305" t.Run("", func(t *testing.T) { res, err := client.SignMessageWithPrivateKey(t.Context(), &pactus.SignMessageWithPrivateKeyRequest{ Message: msg, PrivateKey: prvStr, }) require.NoError(t, err) assert.Equal(t, expectedSig, res.Signature) }) t.Run("", func(t *testing.T) { res, err := client.SignMessageWithPrivateKey(t.Context(), &pactus.SignMessageWithPrivateKeyRequest{ Message: msg, PrivateKey: invalidPrvStr, }) require.Error(t, err) assert.Nil(t, res) }) } func TestVerifyMessage(t *testing.T) { conf := testConfig() td := setup(t, conf) client := td.utilClient(t) msg := "pactus" pubStr := "public1p4u8hfytl2pj6l9rj0t54gxcdmna4hq52ncqkkqjf3arha5mlk3x4mzpyjkhmdl20jae7f65aamjr" + "vqcvf4sudcapz52ctcwc8r9wz3z2gwxs38880cgvfy49ta5ssyjut05myd4zgmjqstggmetyuyg7v5jhx47a" sigStr := "923d67a8624cbb7972b29328e15ec76cc846076ccf00a9e94d991c677846f334ae4ba4551396fbcd6d1cab7593baf3b7" invalidSigStr := "113d67a8624cbb7972b29328e15ec76cc846076ccf00a9e94d991c677846f334ae4ba4551396fbcd6d1cab7593baf3c9" t.Run("valid message", func(t *testing.T) { res, err := client.VerifyMessage(t.Context(), &pactus.VerifyMessageRequest{ Message: msg, Signature: sigStr, PublicKey: pubStr, }) require.NoError(t, err) assert.True(t, res.IsValid) }) t.Run("invalid message", func(t *testing.T) { res, err := client.VerifyMessage(t.Context(), &pactus.VerifyMessageRequest{ Message: msg, Signature: invalidSigStr, PublicKey: pubStr, }) require.NoError(t, err) assert.False(t, res.IsValid) }) } func TestVerifyED25519Message(t *testing.T) { conf := testConfig() td := setup(t, conf) client := td.utilClient(t) msg := "pactus" pubStr := "public1rvqxnpfph8tnc3ck55z85w285t5jetylmmktr9wlzs0zvx7kx500szxfudh" sigStr := "361aaa09c408bfcf7e79dd90c583eeeaefe7c732ca5643cfb2ea7a6d22105b874a41" + "2080525a855bbd5df94110a7d0083d6e386e016ecf8b7f522c339f79d305" invalidSigStr := "001aaa09c408bfcf7e79dd90c583eeeaefe7c732ca5643cfb2ea7a6d22105b" + "874a412080525a855bbd5df94110a7d0083d6e386e016ecf8b7f522c339f79d305" t.Run("valid message", func(t *testing.T) { res, err := client.VerifyMessage(t.Context(), &pactus.VerifyMessageRequest{ Message: msg, Signature: sigStr, PublicKey: pubStr, }) require.NoError(t, err) assert.True(t, res.IsValid) }) t.Run("invalid message", func(t *testing.T) { res, err := client.VerifyMessage(t.Context(), &pactus.VerifyMessageRequest{ Message: msg, Signature: invalidSigStr, PublicKey: pubStr, }) require.NoError(t, err) assert.False(t, res.IsValid) }) } func TestPublicKeyAggregation(t *testing.T) { ts := testsuite.NewTestSuite(t) conf := testConfig() td := setup(t, conf) client := td.utilClient(t) pub1, _ := ts.RandBLSKeyPair() pub2, _ := ts.RandBLSKeyPair() pub3, _ := ts.RandBLSKeyPair() aggPub, _ := bls.PublicKeyAggregate(pub1, pub2, pub3) invalidPub := "invalidpub" t.Run("no public keys", func(t *testing.T) { res, err := client.PublicKeyAggregation(t.Context(), &pactus.PublicKeyAggregationRequest{ PublicKeys: []string{}, }) require.Error(t, err) assert.Nil(t, res) }) t.Run("only one public key", func(t *testing.T) { res, err := client.PublicKeyAggregation(t.Context(), &pactus.PublicKeyAggregationRequest{ PublicKeys: []string{pub1.String()}, }) require.NoError(t, err) assert.Equal(t, pub1.String(), res.PublicKey) }) t.Run("invalid public key", func(t *testing.T) { res, err := client.PublicKeyAggregation(t.Context(), &pactus.PublicKeyAggregationRequest{ PublicKeys: []string{pub1.String(), pub2.String(), invalidPub, pub3.String()}, }) require.Error(t, err) assert.Nil(t, res) }) t.Run("valid public keys", func(t *testing.T) { res, err := client.PublicKeyAggregation(t.Context(), &pactus.PublicKeyAggregationRequest{ PublicKeys: []string{pub1.String(), pub2.String(), pub3.String()}, }) require.NoError(t, err) assert.Equal(t, aggPub.String(), res.PublicKey) }) } func TestSignatureAggregation(t *testing.T) { ts := testsuite.NewTestSuite(t) conf := testConfig() td := setup(t, conf) client := td.utilClient(t) sig1 := ts.RandBLSSignature() sig2 := ts.RandBLSSignature() sig3 := ts.RandBLSSignature() aggSig, _ := bls.SignatureAggregate(sig1, sig2, sig3) invalidSig := "invalidsig" t.Run("no signatures", func(t *testing.T) { res, err := client.SignatureAggregation(t.Context(), &pactus.SignatureAggregationRequest{ Signatures: []string{}, }) require.Error(t, err) assert.Nil(t, res) }) t.Run("only one signature", func(t *testing.T) { res, err := client.SignatureAggregation(t.Context(), &pactus.SignatureAggregationRequest{ Signatures: []string{sig1.String()}, }) require.NoError(t, err) assert.Equal(t, sig1.String(), res.Signature) }) t.Run("invalid signature", func(t *testing.T) { res, err := client.SignatureAggregation(t.Context(), &pactus.SignatureAggregationRequest{ Signatures: []string{sig1.String(), sig2.String(), invalidSig, sig3.String()}, }) require.Error(t, err) assert.Nil(t, res) }) t.Run("valid signatures", func(t *testing.T) { res, err := client.SignatureAggregation(t.Context(), &pactus.SignatureAggregationRequest{ Signatures: []string{sig1.String(), sig2.String(), sig3.String()}, }) require.NoError(t, err) assert.Equal(t, aggSig.String(), res.Signature) }) } ================================================ FILE: www/grpc/wallet.go ================================================ package grpc import ( "context" "encoding/hex" "errors" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/wallet" wltmgr "github.com/pactus-project/pactus/wallet/manager" "github.com/pactus-project/pactus/wallet/types" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) type walletServer struct { *Server walletManager wltmgr.IManager } func newWalletServer(server *Server, manager wltmgr.IManager) *walletServer { return &walletServer{ Server: server, walletManager: manager, } } func (*walletServer) addressInfoToProto(ai *types.AddressInfo) *pactus.AddressInfo { return &pactus.AddressInfo{ Address: ai.Address, Label: ai.Label, PublicKey: ai.PublicKey, Path: ai.Path, } } func (s *walletServer) GetValidatorAddress(_ context.Context, req *pactus.GetValidatorAddressRequest, ) (*pactus.GetValidatorAddressResponse, error) { adr, err := s.walletManager.GetValidatorAddress(req.PublicKey) if err != nil { return nil, err } return &pactus.GetValidatorAddressResponse{ Address: adr, }, nil } func (s *walletServer) CreateWallet(_ context.Context, req *pactus.CreateWalletRequest, ) (*pactus.CreateWalletResponse, error) { if req.WalletName == "" { return nil, errors.New("wallet name is required") } mnemonic, err := s.walletManager.CreateWallet( req.WalletName, req.Password, ) if err != nil { return nil, err } return &pactus.CreateWalletResponse{ WalletName: req.WalletName, Mnemonic: mnemonic, }, nil } func (s *walletServer) RestoreWallet(_ context.Context, req *pactus.RestoreWalletRequest, ) (*pactus.RestoreWalletResponse, error) { if req.WalletName == "" { return nil, errors.New("wallet name is required") } if req.Mnemonic == "" { return nil, errors.New("mnemonic is required") } if err := s.walletManager.RestoreWallet( req.WalletName, req.Mnemonic, req.Password, ); err != nil { return nil, err } return &pactus.RestoreWalletResponse{ WalletName: req.WalletName, }, nil } func (*walletServer) LoadWallet(_ context.Context, req *pactus.LoadWalletRequest, ) (*pactus.LoadWalletResponse, error) { return &pactus.LoadWalletResponse{ WalletName: req.WalletName, }, nil } func (*walletServer) UnloadWallet(_ context.Context, req *pactus.UnloadWalletRequest, ) (*pactus.UnloadWalletResponse, error) { return &pactus.UnloadWalletResponse{ WalletName: req.WalletName, }, nil } func (s *walletServer) ListWallets(_ context.Context, _ *pactus.ListWalletsRequest, ) (*pactus.ListWalletsResponse, error) { wallets, err := s.walletManager.ListWallets() if err != nil { return nil, err } return &pactus.ListWalletsResponse{ Wallets: wallets, }, nil } func (s *walletServer) GetTotalBalance(_ context.Context, req *pactus.GetTotalBalanceRequest, ) (*pactus.GetTotalBalanceResponse, error) { balance, err := s.walletManager.TotalBalance(req.WalletName) if err != nil { return nil, err } return &pactus.GetTotalBalanceResponse{ WalletName: req.WalletName, TotalBalance: balance.ToNanoPAC(), }, nil } func (s *walletServer) GetTotalStake(_ context.Context, req *pactus.GetTotalStakeRequest, ) (*pactus.GetTotalStakeResponse, error) { stake, err := s.walletManager.TotalStake(req.WalletName) if err != nil { return nil, err } return &pactus.GetTotalStakeResponse{ TotalStake: stake.ToNanoPAC(), WalletName: req.WalletName, }, nil } func (s *walletServer) SignRawTransaction(_ context.Context, req *pactus.SignRawTransactionRequest, ) (*pactus.SignRawTransactionResponse, error) { rawBytes, err := hex.DecodeString(req.RawTransaction) if err != nil { return nil, err } txID, data, err := s.walletManager.SignRawTransaction( req.WalletName, req.Password, rawBytes, ) if err != nil { return nil, err } return &pactus.SignRawTransactionResponse{ TransactionId: hex.EncodeToString(txID), SignedRawTransaction: hex.EncodeToString(data), }, nil } func (s *walletServer) SignMessage(_ context.Context, req *pactus.SignMessageRequest, ) (*pactus.SignMessageResponse, error) { sig, err := s.walletManager.SignMessage(req.WalletName, req.Password, req.Address, req.Message) if err != nil { return nil, err } return &pactus.SignMessageResponse{ Signature: sig, }, nil } func (s *walletServer) GetNewAddress(_ context.Context, req *pactus.GetNewAddressRequest, ) (*pactus.GetNewAddressResponse, error) { info, err := s.walletManager.NewAddress( req.WalletName, crypto.AddressType(req.AddressType), req.Label, wallet.WithPassword(req.Password), ) if err != nil { return nil, err } return &pactus.GetNewAddressResponse{ WalletName: req.WalletName, Addr: s.addressInfoToProto(info), }, nil } func (s *walletServer) GetAddressInfo(_ context.Context, req *pactus.GetAddressInfoRequest, ) (*pactus.GetAddressInfoResponse, error) { info, err := s.walletManager.AddressInfo(req.WalletName, req.Address) if err != nil { return nil, err } return &pactus.GetAddressInfoResponse{ WalletName: req.WalletName, Addr: s.addressInfoToProto(info), }, nil } func (s *walletServer) SetAddressLabel(_ context.Context, req *pactus.SetAddressLabelRequest, ) (*pactus.SetAddressLabelResponse, error) { err := s.walletManager.SetAddressLabel(req.WalletName, req.Address, req.Label) if err != nil { return nil, err } return &pactus.SetAddressLabelResponse{ WalletName: req.WalletName, Address: req.Address, Label: req.Label, }, nil } func (s *walletServer) GetWalletInfo(_ context.Context, req *pactus.GetWalletInfoRequest, ) (*pactus.GetWalletInfoResponse, error) { info, err := s.walletManager.WalletInfo(req.WalletName) if err != nil { return nil, err } return &pactus.GetWalletInfoResponse{ WalletName: req.WalletName, Version: int32(info.Version), Network: info.Network.String(), Encrypted: info.Encrypted, Uuid: info.UUID, CreatedAt: info.CreatedAt.Unix(), DefaultFee: info.DefaultFee.ToNanoPAC(), Driver: info.Driver, Path: info.Path, }, nil } func (s *walletServer) ListAddresses(_ context.Context, req *pactus.ListAddressesRequest, ) (*pactus.ListAddressesResponse, error) { addressTypes := make([]crypto.AddressType, 0, len(req.AddressTypes)) for _, addrType := range req.AddressTypes { addressTypes = append(addressTypes, crypto.AddressType(addrType)) } addrs, err := s.walletManager.ListAddresses(req.WalletName, wallet.WithAddressTypes(addressTypes)) if err != nil { return nil, err } addrsPB := make([]*pactus.AddressInfo, 0, len(addrs)) for _, info := range addrs { addrsPB = append(addrsPB, s.addressInfoToProto(&info)) } return &pactus.ListAddressesResponse{ WalletName: req.WalletName, Addrs: addrsPB, }, nil } func (s *walletServer) ListTransactions(_ context.Context, req *pactus.ListTransactionsRequest, ) (*pactus.ListTransactionsResponse, error) { infos, err := s.walletManager.ListTransactions(req.WalletName, wallet.WithDirection(types.TxDirection(req.Direction)), wallet.WithAddress(req.Address), wallet.WithCount(int(req.Count)), wallet.WithSkip(int(req.Skip))) if err != nil { return nil, err } trxs := make([]*pactus.WalletTransactionInfo, 0, len(infos)) for _, info := range infos { trxs = append(trxs, &pactus.WalletTransactionInfo{ No: info.No, TxId: info.TxID, Sender: info.Sender, Receiver: info.Receiver, Direction: pactus.TxDirection(info.Direction), Amount: info.Amount.ToNanoPAC(), Fee: info.Fee.ToNanoPAC(), Memo: info.Memo, Status: pactus.TransactionStatus(info.Status), BlockHeight: uint32(info.BlockHeight), PayloadType: pactus.PayloadType(info.PayloadType), Data: info.Data, Comment: info.Comment, CreatedAt: info.CreatedAt.Unix(), UpdatedAt: info.UpdatedAt.Unix(), }) } return &pactus.ListTransactionsResponse{ WalletName: req.WalletName, Txs: trxs, }, nil } func (s *walletServer) UpdatePassword(_ context.Context, req *pactus.UpdatePasswordRequest, ) (*pactus.UpdatePasswordResponse, error) { err := s.walletManager.UpdatePassword(req.WalletName, req.OldPassword, req.NewPassword) if err != nil { return nil, err } return &pactus.UpdatePasswordResponse{ WalletName: req.WalletName, }, nil } func (s *walletServer) SetDefaultFee(_ context.Context, req *pactus.SetDefaultFeeRequest, ) (*pactus.SetDefaultFeeResponse, error) { err := s.walletManager.SetDefaultFee(req.WalletName, amount.Amount(req.Amount)) if err != nil { return nil, err } return &pactus.SetDefaultFeeResponse{ WalletName: req.WalletName, }, nil } func (s *walletServer) GetMnemonic(_ context.Context, req *pactus.GetMnemonicRequest, ) (*pactus.GetMnemonicResponse, error) { mnemonic, err := s.walletManager.Mnemonic(req.WalletName, req.Password) if err != nil { return nil, err } return &pactus.GetMnemonicResponse{ Mnemonic: mnemonic, }, nil } func (s *walletServer) GetPrivateKey(_ context.Context, req *pactus.GetPrivateKeyRequest, ) (*pactus.GetPrivateKeyResponse, error) { prv, err := s.walletManager.PrivateKey(req.WalletName, req.Password, req.Address) if err != nil { return nil, err } return &pactus.GetPrivateKeyResponse{ PrivateKey: prv.String(), }, nil } ================================================ FILE: www/grpc/wallet_test.go ================================================ package grpc import ( "errors" "testing" "time" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/genesis" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/wallet" "github.com/pactus-project/pactus/wallet/types" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func TestWalletServiceIsDisabled(t *testing.T) { conf := testConfig() conf.EnableWallet = false td := setup(t, conf) client := td.walletClient(t) res, err := client.CreateWallet(t.Context(), &pactus.CreateWalletRequest{ WalletName: "TestWallet", }) require.ErrorIs(t, err, status.Error(codes.Unimplemented, "unknown service pactus.Wallet")) assert.Nil(t, res) } func TestCreateWallet(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("No wallet name, should return an error", func(t *testing.T) { res, err := client.CreateWallet(t.Context(), &pactus.CreateWalletRequest{ WalletName: "", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Create wallet failed", func(t *testing.T) { td.mockWalletMgr.EXPECT(). CreateWallet("test", "password"). Return("", errors.New("error on creating wallet")) res, err := client.CreateWallet(t.Context(), &pactus.CreateWalletRequest{ WalletName: "test", Password: "password", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Create wallet successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). CreateWallet("test", "password"). Return("mnemonic", nil) res, err := client.CreateWallet(t.Context(), &pactus.CreateWalletRequest{ WalletName: "test", Password: "password", }) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, "test", res.WalletName) assert.Equal(t, "mnemonic", res.Mnemonic) }) } func TestRestoreWallet(t *testing.T) { config := testConfig() config.EnableWallet = true td := setup(t, config) client := td.walletClient(t) t.Run("No wallet name, should return an error", func(t *testing.T) { res, err := client.RestoreWallet(t.Context(), &pactus.RestoreWalletRequest{}) require.Error(t, err) assert.Nil(t, res) }) t.Run("No mnemonic, should return an error", func(t *testing.T) { res, err := client.RestoreWallet(t.Context(), &pactus.RestoreWalletRequest{ WalletName: "test", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Restore wallet failed", func(t *testing.T) { mnemonic, err := wallet.GenerateMnemonic(128) require.NoError(t, err) td.mockWalletMgr.EXPECT(). RestoreWallet("test", mnemonic, "password"). Return(errors.New("error on restoring wallet")) res, err := client.RestoreWallet(t.Context(), &pactus.RestoreWalletRequest{ WalletName: "test", Mnemonic: mnemonic, Password: "password", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Restore wallet successfully", func(t *testing.T) { mnemonic, err := wallet.GenerateMnemonic(128) require.NoError(t, err) td.mockWalletMgr.EXPECT(). RestoreWallet("test", mnemonic, "password"). Return(nil) res, err := client.RestoreWallet(t.Context(), &pactus.RestoreWalletRequest{ WalletName: "test", Mnemonic: mnemonic, Password: "password", }) require.NoError(t, err) assert.NotNil(t, res) assert.Equal(t, "test", res.WalletName) }) } func TestGetTotalBalance(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on getting total balance", func(t *testing.T) { td.mockWalletMgr.EXPECT(). TotalBalance("test"). Return(amount.Amount(0), errors.New("error on getting total balance")) res, err := client.GetTotalBalance(t.Context(), &pactus.GetTotalBalanceRequest{ WalletName: "test", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Get total balance successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). TotalBalance("test"). Return(amount.Amount(123), nil) res, err := client.GetTotalBalance(t.Context(), &pactus.GetTotalBalanceRequest{ WalletName: "test", }) require.NoError(t, err) assert.Equal(t, "test", res.WalletName) assert.Equal(t, int64(123), res.TotalBalance) }) } func TestGetTotalStake(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on getting total stake", func(t *testing.T) { td.mockWalletMgr.EXPECT(). TotalStake("test"). Return(amount.Amount(0), errors.New("error on getting total stake")) res, err := client.GetTotalStake(t.Context(), &pactus.GetTotalStakeRequest{ WalletName: "test", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Get total stake successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). TotalStake("test"). Return(amount.Amount(123), nil) res, err := client.GetTotalStake(t.Context(), &pactus.GetTotalStakeRequest{ WalletName: "test", }) require.NoError(t, err) assert.Equal(t, "test", res.WalletName) assert.Equal(t, int64(123), res.TotalStake) }) } func TestSignRawTransaction(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Bad traansaction data", func(t *testing.T) { res, err := client.SignRawTransaction(t.Context(), &pactus.SignRawTransactionRequest{ WalletName: "test", RawTransaction: "invalid-hex", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Error on signing raw transaction", func(t *testing.T) { td.mockWalletMgr.EXPECT(). SignRawTransaction("test", "", gomock.Any()). Return(nil, nil, errors.New("error on signing raw transaction")) res, err := client.SignRawTransaction(t.Context(), &pactus.SignRawTransactionRequest{ WalletName: "test", RawTransaction: "1a2b3c4d", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Sign raw transaction successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). SignRawTransaction("test", "", gomock.Any()). Return(nil, nil, nil) res, err := client.SignRawTransaction(t.Context(), &pactus.SignRawTransactionRequest{ WalletName: "test", RawTransaction: "1a2b3c4d", }) require.NoError(t, err) assert.NotNil(t, res) }) } func TestGetValidatorAddress(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on getting validator address", func(t *testing.T) { td.mockWalletMgr.EXPECT(). GetValidatorAddress("pubKey"). Return("", errors.New("error on getting validator address")) res, err := client.GetValidatorAddress(t.Context(), &pactus.GetValidatorAddressRequest{ PublicKey: "pubKey", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Get validator address successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). GetValidatorAddress("pubKey"). Return("valAddr", nil) res, err := client.GetValidatorAddress(t.Context(), &pactus.GetValidatorAddressRequest{ PublicKey: "pubKey", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "valAddr", res.Address) }) } func TestSignMessage(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on signing message", func(t *testing.T) { td.mockWalletMgr.EXPECT(). SignMessage("test", "password", "addr", "hello"). Return("", errors.New("error on signing message")) res, err := client.SignMessage(t.Context(), &pactus.SignMessageRequest{ WalletName: "test", Password: "password", Address: "addr", Message: "hello", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Sign message successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). SignMessage("test", "password", "addr", "hello"). Return("signature", nil) res, err := client.SignMessage(t.Context(), &pactus.SignMessageRequest{ WalletName: "test", Password: "password", Address: "addr", Message: "hello", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "signature", res.Signature) }) } func TestNewAddress(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on getting new address", func(t *testing.T) { td.mockWalletMgr.EXPECT(). NewAddress("test", crypto.AddressTypeBLSAccount, "label", gomock.Any()). Return(nil, errors.New("error on getting new address")) res, err := client.GetNewAddress(t.Context(), &pactus.GetNewAddressRequest{ WalletName: "test", AddressType: pactus.AddressType_ADDRESS_TYPE_BLS_ACCOUNT, Label: "label", Password: "password", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Get new address successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). NewAddress("test", crypto.AddressTypeBLSAccount, "label", gomock.Any()). Return(&types.AddressInfo{ Address: "addr", Label: "label", PublicKey: "pub", Path: "m/44'/0'/0'/0/0", }, nil) res, err := client.GetNewAddress(t.Context(), &pactus.GetNewAddressRequest{ WalletName: "test", AddressType: pactus.AddressType_ADDRESS_TYPE_BLS_ACCOUNT, Label: "label", Password: "password", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "test", res.WalletName) require.NotNil(t, res.Addr) assert.Equal(t, "addr", res.Addr.Address) assert.Equal(t, "label", res.Addr.Label) assert.Equal(t, "pub", res.Addr.PublicKey) assert.Equal(t, "m/44'/0'/0'/0/0", res.Addr.Path) }) } func TestAddressInfo(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on getting address info", func(t *testing.T) { td.mockWalletMgr.EXPECT(). AddressInfo("test", "addr"). Return(nil, errors.New("error on getting address info")) res, err := client.GetAddressInfo(t.Context(), &pactus.GetAddressInfoRequest{ WalletName: "test", Address: "addr", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Get address info successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). AddressInfo("test", "addr"). Return(&types.AddressInfo{ Address: "addr", Label: "label", PublicKey: "pub", Path: "path", }, nil) res, err := client.GetAddressInfo(t.Context(), &pactus.GetAddressInfoRequest{ WalletName: "test", Address: "addr", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "test", res.WalletName) assert.Equal(t, "addr", res.Addr.Address) assert.Equal(t, "label", res.Addr.Label) assert.Equal(t, "pub", res.Addr.PublicKey) assert.Equal(t, "path", res.Addr.Path) }) } func TestSetAddressLabel(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on setting address label", func(t *testing.T) { td.mockWalletMgr.EXPECT(). SetAddressLabel("test", "addr", "label"). Return(errors.New("error on setting address label")) res, err := client.SetAddressLabel(t.Context(), &pactus.SetAddressLabelRequest{ WalletName: "test", Password: "password", Address: "addr", Label: "label", }) require.Error(t, err) assert.Nil(t, res) }) t.Run("Set address label successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). SetAddressLabel("test", "addr", "label"). Return(nil) res, err := client.SetAddressLabel(t.Context(), &pactus.SetAddressLabelRequest{ WalletName: "test", Password: "password", Address: "addr", Label: "label", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "test", res.WalletName) assert.Equal(t, "addr", res.Address) assert.Equal(t, "label", res.Label) }) } func TestListWallet(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on listing wallets", func(t *testing.T) { td.mockWalletMgr.EXPECT(). ListWallets(). Return(nil, errors.New("error on listing wallets")) res, err := client.ListWallets(t.Context(), &pactus.ListWalletsRequest{}) require.Error(t, err) assert.Nil(t, res) }) t.Run("List wallets successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). ListWallets(). Return([]string{"w1", "w2"}, nil) res, err := client.ListWallets(t.Context(), &pactus.ListWalletsRequest{}) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, []string{"w1", "w2"}, res.Wallets) }) } func TestGetWalletInfo(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on getting wallet info", func(t *testing.T) { td.mockWalletMgr.EXPECT(). WalletInfo("test"). Return(nil, errors.New("error on getting wallet info")) res, err := client.GetWalletInfo(t.Context(), &pactus.GetWalletInfoRequest{WalletName: "test"}) require.Error(t, err) assert.Nil(t, res) }) t.Run("Get wallet info successfully", func(t *testing.T) { createdAt := time.Unix(123, 0).UTC() td.mockWalletMgr.EXPECT(). WalletInfo("test"). Return(&types.WalletInfo{ Version: 7, Network: genesis.Mainnet, Encrypted: true, UUID: "uuid", CreatedAt: createdAt, DefaultFee: amount.Amount(456), }, nil) res, err := client.GetWalletInfo(t.Context(), &pactus.GetWalletInfoRequest{WalletName: "test"}) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "test", res.WalletName) assert.Equal(t, int32(7), res.Version) assert.Equal(t, "Mainnet", res.Network) assert.True(t, res.Encrypted) assert.Equal(t, "uuid", res.Uuid) assert.Equal(t, createdAt.Unix(), res.CreatedAt) assert.Equal(t, int64(456), res.DefaultFee) }) } func TestListAddress(t *testing.T) { conf := testConfig() conf.EnableWallet = true td := setup(t, conf) client := td.walletClient(t) t.Run("Error on listing addresses", func(t *testing.T) { td.mockWalletMgr.EXPECT(). ListAddresses("test", gomock.Any()). Return(nil, errors.New("error on listing addresses")) res, err := client.ListAddresses(t.Context(), &pactus.ListAddressesRequest{WalletName: "test"}) require.Error(t, err) assert.Nil(t, res) }) t.Run("List addresses successfully", func(t *testing.T) { td.mockWalletMgr.EXPECT(). ListAddresses("test", gomock.Any()). Return([]types.AddressInfo{ { Address: "addr1", Label: "label1", PublicKey: "pub1", Path: "path1", }, { Address: "addr2", Label: "label2", PublicKey: "pub2", Path: "path2", }, }, nil) res, err := client.ListAddresses(t.Context(), &pactus.ListAddressesRequest{WalletName: "test"}) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "test", res.WalletName) require.Len(t, res.Addrs, 2) assert.Equal(t, "addr1", res.Addrs[0].Address) assert.Equal(t, "label1", res.Addrs[0].Label) assert.Equal(t, "pub1", res.Addrs[0].PublicKey) assert.Equal(t, "path1", res.Addrs[0].Path) }) } ================================================ FILE: www/html/README.md ================================================ # HTTP This directory contains required files for HTTP service. HTTP modules has no direct connection with Pactus blockchain. It gets information through [GRPC](../grpc) APIs. Note: It's recommended to disable HTTP service in production. ================================================ FILE: www/html/blockchain.go ================================================ package html import ( "context" "fmt" "net/http" "strconv" "time" "github.com/gorilla/mux" "github.com/pactus-project/pactus/crypto/hash" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/types/vote" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) func (s *Server) BlockchainHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() res, err := s.blockchain.GetBlockchainInfo(ctx, &pactus.GetBlockchainInfoRequest{}) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowBlockHash("Last Block Hash", res.LastBlockHash) tmk.addRowInt("Last Block Height", int(res.LastBlockHeight)) tmk.addRowString("Last Block Time", time.Unix(res.LastBlockTime, 0).String()) tmk.addRowInt("Total Accounts", int(res.TotalAccounts)) tmk.addRowInt("Total Validators", int(res.TotalValidators)) tmk.addRowInt("Active Validators", int(res.ActiveValidators)) tmk.addRowString("Average Score", fmt.Sprintf("%.2f", res.AverageScore)) tmk.addRowPower("Total Power", res.TotalPower) tmk.addRowPower("Committee Power", res.CommitteePower) tmk.addRowInt("Committee Size", int(res.CommitteeSize)) tmk.addRowBool("Is Pruned", res.IsPruned) tmk.addRowInt("Pruning Height", int(res.PruningHeight)) tmk.addRowBool("In Committee", res.InCommittee) s.writeHTML(w, tmk.html()) } func (s *Server) CommitteeHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() res, err := s.blockchain.GetCommitteeInfo(ctx, &pactus.GetCommitteeInfoRequest{}) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowPower("Committee Power", res.CommitteePower) tmk.addRowPower("Total Power", res.TotalPower) tmk.addRowInt("Committee Size", int(res.CommitteeSize)) tmk.addRowInt("Validators", len(res.Validators)) tmk.addRowString("--- Protocol Versions", "---") for ver, percentage := range res.ProtocolVersions { tmk.addRowDouble(fmt.Sprintf("Version %d", ver), percentage) } tmk.addRowString("--- Validators", "---") for i, val := range res.Validators { tmk.addRowInt("--- Validator", i+1) tmVal := s.writeValidatorTable(val) tmk.addRowString("", tmVal.html()) } s.writeHTML(w, tmk.html()) } func (s *Server) GetBlockByHeightHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) height, err := strconv.ParseInt(vars["height"], 10, 32) if err != nil { s.writeError(w, err) return } s.blockByHeight(ctx, w, uint32(height)) } func (s *Server) GetBlockByHashHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) blockHash, err := hash.FromString(vars["hash"]) if err != nil { s.writeError(w, err) return } res, err := s.blockchain.GetBlockHeight(ctx, &pactus.GetBlockHeightRequest{Hash: blockHash.String()}) if err != nil { s.writeError(w, err) return } s.blockByHeight(ctx, w, res.Height) } func (s *Server) blockByHeight(ctx context.Context, w http.ResponseWriter, blockHeight uint32) { res, err := s.blockchain.GetBlock(ctx, &pactus.GetBlockRequest{ Height: blockHeight, Verbosity: pactus.BlockVerbosity_BLOCK_VERBOSITY_TRANSACTIONS, }, ) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowString("Time", time.Unix(int64(res.BlockTime), 0).String()) tmk.addRowInt("Height", int(res.Height)) tmk.addRowString("Hash", res.Hash) tmk.addRowString("Data", res.Data) if res.Header != nil { tmk.addRowString("--- Header", "---") tmk.addRowInt("Version", int(res.Header.Version)) tmk.addRowInt("UnixTime", int(res.BlockTime)) tmk.addRowBlockHash("PrevBlockHash", res.Header.PrevBlockHash) tmk.addRowString("StateRoot", res.Header.StateRoot) tmk.addRowString("SortitionSeed", res.Header.SortitionSeed) tmk.addRowValAddress("ProposerAddress", res.Header.ProposerAddress) } if res.PrevCert != nil { tmk.addRowString("--- PrevCertificate", "---") tmk.addRowString("Hash", res.PrevCert.Hash) tmk.addRowInt("Round", int(res.PrevCert.Round)) tmk.addRowInts("Committers", res.PrevCert.Committers) tmk.addRowInts("Absentees", res.PrevCert.Absentees) tmk.addRowString("Signature", res.PrevCert.Signature) } tmk.addRowString("--- Transactions", "---") for i, trx := range res.Txs { tmk.addRowInt("Transaction #", i+1) txToTable(tmk, trx) } s.writeHTML(w, tmk.html()) } // GetAccountHandler returns a handler to get account by address. func (s *Server) GetAccountHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) res, err := s.blockchain.GetAccount(ctx, &pactus.GetAccountRequest{Address: vars["address"]}) if err != nil { s.writeError(w, err) return } acc := res.Account tmk := newTableMaker() tmk.addRowAccAddress("Address", acc.Address) tmk.addRowInt("Number", int(acc.Number)) tmk.addRowAmount("Balance", amount.Amount(acc.Balance)) tmk.addRowString("Hash", acc.Hash) s.writeHTML(w, tmk.html()) } // GetValidatorHandler returns a handler to get validator by address. func (s *Server) GetValidatorHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) res, err := s.blockchain.GetValidator(ctx, &pactus.GetValidatorRequest{Address: vars["address"]}) if err != nil { s.writeError(w, err) return } tm := s.writeValidatorTable(res.Validator) s.writeHTML(w, tm.html()) } // GetValidatorByNumberHandler returns a handler to get validator by number. func (s *Server) GetValidatorByNumberHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) num, err := strconv.ParseInt(vars["number"], 10, 32) if err != nil { s.writeError(w, err) return } res, err := s.blockchain.GetValidatorByNumber(ctx, &pactus.GetValidatorByNumberRequest{ Number: int32(num), }) if err != nil { s.writeError(w, err) return } tm := s.writeValidatorTable(res.Validator) s.writeHTML(w, tm.html()) } func (s *Server) GetTxPoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() res, err := s.blockchain.GetTxPoolContent(ctx, &pactus.GetTxPoolContentRequest{}) if err != nil { s.writeError(w, err) return } tm := newTableMaker() for i, trx := range res.Txs { tm.addRowString("\n-------------- ", fmt.Sprintf("%d --------------\n", i)) txToTable(tm, trx) } s.writeHTML(w, tm.html()) } func (*Server) writeValidatorTable(val *pactus.ValidatorInfo) *tableMaker { tmk := newTableMaker() tmk.addRowString("Public Key", val.PublicKey) tmk.addRowValAddress("Address", val.Address) tmk.addRowInt("Number", int(val.Number)) tmk.addRowAmount("Stake", amount.Amount(val.Stake)) tmk.addRowInt("LastBondingHeight", int(val.LastBondingHeight)) tmk.addRowInt("LastSortitionHeight", int(val.LastSortitionHeight)) tmk.addRowInt("UnbondingHeight", int(val.UnbondingHeight)) tmk.addRowDouble("AvailabilityScore", val.AvailabilityScore) tmk.addRowInt("ProtocolVersion", int(val.ProtocolVersion)) tmk.addRowBool("IsDelegated", val.IsDelegated) if val.IsDelegated { tmk.addRowAccAddress("DelegateOwner", val.DelegateOwner) tmk.addRowAmount("DelegateShare", amount.Amount(val.DelegateShare)) tmk.addRowInt("DelegateExpiry", int(val.DelegateExpiry)) } tmk.addRowString("Hash", val.Hash) return tmk } func (s *Server) ConsensusHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() res, err := s.blockchain.GetConsensusInfo(ctx, &pactus.GetConsensusInfoRequest{}) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowString("== Proposal", "") if res.Proposal != nil { tmk.addRowInt("Height", int(res.Proposal.Height)) tmk.addRowInt("Round", int(res.Proposal.Round)) tmk.addRowString("BlockData", res.Proposal.BlockData) tmk.addRowString("Signature", res.Proposal.Signature) } for i, cons := range res.Instances { tmk.addRowInt("== Validator", i+1) tmk.addRowValAddress("Address", cons.Address) tmk.addRowBool("Active", cons.Active) tmk.addRowInt("Height", int(cons.Height)) tmk.addRowInt("Round", int(cons.Round)) tmk.addRowString("Votes", "---") for index, vte := range cons.Votes { tmk.addRowInt("-- Vote #", index+1) tmk.addRowBlockHash("BlockHash", vte.BlockHash) tmk.addRowString("Type", vote.Type(vte.Type).String()) tmk.addRowString("Voter", vte.Voter) tmk.addRowInt("Round", int(vte.Round)) tmk.addRowInt("CPRound", int(vte.CpRound)) tmk.addRowInt("CPValue", int(vte.CpValue)) } } s.writeHTML(w, tmk.html()) } ================================================ FILE: www/html/blockchain_test.go ================================================ package html import ( "fmt" "net/http" "net/http/httptest" "strconv" "testing" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" ) func TestBlockchainInfo(t *testing.T) { td := setup(t) td.mockState.CommitTestBlocks(10) w := httptest.NewRecorder() r := new(http.Request) td.httpServer.BlockchainHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "10") td.StopServers() } func TestBlock(t *testing.T) { td := setup(t) height := td.RandHeight() blk := td.mockState.TestStore.AddTestBlock(height) t.Run("Shall return a block", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"hash": blk.Hash().String()}) td.httpServer.GetBlockByHashHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), blk.Hash().String()) }) t.Run("Shall return a block", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"height": fmt.Sprintf("%d", height)}) td.httpServer.GetBlockByHeightHandler(w, r) assert.Equal(t, 200, w.Code) }) t.Run("Shall return an error, invalid height", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"height": "x"}) td.httpServer.GetBlockByHeightHandler(w, r) assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, non exists", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"hash": td.RandHash().String()}) td.httpServer.GetBlockByHashHandler(w, r) assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, invalid hash", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"hash": "abc"}) td.httpServer.GetBlockByHashHandler(w, r) fmt.Println(w.Body) assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, empty hash", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"hash": ""}) td.httpServer.GetBlockByHashHandler(w, r) fmt.Println(w.Body) assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, no hash", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) td.httpServer.GetBlockByHashHandler(w, r) fmt.Println(w.Body) assert.Equal(t, 400, w.Code) }) td.StopServers() } func TestAccount(t *testing.T) { td := setup(t) addr, acc := td.mockState.TestStore.AddTestAccount() t.Run("Shall return an account", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": addr.String()}) td.httpServer.GetAccountHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), acc.Balance().String()) fmt.Println(w.Body) }) t.Run("Shall return nil, non exist", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": td.RandAccAddress().String()}) td.httpServer.GetAccountHandler(w, r) assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, invalid address", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": "invalid-address"}) td.httpServer.GetAccountHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, empty address", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": ""}) td.httpServer.GetAccountHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, no address", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) td.httpServer.GetAccountHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) td.StopServers() } func TestValidator(t *testing.T) { td := setup(t) val := td.mockState.TestStore.AddTestValidator() t.Run("Shall return an error, non exist", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": td.RandAccAddress().String()}) td.httpServer.GetValidatorHandler(w, r) assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, invalid address", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": "invalid-address"}) td.httpServer.GetValidatorHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, empty address", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": ""}) td.httpServer.GetValidatorHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, no address", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) td.httpServer.GetValidatorHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return a validator", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"address": val.Address().String()}) td.httpServer.GetValidatorHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "0.987") fmt.Println(w.Body) }) td.StopServers() } func TestValidatorByNumber(t *testing.T) { td := setup(t) val := td.mockState.TestStore.AddTestValidator() t.Run("Shall return a validator", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) fmt.Println(val.Number()) fmt.Println(strconv.Itoa(int(val.Number()))) r = mux.SetURLVars(r, map[string]string{"number": strconv.Itoa(int(val.Number()))}) td.httpServer.GetValidatorByNumberHandler(w, r) assert.Equal(t, 200, w.Code) fmt.Println(w.Body) }) t.Run("Shall return a error, non exist", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) fmt.Println(val.Number()) fmt.Println(strconv.Itoa(int(val.Number()))) r = mux.SetURLVars(r, map[string]string{"number": strconv.Itoa(int(val.Number() + 1))}) td.httpServer.GetValidatorByNumberHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, empty number", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"number": ""}) td.httpServer.GetValidatorByNumberHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, invalid number", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"number": "not-a-number"}) td.httpServer.GetValidatorByNumberHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) t.Run("Shall return an error, no number", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) td.httpServer.GetValidatorByNumberHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) td.StopServers() } func TestConsensusInfo(t *testing.T) { td := setup(t) height, _ := td.mockConsMgr.HeightRound() vote1, _ := td.GenerateTestPrepareVote(height, 1) vote2, _ := td.GenerateTestPrecommitVote(height, 2) prop := td.GenerateTestProposal(height, 2) td.mockConsMgr.AddVote(vote1) td.mockConsMgr.AddVote(vote2) td.mockConsMgr.SetProposal(prop) w := httptest.NewRecorder() r := new(http.Request) td.httpServer.ConsensusHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "2") assert.Contains(t, w.Body.String(), vote2.Signer().String()) assert.Contains(t, w.Body.String(), prop.Signature().String()) td.StopServers() } ================================================ FILE: www/html/config.go ================================================ package html // Config defines parameters for the HTML UI server. type Config struct { Enable bool `toml:"enable"` Listen string `toml:"listen"` EnablePprof bool `toml:"enable_pprof"` } func DefaultConfig() *Config { return &Config{ Enable: false, Listen: "", EnablePprof: false, } } // BasicCheck performs basic checks on the configuration. func (*Config) BasicCheck() error { return nil } ================================================ FILE: www/html/html_test.go ================================================ package html import ( "fmt" "net/http" "net/http/httptest" "testing" consmgr "github.com/pactus-project/pactus/consensus/manager" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/network" "github.com/pactus-project/pactus/state" "github.com/pactus-project/pactus/sync" "github.com/pactus-project/pactus/util/testsuite" wltmgr "github.com/pactus-project/pactus/wallet/manager" "github.com/pactus-project/pactus/www/grpc" "github.com/pactus-project/pactus/www/zmq" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testData struct { *testsuite.TestSuite mockState *state.MockState mockSync *sync.MockSync mockConsMgr consmgr.Manager gRPCServer *grpc.Server httpServer *Server } func (td *testData) StopServers() { td.httpServer.StopServer() td.gRPCServer.StopServer() } func setup(t *testing.T) *testData { t.Helper() ts := testsuite.NewTestSuite(t) // Resetting http handlers in golang for unit testing: // https://stackoverflow.com/questions/40786526/resetting-http-handlers-in-golang-for-unit-testing // http.DefaultServeMux = new(http.ServeMux) valKeys := []*bls.ValidatorKey{ts.RandValKey(), ts.RandValKey()} mockState := state.MockingState(ts) mockSync := sync.MockingSync(ts) mockNet := network.MockingNetwork(ts, ts.RandPeerID()) mockConsMgr, _ := consmgr.MockingManager(ts, mockState, valKeys) mockConsMgr.MoveToNewHeight() grpcConf := &grpc.Config{ Enable: true, Listen: "[::]:0", } httpConf := &Config{ Enable: true, Listen: "[::]:0", } mockWalletMgr := wltmgr.NewMockIManager(ts.MockingController()) zmqPublishers := []zmq.Publisher{ zmq.MockingPublisher("zmq_address", "zmq_topic", 100), } gRPCServer := grpc.NewServer(t.Context(), grpcConf, mockState, mockSync, mockNet, mockConsMgr, mockWalletMgr, zmqPublishers, ) require.NoError(t, gRPCServer.StartServer()) httpServer := NewServer(t.Context(), httpConf, false) require.NoError(t, httpServer.StartServer(gRPCServer.Address())) return &testData{ TestSuite: ts, mockState: mockState, mockSync: mockSync, mockConsMgr: mockConsMgr, gRPCServer: gRPCServer, httpServer: httpServer, } } func TestRootHandler(t *testing.T) { td := setup(t) w := httptest.NewRecorder() r := new(http.Request) td.httpServer.RootHandler(w, r) assert.Equal(t, 200, w.Code) fmt.Println(w.Body) td.StopServers() } ================================================ FILE: www/html/middleware.go ================================================ package html import ( "net/http" "github.com/pactus-project/pactus/www/grpc/basicauth" "google.golang.org/grpc/metadata" ) func basicAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, password, ok := r.BasicAuth() if !ok { w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) http.Error(w, "unauthorized", http.StatusUnauthorized) return } ba := basicauth.New(user, password) tokens, _ := ba.GetRequestMetadata(r.Context()) md := metadata.New(tokens) r = r.WithContext(metadata.NewOutgoingContext(r.Context(), md)) next.ServeHTTP(w, r) }) } ================================================ FILE: www/html/middleware_test.go ================================================ package html import ( "encoding/base64" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "google.golang.org/grpc/metadata" ) func TestBasicAuthMiddleware(t *testing.T) { handler := basicAuth(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("authorized")) assert.NoError(t, err) })) t.Run("NoAuth", func(t *testing.T) { req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody) rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) assert.Equal(t, http.StatusUnauthorized, rec.Code) assert.Equal(t, `Basic realm="restricted", charset="UTF-8"`, rec.Header().Get("WWW-Authenticate")) }) t.Run("WithAuth", func(t *testing.T) { req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody) req.SetBasicAuth("username", "password") rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "authorized", rec.Body.String()) }) t.Run("CheckMetadata", func(t *testing.T) { req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody) req.SetBasicAuth("username", "password") rec := httptest.NewRecorder() checkMetadataHandler := basicAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { md, ok := metadata.FromOutgoingContext(r.Context()) assert.True(t, ok, "No metadata in context") auth := md["authorization"][0] const prefix = "Basic " c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) assert.NoError(t, err) cs := string(c) username, password, ok := strings.Cut(cs, ":") assert.True(t, ok) assert.Equal(t, "username", username) assert.Equal(t, "password", password) w.WriteHeader(http.StatusOK) })) checkMetadataHandler.ServeHTTP(rec, req) assert.Equal(t, http.StatusOK, rec.Code) }) } ================================================ FILE: www/html/network.go ================================================ package html import ( "cmp" "fmt" "net/http" "slices" "time" lp2pnetwork "github.com/libp2p/go-libp2p/core/network" "github.com/pactus-project/pactus/crypto/bls" "github.com/pactus-project/pactus/sync/bundle/message" "github.com/pactus-project/pactus/sync/peerset/peer/service" "github.com/pactus-project/pactus/sync/peerset/peer/status" "github.com/pactus-project/pactus/util" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) func (s *Server) NetworkHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() info, err := s.network.GetNetworkInfo(ctx, &pactus.GetNetworkInfoRequest{}) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowString("Network Name", info.NetworkName) tmk.addRowInt("Connected Peers Count", int(info.ConnectedPeersCount)) tmk.addRowString("Peers", "/network/peers") metricToTable(tmk, info.MetricInfo) s.writeHTML(w, tmk.html()) } func (s *Server) PeerListHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() includeDisconnected := r.URL.Query().Get("includeDisconnected") == "true" res, err := s.network.ListPeers(ctx, &pactus.ListPeersRequest{ IncludeDisconnected: includeDisconnected, }) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowString("Peers", "---") peers := res.Peers slices.SortFunc(peers, func(a, b *pactus.PeerInfo) int { return cmp.Compare( b.MetricInfo.TotalReceived.Bundles, a.MetricInfo.TotalReceived.Bundles, ) }) for index, peer := range peers { tmk.addRowInt("-- Peer #", index+1) tmk.addRowString("Status", status.Status(peer.Status).String()) tmk.addRowString("PeerID", peer.PeerId) tmk.addRowString("Services", service.Services(peer.Services).String()) tmk.addRowString("Agent", peer.Agent) tmk.addRowString("Moniker", peer.Moniker) tmk.addRowString("Remote Address", peer.Address) tmk.addRowString("Direction", lp2pnetwork.Direction(peer.Direction).String()) tmk.addRowBool("OutboundHelloSent", peer.OutboundHelloSent) tmk.addRowStrings("Protocols", peer.Protocols) tmk.addRowString("LastSent", time.Unix(peer.LastSent, 0).String()) tmk.addRowString("LastReceived", time.Unix(peer.LastReceived, 0).String()) tmk.addRowBlockHash("Last block Hash", peer.LastBlockHash) tmk.addRowInt("Height", int(peer.Height)) tmk.addRowInt("TotalSessions", int(peer.TotalSessions)) tmk.addRowInt("CompletedSessions", int(peer.CompletedSessions)) metricToTable(tmk, peer.MetricInfo) for _, key := range peer.ConsensusKeys { pub, _ := bls.PublicKeyFromString(key) tmk.addRowString("-- PublicKey", pub.String()) tmk.addRowValAddress("-- Address", pub.ValidatorAddress().String()) } } s.writeHTML(w, tmk.html()) } func (s *Server) NodeHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() res, err := s.network.GetNodeInfo(ctx, &pactus.GetNodeInfoRequest{}) if err != nil { s.writeError(w, err) return } tmk := newTableMaker() tmk.addRowString("Peer ID", res.PeerId) tmk.addRowString("Agent", res.Agent) tmk.addRowString("Moniker", res.Moniker) tmk.addRowTime("Started at", int64(res.StartedAt)) tmk.addRowTime("Current time", int64(res.CurrentTime)) tmk.addRowString("Reachability", res.Reachability) tmk.addRowFloat64("Clock Offset", res.ClockOffset) tmk.addRowInt("Services", int(res.Services)) tmk.addRowString("Services Names", res.ServicesNames) tmk.addRowString("Connection Info", "---") tmk.addRowInt("-- Total connections", int(res.ConnectionInfo.Connections)) tmk.addRowInt("-- Inbound connections", int(res.ConnectionInfo.InboundConnections)) tmk.addRowInt("-- Outbound connections", int(res.ConnectionInfo.OutboundConnections)) tmk.addRowString("Protocols", "---") for i, p := range res.Protocols { tmk.addRowString(fmt.Sprint(i), p) } tmk.addRowString("ZeroMQ Publishers", "---") for i, p := range res.ZmqPublishers { tmk.addRowString(fmt.Sprint(i), fmt.Sprintf("%s, %s, %d", p.Topic, p.Address, p.Hwm)) } tmk.addRowString("Local Addresses", "---") for i, la := range res.LocalAddrs { tmk.addRowString(fmt.Sprint(i), la) } s.writeHTML(w, tmk.html()) } func metricToTable(tmk *tableMaker, metricInfo *pactus.MetricInfo) { printCounter := func(tmk *tableMaker, name string, counterInfo *pactus.CounterInfo) { tmk.addRowString(name, fmt.Sprintf("[%d, %s]", counterInfo.Bundles, util.FormatBytesToHumanReadable(counterInfo.Bytes))) } printSortedMap := func(tmk *tableMaker, msgCounter map[int32]*pactus.CounterInfo) { keys := make([]int32, 0, len(msgCounter)) for k := range msgCounter { keys = append(keys, k) } slices.SortFunc(keys, func(a, b int32) int { return cmp.Compare(msgCounter[b].Bundles, msgCounter[a].Bundles) }) for _, key := range keys { printCounter(tmk, message.Type(key).String(), msgCounter[key]) } } printCounter(tmk, "Total Invalid", metricInfo.TotalInvalid) tmk.addRowString("Sent Metric", "---") printCounter(tmk, "Total Sent", metricInfo.TotalSent) printSortedMap(tmk, metricInfo.MessageSent) tmk.addRowString("Received Metric", "---") printCounter(tmk, "Total Received", metricInfo.TotalReceived) printSortedMap(tmk, metricInfo.MessageReceived) } ================================================ FILE: www/html/network_test.go ================================================ package html import ( "net/http" "net/http/httptest" "testing" "github.com/pactus-project/pactus/version" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNodeInfo(t *testing.T) { td := setup(t) w := httptest.NewRecorder() r := new(http.Request) td.httpServer.NodeHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), version.NodeAgent.String()) assert.Contains(t, w.Body.String(), "zmq_topic") td.StopServers() } func TestNetworkInfo(t *testing.T) { td := setup(t) w := httptest.NewRecorder() r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "/network/info", http.NoBody) require.NoError(t, err) td.httpServer.NetworkHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "Network Name") assert.Contains(t, w.Body.String(), "Connected Peers Count") assert.Contains(t, w.Body.String(), "/network/peers") td.StopServers() } func TestPeerList(t *testing.T) { td := setup(t) w := httptest.NewRecorder() r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "/network/peers", http.NoBody) require.NoError(t, err) td.httpServer.PeerListHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "Peers") td.StopServers() } ================================================ FILE: www/html/server.go ================================================ package html import ( "bytes" "context" "fmt" "io" "net" "net/http" "net/http/pprof" "strings" "time" "github.com/gorilla/handlers" "github.com/gorilla/mux" ret "github.com/grpc-ecosystem/go-grpc-middleware/retry" "github.com/pactus-project/pactus/types/amount" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "github.com/prometheus/client_golang/prometheus/promhttp" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) type Server struct { ctx context.Context config *Config listener net.Listener server *http.Server grpcConn *grpc.ClientConn blockchain pactus.BlockchainClient transaction pactus.TransactionClient network pactus.NetworkClient router *mux.Router enableAuth bool logger *logger.SubLogger } // init disables default pprof handlers registered by importing net/http/pprof. // Your pprof is showing (https://mmcloughlin.com/posts/your-pprof-is-showing) func init() { http.DefaultServeMux = http.NewServeMux() } func NewServer(ctx context.Context, conf *Config, enableAuth bool) *Server { return &Server{ ctx: ctx, config: conf, enableAuth: enableAuth, logger: logger.NewSubLogger("_html", nil), } } func (s *Server) StartServer(grpcServer string) error { if !s.config.Enable { return nil } dialOpts := make([]grpc.DialOption, 0, 2) dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithUnaryInterceptor(ret.UnaryClientInterceptor()), ) grpcConn, err := grpc.NewClient( grpcServer, dialOpts..., ) if err != nil { return fmt.Errorf("failed to dial server: %w", err) } s.grpcConn = grpcConn s.blockchain = pactus.NewBlockchainClient(grpcConn) s.transaction = pactus.NewTransactionClient(grpcConn) s.network = pactus.NewNetworkClient(grpcConn) s.router = mux.NewRouter() s.router.HandleFunc("/", s.RootHandler) s.router.HandleFunc("/blockchain/", s.BlockchainHandler) s.router.HandleFunc("/committee/", s.CommitteeHandler) s.router.HandleFunc("/consensus", s.ConsensusHandler) s.router.HandleFunc("/network/info", s.NetworkHandler) s.router.HandleFunc("/network/peers", s.PeerListHandler) s.router.HandleFunc("/node", s.NodeHandler) s.router.HandleFunc("/block/hash/{hash}", s.GetBlockByHashHandler) s.router.HandleFunc("/block/height/{height}", s.GetBlockByHeightHandler) s.router.HandleFunc("/transaction/id/{id}", s.GetTransactionHandler) s.router.HandleFunc("/txpool", s.GetTxPoolHandler) s.router.HandleFunc("/account/address/{address}", s.GetAccountHandler) s.router.HandleFunc("/validator/address/{address}", s.GetValidatorHandler) s.router.HandleFunc("/validator/number/{number}", s.GetValidatorByNumberHandler) s.router.HandleFunc("/metrics/prometheus", promhttp.Handler().ServeHTTP) if s.config.EnablePprof { http.HandleFunc("/debug/pprof/", pprof.Index) http.HandleFunc("/debug/pprof/profile", pprof.Profile) http.HandleFunc("/debug/pprof/symbol", pprof.Symbol) http.HandleFunc("/debug/pprof/trace", pprof.Trace) s.router.HandleFunc("/debug/pprof", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/debug/pprof/", http.StatusPermanentRedirect) }) } if s.enableAuth { http.Handle("/", handlers.RecoveryHandler()(basicAuth(s.router))) } else { http.Handle("/", handlers.RecoveryHandler()(s.router)) } listener, err := util.NetworkListen(s.ctx, "tcp", s.config.Listen) if err != nil { return err } s.listener = listener s.server = &http.Server{ Addr: listener.Addr().String(), ReadHeaderTimeout: 3 * time.Second, } go func() { s.logger.Info("HTML server start listening", "address", listener.Addr()) if err := s.server.Serve(listener); err != nil { s.logger.Debug("error on HTML server", "error", err) } }() return nil } func (s *Server) StopServer() { if s.server != nil { _ = s.server.Shutdown(s.ctx) _ = s.server.Close() _ = s.listener.Close() } if s.grpcConn != nil { _ = s.grpcConn.Close() } } func (s *Server) RootHandler(w http.ResponseWriter, r *http.Request) { if s.enableAuth { if _, _, ok := r.BasicAuth(); !ok { w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) http.Error(w, "unauthorized", http.StatusUnauthorized) return } } buf := new(bytes.Buffer) buf.WriteString("
") err := s.router.Walk(func(route *mux.Route, _ *mux.Router, _ []*mux.Route) error { pathTemplate, err := route.GetPathTemplate() if err == nil { link := pathTemplate i := strings.Index(link, "{") if i != -1 { link = link[0:i] } fmt.Fprintf(buf, "%s
", link, pathTemplate) } return nil }) if err != nil { s.logger.Error("unable to walk through methods", "error", err) return } buf.WriteString("") s.writeHTML(w, buf.String()) } func (s *Server) writeError(w http.ResponseWriter, err error) int { s.logger.Error("an error occurred", "error", err) w.Header().Set("Content-Type", "text/plain") w.WriteHeader(http.StatusBadRequest) n, _ := io.WriteString(w, err.Error()) return n } func (*Server) writeHTML(w http.ResponseWriter, html string) int { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusOK) n, _ := io.WriteString(w, html) return n } type tableMaker struct { w *bytes.Buffer } func newTableMaker() *tableMaker { t := &tableMaker{ w: bytes.NewBufferString(""), } return t } func (t *tableMaker) addRowBlockHash(key, val string) { fmt.Fprintf(t.w, "", key, val, val) } func (t *tableMaker) addRowAccAddress(key, val string) { fmt.Fprintf(t.w, "", key, val, val) } func (t *tableMaker) addRowValAddress(key, val string) { fmt.Fprintf(t.w, "", key, val, val) } func (t *tableMaker) addRowTxID(key, val string) { fmt.Fprintf(t.w, "", key, val, val) } func (t *tableMaker) addRowString(key, val string) { fmt.Fprintf(t.w, "", key, val) } func (t *tableMaker) addRowStrings(key string, val []string) { fmt.Fprintf(t.w, "", key, strings.Join(val, ",")) } func (t *tableMaker) addRowTime(key string, sec int64) { fmt.Fprintf(t.w, "", key, time.Unix(sec, 0).String()) } func (t *tableMaker) addRowAmount(key string, amt amount.Amount) { fmt.Fprintf(t.w, "", key, amt.String()) } func (t *tableMaker) addRowPower(key string, power int64) { amt := amount.Amount(power) fmt.Fprintf(t.w, "", key, amt.String()) } func (t *tableMaker) addRowFloat64(key string, val float64) { fmt.Fprintf(t.w, "", key, val) } func (t *tableMaker) addRowInt(key string, val int) { fmt.Fprintf(t.w, "", key, val) } func (t *tableMaker) addRowBool(key string, val bool) { fmt.Fprintf(t.w, "", key, val) } func (t *tableMaker) addRowInts(key string, vals []int32) { fmt.Fprintf(t.w, "") } func (t *tableMaker) addRowDouble(key string, val float64) { fmt.Fprintf(t.w, "", key, val) } func (t *tableMaker) html() string { t.w.WriteString("
%s%s
%s%s
%s%s
%s%s
%s%s
%s%v
%s%s
%s%s
%s%s
%s%v
%s%d
%s%v
%s", key) for _, n := range vals { fmt.Fprintf(t.w, "%d, ", n) } t.w.WriteString("
%s%f
") return t.w.String() } ================================================ FILE: www/html/transaction.go ================================================ package html import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/pactus-project/pactus/types/amount" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" ) func (s *Server) GetTransactionHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) res, err := s.transaction.GetTransaction(ctx, &pactus.GetTransactionRequest{ Id: vars["id"], Verbosity: pactus.TransactionVerbosity_TRANSACTION_VERBOSITY_INFO, }, ) if err != nil { s.writeError(w, err) return } tm := newTableMaker() txToTable(tm, res.Transaction) s.writeHTML(w, tm.html()) } func txToTable(tmk *tableMaker, trx *pactus.TransactionInfo) { if trx == nil { return } tmk.addRowTxID("ID", trx.Id) tmk.addRowInt("Version", int(trx.Version)) tmk.addRowInt("LockTime", int(trx.LockTime)) tmk.addRowInt("Block Height", int(trx.BlockHeight)) tmk.addRowBool("Confirmed", trx.Confirmed) tmk.addRowInt("Confirmations", int(trx.Confirmations)) tmk.addRowAmount("Fee", amount.Amount(trx.Fee)) tmk.addRowString("Memo", trx.Memo) tmk.addRowString("Payload Type", trx.PayloadType.String()) switch trx.PayloadType { case pactus.PayloadType_PAYLOAD_TYPE_TRANSFER: pld := trx.Payload.(*pactus.TransactionInfo_Transfer).Transfer tmk.addRowAccAddress("Sender", pld.Sender) tmk.addRowAccAddress("Receiver", pld.Receiver) tmk.addRowAmount("Amount", amount.Amount(pld.Amount)) case pactus.PayloadType_PAYLOAD_TYPE_BOND: pld := trx.Payload.(*pactus.TransactionInfo_Bond).Bond tmk.addRowAccAddress("Sender", pld.Sender) tmk.addRowValAddress("Receiver", pld.Receiver) tmk.addRowAmount("Stake", amount.Amount(pld.Stake)) tmk.addRowBool("Is Delegated", pld.IsDelegated) if pld.IsDelegated { tmk.addRowAccAddress("Delegate Owner", pld.DelegateOwner) tmk.addRowAmount("Delegate Share", amount.Amount(pld.DelegateShare)) tmk.addRowInt("Delegate Expiry", int(pld.DelegateExpiry)) } case pactus.PayloadType_PAYLOAD_TYPE_SORTITION: pld := trx.Payload.(*pactus.TransactionInfo_Sortition).Sortition tmk.addRowValAddress("Address", pld.Address) tmk.addRowString("Proof", pld.Proof) case pactus.PayloadType_PAYLOAD_TYPE_UNBOND: pld := trx.Payload.(*pactus.TransactionInfo_Unbond).Unbond tmk.addRowValAddress("Validator", pld.Validator) if pld.DelegateOwner != "" { tmk.addRowAccAddress("Delegate Owner", pld.DelegateOwner) } case pactus.PayloadType_PAYLOAD_TYPE_WITHDRAW: pld := trx.Payload.(*pactus.TransactionInfo_Withdraw).Withdraw tmk.addRowValAddress("Sender", pld.ValidatorAddress) tmk.addRowAccAddress("Receiver", pld.AccountAddress) tmk.addRowAmount("Amount", amount.Amount(pld.Amount)) case pactus.PayloadType_PAYLOAD_TYPE_BATCH_TRANSFER: pld := trx.Payload.(*pactus.TransactionInfo_BatchTransfer) tmk.addRowAccAddress("Sender", pld.BatchTransfer.Sender) for i, recip := range pld.BatchTransfer.Recipients { tmk.addRowAccAddress(fmt.Sprintf("\tReceiver [%d]", i+1), recip.Receiver) tmk.addRowAmount("\tAmount", amount.Amount(recip.Amount)) } case pactus.PayloadType_PAYLOAD_TYPE_UNSPECIFIED: tmk.addRowValAddress("error", "unknown payload type") } if trx.PublicKey != "" { tmk.addRowString("PublicKey", trx.PublicKey) } if trx.Signature != "" { tmk.addRowString("Signature", trx.Signature) } } ================================================ FILE: www/html/transaction_test.go ================================================ package html import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" ) func TestTransaction(t *testing.T) { td := setup(t) testBlock := td.mockState.TestStore.AddTestBlock(1) testTx := testBlock.Transactions()[1] t.Run("Shall return a transaction", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) r = mux.SetURLVars(r, map[string]string{"id": testTx.ID().String()}) td.httpServer.GetTransactionHandler(w, r) assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), testTx.Signature().String()) assert.Contains(t, w.Body.String(), testTx.Signature().String()) fmt.Println(w.Body) }) t.Run("Shall return an error", func(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) td.httpServer.GetTransactionHandler(w, r) assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) td.StopServers() } ================================================ FILE: www/http/config.go ================================================ package http import ( "fmt" "strings" ) // Config defines parameters for the HTTP server. type Config struct { Enable bool `toml:"enable"` Listen string `toml:"listen"` BasePath string `toml:"base_path"` EnableCORS bool `toml:"enable_cors"` } func DefaultConfig() *Config { return &Config{ Enable: false, Listen: "", BasePath: "/http", EnableCORS: false, } } func (*Config) BasicCheck() error { return nil } func (c *Config) swaggerPattern() string { return fmt.Sprintf("%sui/", c.rootPattern()) } func (c *Config) apiPattern() string { return fmt.Sprintf("%sapi/", c.rootPattern()) } func (c *Config) rootPattern() string { path := fmt.Sprintf("/%s/", c.BasePath) path = strings.ReplaceAll(path, "//", "/") path = strings.ReplaceAll(path, "//", "/") return path } ================================================ FILE: www/http/config_test.go ================================================ package http import ( "testing" "github.com/stretchr/testify/assert" ) func TestHandlerPattern(t *testing.T) { tests := []struct { basePath string expectedRoot string expectedAPI string expectedSwagger string }{ { basePath: "", expectedRoot: "/", expectedAPI: "/api/", expectedSwagger: "/ui/", }, { basePath: "/", expectedRoot: "/", expectedAPI: "/api/", expectedSwagger: "/ui/", }, { basePath: "http", expectedRoot: "/http/", expectedAPI: "/http/api/", expectedSwagger: "/http/ui/", }, { basePath: "/http", expectedRoot: "/http/", expectedAPI: "/http/api/", expectedSwagger: "/http/ui/", }, { basePath: "http/", expectedRoot: "/http/", expectedAPI: "/http/api/", expectedSwagger: "/http/ui/", }, } for _, tt := range tests { cfg := &Config{ BasePath: tt.basePath, } assert.Equal(t, tt.expectedRoot, cfg.rootPattern()) assert.Equal(t, tt.expectedAPI, cfg.apiPattern()) assert.Equal(t, tt.expectedSwagger, cfg.swaggerPattern()) } } ================================================ FILE: www/http/server.go ================================================ package http import ( "bytes" "context" "embed" "fmt" "io/fs" "net" "net/http" "strings" "time" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/pactus-project/pactus/util" "github.com/pactus-project/pactus/util/logger" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) type Server struct { ctx context.Context config *Config listener net.Listener server *http.Server grpcConn *grpc.ClientConn logger *logger.SubLogger } //go:embed swagger-ui var swaggerFS embed.FS // getOpenAPIHandler serves an OpenAPI UI. func (s *Server) getOpenAPIHandler() (http.Handler, error) { swaggerTree, err := fs.Sub(swaggerFS, "swagger-ui") if err != nil { return nil, err } handler := http.FileServer(http.FS(swaggerTree)) // Modify basePath in Swagger JSON file origContent, err := swaggerFS.ReadFile("swagger-ui/pactus.swagger.json") if err != nil { return nil, err } modifiedContent := bytes.Replace( origContent, []byte(`"basePath": "/http/api"`), []byte(fmt.Sprintf(`"basePath": %q`, s.patternToPrefix(s.config.apiPattern()))), 1, ) handler = s.changeBasePath(handler, modifiedContent) return handler, nil } func NewServer(ctx context.Context, conf *Config) *Server { return &Server{ ctx: ctx, config: conf, logger: logger.NewSubLogger("_http", nil), } } func (s *Server) StartServer(grpcAddr string) error { if !s.config.Enable { return nil } grpcConn, err := grpc.NewClient( grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { return fmt.Errorf("failed to dial server: %w", err) } s.grpcConn = grpcConn // gRPC-Gateway multiplexer gatewayMux := runtime.NewServeMux() if err := pactus.RegisterBlockchainHandler(s.ctx, gatewayMux, grpcConn); err != nil { return err } if err := pactus.RegisterTransactionHandler(s.ctx, gatewayMux, grpcConn); err != nil { return err } if err := pactus.RegisterNetworkHandler(s.ctx, gatewayMux, grpcConn); err != nil { return err } if err := pactus.RegisterWalletHandler(s.ctx, gatewayMux, grpcConn); err != nil { return err } if err := pactus.RegisterUtilsHandler(s.ctx, gatewayMux, grpcConn); err != nil { return err } // Swagger UI swaggerHandler, err := s.getOpenAPIHandler() if err != nil { return err } httpMux := http.NewServeMux() // Register gRPC-Gateway Handler at `/http/api` httpMux.Handle(s.config.apiPattern(), http.StripPrefix(s.patternToPrefix(s.config.apiPattern()), gatewayMux)) // Register Swagger Handler at `/http/ui` httpMux.Handle(s.config.swaggerPattern(), http.StripPrefix(s.patternToPrefix(s.config.swaggerPattern()), swaggerHandler)) // Redirect `/http` to `/http/ui` httpMux.HandleFunc(s.config.rootPattern(), func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, s.config.swaggerPattern(), http.StatusFound) }) gwServer := &http.Server{ Addr: s.config.Listen, ReadHeaderTimeout: 3 * time.Second, Handler: httpMux, } if s.config.EnableCORS { gwServer.Handler = allowCORS(gwServer.Handler) } listener, err := util.NetworkListen(s.ctx, "tcp", s.config.Listen) if err != nil { return err } s.server = gwServer s.listener = listener go func() { s.logger.Info("HTTP-API server start listening", "address", listener.Addr().String()) if err := s.server.Serve(listener); err != nil && err != http.ErrServerClosed { s.logger.Debug("error on HTTP-API server", "error", err) } }() return nil } func (*Server) changeBasePath(handler http.Handler, modifiedContent []byte) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/pactus.swagger.json" { w.Header().Set("Content-Type", "application/json") _, err := w.Write(modifiedContent) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } else { handler.ServeHTTP(w, r) } }) } func (s *Server) StopServer() { if s.server != nil { _ = s.server.Close() _ = s.listener.Close() } if s.grpcConn != nil { _ = s.grpcConn.Close() } } // preflightHandler adds the necessary headers in order to serve // CORS from any origin using the methods "GET", "HEAD", "POST", "PUT", "DELETE" // We insist, don't do this without consideration in production systems. func preflightHandler(w http.ResponseWriter) { headers := []string{"Content-Type", "Accept", "Authorization"} w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"} w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) } // allowCORS allows Cross Origin Resource Sharing from any origin. // Don't do this without consideration in production systems. func allowCORS(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { preflightHandler(w) return } } handler.ServeHTTP(w, r) }) } // patternToPrefix removes the trailing '/' from the given pattern. // Example: "/http/ui/" becomes "/http/ui". func (*Server) patternToPrefix(pattern string) string { return pattern[:len(pattern)-1] } ================================================ FILE: www/http/server_test.go ================================================ package http import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) // passThroughHandler is a minimal handler that records that it was called and // optionally sets a body so tests can assert whether the CORS wrapper invoked it. func passThroughHandler(t *testing.T, called *bool) http.Handler { t.Helper() return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { if called != nil { *called = true } w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("ok")) assert.NoError(t, err) }) } func TestAllowCORS(t *testing.T) { tests := []struct { name string method string origin string preflightMethod string wantAllowOrigin string wantPreflight bool wantHandlerCalled bool }{ { name: "SimpleGETWithOriginSetsAllowOrigin", method: http.MethodGet, origin: "https://example.com", wantAllowOrigin: "https://example.com", wantHandlerCalled: true, }, { name: "SimplePOSTWithOriginSetsAllowOrigin", method: http.MethodPost, origin: "https://app.example.com", wantAllowOrigin: "https://app.example.com", wantHandlerCalled: true, }, { name: "RequestWithoutOriginGetsNoCORSHeaders", method: http.MethodGet, origin: "", wantAllowOrigin: "", wantHandlerCalled: true, }, { name: "PreflightOPTIONSSetsPreflightHeaders", method: http.MethodOptions, origin: "https://example.com", preflightMethod: http.MethodPost, wantAllowOrigin: "https://example.com", wantPreflight: true, wantHandlerCalled: false, }, { name: "OPTIONSWithoutPreflightHeaderFallsThrough", method: http.MethodOptions, origin: "https://example.com", preflightMethod: "", wantAllowOrigin: "https://example.com", wantPreflight: false, wantHandlerCalled: true, }, { name: "PreflightWithoutOriginDoesNothing", method: http.MethodOptions, origin: "", preflightMethod: http.MethodPost, wantAllowOrigin: "", wantPreflight: false, wantHandlerCalled: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { called := false handler := allowCORS(passThroughHandler(t, &called)) req := httptest.NewRequestWithContext( t.Context(), tt.method, "/http/api/blockchain/get_block_hash", http.NoBody, ) if tt.origin != "" { req.Header.Set("Origin", tt.origin) } if tt.preflightMethod != "" { req.Header.Set("Access-Control-Request-Method", tt.preflightMethod) } rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) assert.Equal(t, tt.wantAllowOrigin, rec.Header().Get("Access-Control-Allow-Origin")) assert.Equal(t, tt.wantHandlerCalled, called, "handler invocation expectation mismatch") if tt.wantPreflight { allowHeaders := rec.Header().Get("Access-Control-Allow-Headers") allowMethods := rec.Header().Get("Access-Control-Allow-Methods") assert.Contains(t, allowHeaders, "Authorization") assert.Contains(t, allowHeaders, "Content-Type") assert.Contains(t, allowHeaders, "Accept") for _, m := range []string{"GET", "HEAD", "POST", "PUT", "DELETE"} { assert.Contains(t, allowMethods, m, "preflight missing method %q", m) } } else { assert.Empty(t, rec.Header().Get("Access-Control-Allow-Headers")) assert.Empty(t, rec.Header().Get("Access-Control-Allow-Methods")) } }) } } func TestPreflightHandlerSetsAllMethodsAndHeaders(t *testing.T) { rec := httptest.NewRecorder() preflightHandler(rec) allowHeaders := rec.Header().Get("Access-Control-Allow-Headers") allowMethods := rec.Header().Get("Access-Control-Allow-Methods") // Headers must include everything documented in the preflightHandler comment. for _, h := range []string{"Content-Type", "Accept", "Authorization"} { assert.Containsf(t, allowHeaders, h, "preflight Access-Control-Allow-Headers %q missing %q", allowHeaders, h) } // Methods must include everything documented in the preflightHandler comment. for _, m := range []string{"GET", "HEAD", "POST", "PUT", "DELETE"} { assert.Containsf(t, allowMethods, m, "preflight Access-Control-Allow-Methods %q missing %q", allowMethods, m) } } ================================================ FILE: www/http/swagger-ui/LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: www/http/swagger-ui/README.md ================================================ # Swagger UI This directory contains HTML, Javascript, and CSS assets that dynamically generate Swagger documentation from a [OpenAPI Specification Version 2.0](https://swagger.io/docs/specification/2-0/basic-structure/). That file is auto-generated by running `make proto` in the root of this repository. The static assets are copied from the [dist folder](https://github.com/swagger-api/swagger-ui/tree/master/dist). After copying, [`swagger-initializer.js`](./swagger-initializer.js) is edited to load the swagger file from the local server instead of the default petstore. SwaggerUI is licensed under Apache 2.0 license. ================================================ FILE: www/http/swagger-ui/index.css ================================================ html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; } *, *:before, *:after { box-sizing: inherit; } body { margin: 0; background: #fafafa; } ================================================ FILE: www/http/swagger-ui/index.html ================================================ Swagger UI
================================================ FILE: www/http/swagger-ui/oauth2-redirect.html ================================================ Swagger UI: OAuth2 Redirect ================================================ FILE: www/http/swagger-ui/pactus.swagger.json ================================================ { "swagger": "2.0", "info": { "title": "Pactus APIs", "description": "Every node in the Pactus network can be configured to expose HTTP-APIs for communication.\nThese APIs follow the [OpenAPI (Swagger)](https://swagger.io/specification/) specification, and a complete list of available endpoints can be found here.\n\n## Units\n\nAll the amounts are in NanoPAC units, which are atomic and the smallest unit in the Pactus blockchain.\nEach PAC is equivalent to 1,000,000,000 or 10\u003csup\u003e9\u003c/sup\u003e NanoPACs.\n", "version": "2.0", "contact": { "name": "Pactus Blockchain", "url": "https://pactus.org" }, "license": { "name": "MIT License", "url": "https://github.com/pactus-project/pactus/blob/main/LICENSE" } }, "tags": [ { "name": "Transaction" }, { "name": "Blockchain" }, { "name": "Network" }, { "name": "Utils" }, { "name": "Wallet" } ], "basePath": "/http/api", "schemes": [ "http", "https" ], "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/pactus/Utils/public_key_aggregation": { "post": { "summary": "PublicKeyAggregation aggregates multiple BLS public keys into a single key.", "operationId": "Utils_PublicKeyAggregation", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusPublicKeyAggregationResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for aggregating multiple BLS public keys.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusPublicKeyAggregationRequest" } } ], "tags": [ "Utils" ] } }, "/pactus/Utils/sign_message_with_private_key": { "post": { "summary": "SignMessageWithPrivateKey signs a message with the provided private key.", "operationId": "Utils_SignMessageWithPrivateKey", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusSignMessageWithPrivateKeyResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for signing a message with a private key.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusSignMessageWithPrivateKeyRequest" } } ], "tags": [ "Utils" ] } }, "/pactus/Utils/signature_aggregation": { "post": { "summary": "SignatureAggregation aggregates multiple BLS signatures into a single signature.", "operationId": "Utils_SignatureAggregation", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusSignatureAggregationResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for aggregating multiple BLS signatures.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusSignatureAggregationRequest" } } ], "tags": [ "Utils" ] } }, "/pactus/Utils/verify_message": { "post": { "summary": "VerifyMessage verifies a signature against the public key and message.", "operationId": "Utils_VerifyMessage", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusVerifyMessageResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for verifying a message signature.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusVerifyMessageRequest" } } ], "tags": [ "Utils" ] } }, "/pactus/blockchain/get_account": { "get": { "summary": "GetAccount retrieves information about an account based on the provided address.", "operationId": "Blockchain_GetAccount", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetAccountResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "address", "description": "The address of the account to retrieve information for.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_block": { "get": { "summary": "GetBlock retrieves information about a block based on the provided request parameters.", "operationId": "Blockchain_GetBlock", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetBlockResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "height", "description": "The height of the block to retrieve.", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "verbosity", "description": "The verbosity level for block information.\n\n - BLOCK_VERBOSITY_DATA: Request only block data.\n - BLOCK_VERBOSITY_INFO: Request block information and transaction IDs.\n - BLOCK_VERBOSITY_TRANSACTIONS: Request block information and detailed transaction data.", "in": "query", "required": false, "type": "string", "enum": [ "BLOCK_VERBOSITY_DATA", "BLOCK_VERBOSITY_INFO", "BLOCK_VERBOSITY_TRANSACTIONS" ], "default": "BLOCK_VERBOSITY_DATA" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_block_hash": { "get": { "summary": "GetBlockHash retrieves the hash of a block at the specified height.", "operationId": "Blockchain_GetBlockHash", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetBlockHashResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "height", "description": "The height of the block to retrieve the hash for.", "in": "query", "required": false, "type": "integer", "format": "int64" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_block_height": { "get": { "summary": "GetBlockHeight retrieves the height of a block with the specified hash.", "operationId": "Blockchain_GetBlockHeight", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetBlockHeightResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "hash", "description": "The hash of the block to retrieve the height for.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_blockchain_info": { "get": { "summary": "GetBlockchainInfo retrieves general information about the blockchain.", "operationId": "Blockchain_GetBlockchainInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetBlockchainInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_committee_info": { "get": { "summary": "GetCommitteeInfo retrieves information about the current committee.", "operationId": "Blockchain_GetCommitteeInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetCommitteeInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_consensus_info": { "get": { "summary": "GetConsensusInfo retrieves information about the consensus instances.", "operationId": "Blockchain_GetConsensusInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetConsensusInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_public_key": { "get": { "summary": "GetPublicKey retrieves the public key of an account based on the provided address.", "operationId": "Blockchain_GetPublicKey", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetPublicKeyResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "address", "description": "The address for which to retrieve the public key.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_txpool_content": { "get": { "summary": "GetTxPoolContent retrieves current transactions in the transaction pool.", "operationId": "Blockchain_GetTxPoolContent", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetTxPoolContentResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "payloadType", "description": "The type of transactions to retrieve from the transaction pool. 0 means all types.\n\n - PAYLOAD_TYPE_UNSPECIFIED: Unspecified payload type.\n - PAYLOAD_TYPE_TRANSFER: Transfer payload type.\n - PAYLOAD_TYPE_BOND: Bond payload type.\n - PAYLOAD_TYPE_SORTITION: Sortition payload type.\n - PAYLOAD_TYPE_UNBOND: Unbond payload type.\n - PAYLOAD_TYPE_WITHDRAW: Withdraw payload type.\n - PAYLOAD_TYPE_BATCH_TRANSFER: Batch transfer payload type.", "in": "query", "required": false, "type": "string", "enum": [ "PAYLOAD_TYPE_UNSPECIFIED", "PAYLOAD_TYPE_TRANSFER", "PAYLOAD_TYPE_BOND", "PAYLOAD_TYPE_SORTITION", "PAYLOAD_TYPE_UNBOND", "PAYLOAD_TYPE_WITHDRAW", "PAYLOAD_TYPE_BATCH_TRANSFER" ], "default": "PAYLOAD_TYPE_UNSPECIFIED" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_validator": { "get": { "summary": "GetValidator retrieves information about a validator based on the provided address.", "operationId": "Blockchain_GetValidator", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetValidatorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "address", "description": "The address of the validator to retrieve information for.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_validator_addresses": { "get": { "summary": "GetValidatorAddresses retrieves a list of all validator addresses.", "operationId": "Blockchain_GetValidatorAddresses", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetValidatorAddressesResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Blockchain" ] } }, "/pactus/blockchain/get_validator_by_number": { "get": { "summary": "GetValidatorByNumber retrieves information about a validator based on the provided number.", "operationId": "Blockchain_GetValidatorByNumber", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetValidatorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "number", "description": "The unique number of the validator to retrieve information for.", "in": "query", "required": false, "type": "integer", "format": "int32" } ], "tags": [ "Blockchain" ] } }, "/pactus/network/get_network_info": { "get": { "summary": "GetNetworkInfo retrieves information about the overall network.", "operationId": "Network_GetNetworkInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetNetworkInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Network" ] } }, "/pactus/network/get_node_info": { "get": { "summary": "GetNodeInfo retrieves information about a specific node in the network.", "operationId": "Network_GetNodeInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetNodeInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Network" ] } }, "/pactus/network/ping": { "get": { "summary": "Ping provides a simple connectivity test and latency measurement.", "operationId": "Network_Ping", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusPingResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Network" ] } }, "/pactus/transaction/broadcast_transaction": { "post": { "summary": "BroadcastTransaction broadcasts a signed transaction to the network.", "operationId": "Transaction_BroadcastTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusBroadcastTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for broadcasting a signed transaction to the network.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusBroadcastTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/calculate_fee": { "post": { "summary": "CalculateFee calculates the transaction fee based on the specified amount and payload type.", "operationId": "Transaction_CalculateFee", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusCalculateFeeResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for calculating transaction fee.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusCalculateFeeRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/decode_raw_transaction": { "post": { "summary": "DecodeRawTransaction accepts raw transaction and returns decoded transaction.", "operationId": "Transaction_DecodeRawTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusDecodeRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for decoding a raw transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusDecodeRawTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/get_raw_batch_transfer_transaction": { "post": { "summary": "GetRawBatchTransferTransaction retrieves raw details of batch transfer transaction.", "operationId": "Transaction_GetRawBatchTransferTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for retrieving raw details of a batch transfer transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusGetRawBatchTransferTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/get_raw_bond_transaction": { "post": { "summary": "GetRawBondTransaction retrieves raw details of a bond transaction.", "operationId": "Transaction_GetRawBondTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for retrieving raw details of a bond transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusGetRawBondTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/get_raw_transfer_transaction": { "post": { "summary": "GetRawTransferTransaction retrieves raw details of a transfer transaction.", "operationId": "Transaction_GetRawTransferTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for retrieving raw details of a transfer transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusGetRawTransferTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/get_raw_unbond_transaction": { "post": { "summary": "GetRawUnbondTransaction retrieves raw details of an unbond transaction.", "operationId": "Transaction_GetRawUnbondTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for retrieving raw details of an unbond transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusGetRawUnbondTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/get_raw_withdraw_transaction": { "post": { "summary": "GetRawWithdrawTransaction retrieves raw details of a withdraw transaction.", "operationId": "Transaction_GetRawWithdrawTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for retrieving raw details of a withdraw transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusGetRawWithdrawTransactionRequest" } } ], "tags": [ "Transaction" ] } }, "/pactus/transaction/get_transaction": { "get": { "summary": "GetTransaction retrieves transaction details based on the provided request parameters.", "operationId": "Transaction_GetTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "id", "description": "The unique ID of the transaction to retrieve.", "in": "query", "required": false, "type": "string" }, { "name": "verbosity", "description": "The verbosity level for transaction details.\n\n - TRANSACTION_VERBOSITY_DATA: Request transaction data only.\n - TRANSACTION_VERBOSITY_INFO: Request detailed transaction information.", "in": "query", "required": false, "type": "string", "enum": [ "TRANSACTION_VERBOSITY_DATA", "TRANSACTION_VERBOSITY_INFO" ], "default": "TRANSACTION_VERBOSITY_DATA" } ], "tags": [ "Transaction" ] } }, "/pactus/wallet/create_wallet": { "post": { "summary": "CreateWallet creates a new wallet with the specified parameters.", "operationId": "Wallet_CreateWallet", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusCreateWalletResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for creating a new wallet.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusCreateWalletRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/get_address_info": { "get": { "summary": "GetAddressInfo returns detailed information about a specific address.", "operationId": "Wallet_GetAddressInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetAddressInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the wallet containing the address.", "in": "query", "required": false, "type": "string" }, { "name": "address", "description": "The address to query.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/get_new_address": { "post": { "summary": "GetNewAddress generates a new address for the specified wallet.", "operationId": "Wallet_GetNewAddress", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetNewAddressResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for generating a new wallet address.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusGetNewAddressRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/get_total_balance": { "get": { "summary": "GetTotalBalance returns the total available balance of the wallet.", "operationId": "Wallet_GetTotalBalance", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetTotalBalanceResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the wallet to get the total balance.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/get_total_stake": { "get": { "summary": "GetTotalStake returns the total stake amount in the wallet.", "operationId": "Wallet_GetTotalStake", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetTotalStakeResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the wallet to get the total stake.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/get_validator_address": { "get": { "summary": "GetValidatorAddress retrieves the validator address associated with a public key.\nDeprecated: Will move into utils.", "operationId": "Wallet_GetValidatorAddress", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetValidatorAddressResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "publicKey", "description": "The public key of the validator.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/get_wallet_info": { "get": { "summary": "GetWalletInfo returns detailed information about a specific wallet.", "operationId": "Wallet_GetWalletInfo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusGetWalletInfoResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the wallet to query.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/list_addresses": { "get": { "summary": "ListAddresses returns all addresses in the specified wallet.", "operationId": "Wallet_ListAddresses", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusListAddressesResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the queried wallet.", "in": "query", "required": false, "type": "string" }, { "name": "addressTypes", "description": "Filter addresses by their types. If empty, all address types are included.\n\n - ADDRESS_TYPE_TREASURY: Treasury address type.\nShould not be used to generate new addresses.\n - ADDRESS_TYPE_VALIDATOR: Validator address type used for validator nodes.\n - ADDRESS_TYPE_BLS_ACCOUNT: Account address type with BLS signature scheme.\n - ADDRESS_TYPE_ED25519_ACCOUNT: Account address type with Ed25519 signature scheme.\nNote: Generating a new Ed25519 address requires the wallet password.", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ADDRESS_TYPE_TREASURY", "ADDRESS_TYPE_VALIDATOR", "ADDRESS_TYPE_BLS_ACCOUNT", "ADDRESS_TYPE_ED25519_ACCOUNT" ] }, "collectionFormat": "multi" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/list_transactions": { "get": { "summary": "ListTransactions returns a list of transactions for a wallet,\noptionally filtered by a specific address, with pagination support.", "operationId": "Wallet_ListTransactions", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusListTransactionsResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the wallet to query transactions for.", "in": "query", "required": false, "type": "string" }, { "name": "address", "description": "Optional: The address to filter transactions.\nIf empty or set to '*', transactions for all addresses in the wallet are included.", "in": "query", "required": false, "type": "string" }, { "name": "direction", "description": "Filter transactions by direction relative to the wallet.\nDefaults to any direction if not set.\n\n - TX_DIRECTION_ANY: include both incoming and outgoing transactions.\n - TX_DIRECTION_INCOMING: Include only incoming transactions where the wallet receives funds.\n - TX_DIRECTION_OUTGOING: Include only outgoing transactions where the wallet sends funds.", "in": "query", "required": false, "type": "string", "enum": [ "TX_DIRECTION_ANY", "TX_DIRECTION_INCOMING", "TX_DIRECTION_OUTGOING" ], "default": "TX_DIRECTION_ANY" }, { "name": "count", "description": "Optional: The maximum number of transactions to return.\nDefaults to 10 if not set.", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "skip", "description": "Optional: The number of transactions to skip (for pagination).\nDefaults to 0 if not set.", "in": "query", "required": false, "type": "integer", "format": "int32" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/list_wallets": { "get": { "summary": "ListWallets returns a list of all available wallets.", "operationId": "Wallet_ListWallets", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusListWalletsResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "tags": [ "Wallet" ] } }, "/pactus/wallet/load_wallet": { "post": { "summary": "LoadWallet loads an existing wallet with the given name.\ndeprecated: It will be removed in a future version.", "operationId": "Wallet_LoadWallet", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusLoadWalletResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for loading an existing wallet.\nDeprecated: It will be removed in a future version.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusLoadWalletRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/restore_wallet": { "post": { "summary": "RestoreWallet restores an existing wallet with the given mnemonic.", "operationId": "Wallet_RestoreWallet", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusRestoreWalletResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for restoring a wallet from mnemonic (seed phrase).", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusRestoreWalletRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/set_address_label": { "patch": { "summary": "SetAddressLabel sets or updates the label for a given address.", "operationId": "Wallet_SetAddressLabel", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusSetAddressLabelResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "walletName", "description": "The name of the wallet containing the address.", "in": "query", "required": false, "type": "string" }, { "name": "password", "description": "Wallet password required for modification.", "in": "query", "required": false, "type": "string" }, { "name": "address", "description": "The address to label.", "in": "query", "required": false, "type": "string" }, { "name": "label", "description": "The new label for the address.", "in": "query", "required": false, "type": "string" } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/sign_message": { "post": { "summary": "SignMessage signs an arbitrary message using a wallet's private key.", "operationId": "Wallet_SignMessage", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusSignMessageResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message to sign an arbitrary message.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusSignMessageRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/sign_raw_transaction": { "post": { "summary": "SignRawTransaction signs a raw transaction for a specified wallet.", "operationId": "Wallet_SignRawTransaction", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusSignRawTransactionResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for signing a raw transaction.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusSignRawTransactionRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/unload_wallet": { "post": { "summary": "UnloadWallet unloads a currently loaded wallet with the specified name.\ndeprecated: It will be removed in a future version.", "operationId": "Wallet_UnloadWallet", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusUnloadWalletResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for unloading a wallet.\nDeprecated: It will be removed in a future version.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusUnloadWalletRequest" } } ], "tags": [ "Wallet" ] } }, "/pactus/wallet/update_password": { "post": { "summary": "UpdatePassword updates the password of an existing wallet.", "operationId": "Wallet_UpdatePassword", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/pactusUpdatePasswordResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/rpcStatus" } } }, "parameters": [ { "name": "body", "description": "Request message for updating wallet password.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/pactusUpdatePasswordRequest" } } ], "tags": [ "Wallet" ] } } }, "definitions": { "pactusAccountInfo": { "type": "object", "properties": { "hash": { "type": "string", "description": "The hash of the account." }, "data": { "type": "string", "description": "The serialized data of the account." }, "number": { "type": "integer", "format": "int32", "description": "The unique number assigned to the account." }, "balance": { "type": "string", "format": "int64", "description": "The balance of the account in NanoPAC." }, "address": { "type": "string", "description": "The address of the account." } }, "description": "Message contains information about an account." }, "pactusAddressInfo": { "type": "object", "properties": { "address": { "type": "string", "description": "The address string." }, "publicKey": { "type": "string", "description": "The public key associated with the address." }, "label": { "type": "string", "description": "A human-readable label associated with the address." }, "path": { "type": "string", "description": "The Hierarchical Deterministic (HD) path of the address within the wallet." } }, "description": "AddressInfo contains detailed information about a wallet address." }, "pactusAddressType": { "type": "string", "enum": [ "ADDRESS_TYPE_TREASURY", "ADDRESS_TYPE_VALIDATOR", "ADDRESS_TYPE_BLS_ACCOUNT", "ADDRESS_TYPE_ED25519_ACCOUNT" ], "default": "ADDRESS_TYPE_TREASURY", "description": "AddressType defines different types of blockchain addresses.\n\n - ADDRESS_TYPE_TREASURY: Treasury address type.\nShould not be used to generate new addresses.\n - ADDRESS_TYPE_VALIDATOR: Validator address type used for validator nodes.\n - ADDRESS_TYPE_BLS_ACCOUNT: Account address type with BLS signature scheme.\n - ADDRESS_TYPE_ED25519_ACCOUNT: Account address type with Ed25519 signature scheme.\nNote: Generating a new Ed25519 address requires the wallet password." }, "pactusBlockHeaderInfo": { "type": "object", "properties": { "version": { "type": "integer", "format": "int32", "description": "The version of the block." }, "prevBlockHash": { "type": "string", "description": "The hash of the previous block." }, "stateRoot": { "type": "string", "description": "The state root hash of the blockchain." }, "sortitionSeed": { "type": "string", "description": "The sortition seed of the block." }, "proposerAddress": { "type": "string", "description": "The address of the proposer of the block." } }, "description": "Message contains information about the header of a block." }, "pactusBlockVerbosity": { "type": "string", "enum": [ "BLOCK_VERBOSITY_DATA", "BLOCK_VERBOSITY_INFO", "BLOCK_VERBOSITY_TRANSACTIONS" ], "default": "BLOCK_VERBOSITY_DATA", "description": "Enumeration for verbosity levels when requesting block information.\n\n - BLOCK_VERBOSITY_DATA: Request only block data.\n - BLOCK_VERBOSITY_INFO: Request block information and transaction IDs.\n - BLOCK_VERBOSITY_TRANSACTIONS: Request block information and detailed transaction data." }, "pactusBroadcastTransactionRequest": { "type": "object", "properties": { "signedRawTransaction": { "type": "string", "description": "The signed raw transaction data to be broadcasted." } }, "description": "Request message for broadcasting a signed transaction to the network." }, "pactusBroadcastTransactionResponse": { "type": "object", "properties": { "id": { "type": "string", "description": "The unique ID of the broadcasted transaction." } }, "description": "Response message contains the ID of the broadcasted transaction." }, "pactusCalculateFeeRequest": { "type": "object", "properties": { "amount": { "type": "string", "format": "int64", "description": "The amount involved in the transaction, specified in NanoPAC." }, "payloadType": { "$ref": "#/definitions/pactusPayloadType", "description": "The type of transaction payload." }, "fixedAmount": { "type": "boolean", "description": "Indicates if the amount should be fixed and include the fee." } }, "description": "Request message for calculating transaction fee." }, "pactusCalculateFeeResponse": { "type": "object", "properties": { "amount": { "type": "string", "format": "int64", "description": "The calculated amount in NanoPAC." }, "fee": { "type": "string", "format": "int64", "description": "The calculated transaction fee in NanoPAC." } }, "description": "Response message contains the calculated transaction fee." }, "pactusCertificateInfo": { "type": "object", "properties": { "hash": { "type": "string", "description": "The hash of the certificate." }, "round": { "type": "integer", "format": "int32", "description": "The round of the certificate." }, "committers": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "List of committers in the certificate." }, "absentees": { "type": "array", "items": { "type": "integer", "format": "int32" }, "description": "List of absentees in the certificate." }, "signature": { "type": "string", "description": "The signature of the certificate." } }, "description": "Message contains information about a certificate." }, "pactusConnectionInfo": { "type": "object", "properties": { "connections": { "type": "string", "format": "uint64", "description": "Total number of connections." }, "inboundConnections": { "type": "string", "format": "uint64", "description": "Number of inbound connections." }, "outboundConnections": { "type": "string", "format": "uint64", "description": "Number of outbound connections." } }, "description": "ConnectionInfo contains information about the node's connections." }, "pactusConsensusInfo": { "type": "object", "properties": { "address": { "type": "string", "description": "The address of the consensus instance." }, "active": { "type": "boolean", "description": "Indicates whether the consensus instance is active and part of the committee." }, "height": { "type": "integer", "format": "int64", "description": "The height of the consensus instance." }, "round": { "type": "integer", "format": "int32", "description": "The round of the consensus instance." }, "votes": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusVoteInfo" }, "description": "List of votes in the consensus instance." } }, "description": "Message contains information about a consensus instance." }, "pactusCounterInfo": { "type": "object", "properties": { "bytes": { "type": "string", "format": "uint64", "description": "Total number of bytes." }, "bundles": { "type": "string", "format": "uint64", "description": "Total number of bundles." } }, "description": "CounterInfo holds counter data regarding byte and bundle counts." }, "pactusCreateWalletRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name for the new wallet." }, "password": { "type": "string", "description": "Password to secure the new wallet." } }, "description": "Request message for creating a new wallet." }, "pactusCreateWalletResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name for the new wallet." }, "mnemonic": { "type": "string", "description": "The mnemonic (seed phrase) for wallet recovery." } }, "description": "Response message contains wallet recovery mnemonic (seed phrase)." }, "pactusDecodeRawTransactionRequest": { "type": "object", "properties": { "rawTransaction": { "type": "string", "description": "The raw transaction data in hexadecimal format." } }, "description": "Request message for decoding a raw transaction." }, "pactusDecodeRawTransactionResponse": { "type": "object", "properties": { "transaction": { "$ref": "#/definitions/pactusTransactionInfo", "description": "The decoded transaction information." } }, "description": "Response message contains the decoded transaction." }, "pactusGetAccountResponse": { "type": "object", "properties": { "account": { "$ref": "#/definitions/pactusAccountInfo", "description": "Detailed information about the account." } }, "description": "Response message contains account information." }, "pactusGetAddressInfoResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet containing the address." }, "addr": { "$ref": "#/definitions/pactusAddressInfo", "description": "Detailed information about the address." } }, "description": "Response message contains address details." }, "pactusGetBlockHashResponse": { "type": "object", "properties": { "hash": { "type": "string", "description": "The hash of the block." } }, "description": "Response message contains block hash." }, "pactusGetBlockHeightResponse": { "type": "object", "properties": { "height": { "type": "integer", "format": "int64", "description": "The height of the block." } }, "description": "Response message contains block height." }, "pactusGetBlockResponse": { "type": "object", "properties": { "height": { "type": "integer", "format": "int64", "description": "The height of the block." }, "hash": { "type": "string", "description": "The hash of the block." }, "data": { "type": "string", "description": "Block data, available only if verbosity level is set to BLOCK_VERBOSITY_DATA." }, "blockTime": { "type": "integer", "format": "int64", "description": "The timestamp of the block." }, "header": { "$ref": "#/definitions/pactusBlockHeaderInfo", "description": "Header information of the block." }, "prevCert": { "$ref": "#/definitions/pactusCertificateInfo", "description": "Certificate information of the previous block." }, "txs": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusTransactionInfo" }, "description": "List of transactions in the block, available when verbosity level is set to\nBLOCK_VERBOSITY_TRANSACTIONS." } }, "description": "Response message contains block information." }, "pactusGetBlockchainInfoResponse": { "type": "object", "properties": { "lastBlockHeight": { "type": "integer", "format": "int64", "description": "The height of the last block in the blockchain." }, "lastBlockHash": { "type": "string", "description": "The hash of the last block in the blockchain." }, "lastBlockTime": { "type": "string", "format": "int64", "description": "The timestamp of the last block in Unix format." }, "totalAccounts": { "type": "integer", "format": "int32", "description": "The total number of accounts in the blockchain." }, "totalValidators": { "type": "integer", "format": "int32", "description": "The total number of validators in the blockchain." }, "activeValidators": { "type": "integer", "format": "int32", "description": "The number of active (not unbonded) validators in the blockchain." }, "totalPower": { "type": "string", "format": "int64", "description": "The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC." }, "committeePower": { "type": "string", "format": "int64", "description": "The power of the committee." }, "isPruned": { "type": "boolean", "description": "If the blocks are subject to pruning." }, "pruningHeight": { "type": "integer", "format": "int64", "title": "Lowest-height block stored (only present if pruning is enabled)" }, "inCommittee": { "type": "boolean", "description": "Indicates whether this node participates in consensus: true if at least one\nof its running validators is a member of the current committee." }, "committeeSize": { "type": "integer", "format": "int32", "description": "The number of validators in the current committee." }, "averageScore": { "type": "number", "format": "double", "description": "Average availability score of validators with stake, in percentage (0-100)." } }, "description": "Response message contains general blockchain information." }, "pactusGetCommitteeInfoResponse": { "type": "object", "properties": { "committeeSize": { "type": "integer", "format": "int32", "description": "The number of validators in the committee." }, "committeePower": { "type": "string", "format": "int64", "description": "The power of the committee." }, "totalPower": { "type": "string", "format": "int64", "description": "The total power of the blockchain that is the sum of all validators' stakes, in NanoPAC." }, "validators": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusValidatorInfo" }, "description": "List of committee validators." }, "protocolVersions": { "type": "object", "additionalProperties": { "type": "number", "format": "double" }, "description": "Map of protocol versions and their percentages in the committee." } }, "description": "Response message contains committee information." }, "pactusGetConsensusInfoResponse": { "type": "object", "properties": { "proposal": { "$ref": "#/definitions/pactusProposalInfo", "description": "The proposal of the consensus info." }, "instances": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusConsensusInfo" }, "description": "List of consensus instances." } }, "description": "Response message contains consensus information." }, "pactusGetNetworkInfoResponse": { "type": "object", "properties": { "networkName": { "type": "string", "description": "Name of the P2P network." }, "connectedPeersCount": { "type": "integer", "format": "int64", "description": "Number of connected peers." }, "metricInfo": { "$ref": "#/definitions/pactusMetricInfo", "description": "Metrics related to node activity." } }, "description": "Response message contains information about the overall network." }, "pactusGetNewAddressRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet to generate a new address." }, "addressType": { "$ref": "#/definitions/pactusAddressType", "description": "The type of address to generate." }, "label": { "type": "string", "description": "A label for the new address." }, "password": { "type": "string", "description": "Password for the new address. It's required when address_type is Ed25519 type." } }, "description": "Request message for generating a new wallet address." }, "pactusGetNewAddressResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet where address was generated." }, "addr": { "$ref": "#/definitions/pactusAddressInfo", "description": "Detailed information about the new address." } }, "description": "Response message contains newly generated address information." }, "pactusGetNodeInfoResponse": { "type": "object", "properties": { "moniker": { "type": "string", "description": "Moniker or Human-readable name identifying this node in the network." }, "agent": { "type": "string", "description": "Version and agent details of the node." }, "peerId": { "type": "string", "description": "Peer ID of the node." }, "startedAt": { "type": "string", "format": "uint64", "description": "Unix timestamp when the node was started (UTC)." }, "reachability": { "type": "string", "description": "Reachability status of the node." }, "services": { "type": "integer", "format": "int32", "description": "Bitfield representing the services provided by the node." }, "servicesNames": { "type": "string", "description": "Names of services provided by the node." }, "localAddrs": { "type": "array", "items": { "type": "string" }, "description": "List of addresses associated with the node." }, "protocols": { "type": "array", "items": { "type": "string" }, "description": "List of protocols supported by the node." }, "clockOffset": { "type": "number", "format": "double", "description": "Offset between the node's clock and the network's clock (in seconds)." }, "connectionInfo": { "$ref": "#/definitions/pactusConnectionInfo", "description": "Information about the node's connections." }, "zmqPublishers": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusZMQPublisherInfo" }, "description": "List of active ZeroMQ publishers." }, "currentTime": { "type": "string", "format": "uint64", "description": "Current Unix timestamp of the node (UTC)." }, "networkName": { "type": "string", "description": "Name of the P2P network." } }, "description": "Response message contains information about a specific node in the network." }, "pactusGetPublicKeyResponse": { "type": "object", "properties": { "publicKey": { "type": "string", "description": "The public key associated with the provided address." } }, "description": "Response message contains public key information." }, "pactusGetRawBatchTransferTransactionRequest": { "type": "object", "properties": { "lockTime": { "type": "integer", "format": "int64", "description": "The lock time for the transaction. If not set, defaults to the last block height." }, "sender": { "type": "string", "description": "The sender's account address." }, "recipients": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusRecipient" }, "description": "The list of recipients with their amounts. Minimum 2 recipients required." }, "fee": { "type": "string", "format": "int64", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee." }, "memo": { "type": "string", "description": "A memo string for the transaction." } }, "description": "Request message for retrieving raw details of a batch transfer transaction." }, "pactusGetRawBondTransactionRequest": { "type": "object", "properties": { "lockTime": { "type": "integer", "format": "int64", "description": "The lock time for the transaction. If not set, defaults to the last block height." }, "sender": { "type": "string", "description": "The sender's account address." }, "receiver": { "type": "string", "description": "The receiver's validator address." }, "stake": { "type": "string", "format": "int64", "description": "The stake amount in NanoPAC. Must be greater than 0." }, "publicKey": { "type": "string", "title": "The public key of the validator.\nOptional, but required when registering a new validator.;" }, "fee": { "type": "string", "format": "int64", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee." }, "memo": { "type": "string", "description": "A memo string for the transaction." }, "delegateOwner": { "type": "string", "title": "The address of the delegate owner.\nOptional, but required when registering a new validator with delegation.;" }, "delegateShare": { "type": "string", "format": "int64", "description": "The share percentage for the delegate owner.\nOptional, but required when registering a new validator with delegation.;\nMust be between 0 and 0.7 PAC in nano PAC." }, "delegateExpiry": { "type": "integer", "format": "int64", "title": "The expiry height for the delegate relationship.\nOptional, but required when registering a new validator with delegation.;" } }, "description": "Request message for retrieving raw details of a bond transaction." }, "pactusGetRawTransactionResponse": { "type": "object", "properties": { "rawTransaction": { "type": "string", "description": "The raw transaction data in hexadecimal format." }, "id": { "type": "string", "description": "The unique ID of the transaction." } }, "description": "Response message contains raw transaction data." }, "pactusGetRawTransferTransactionRequest": { "type": "object", "properties": { "lockTime": { "type": "integer", "format": "int64", "description": "The lock time for the transaction. If not set, defaults to the last block height." }, "sender": { "type": "string", "description": "The sender's account address." }, "receiver": { "type": "string", "description": "The receiver's account address." }, "amount": { "type": "string", "format": "int64", "description": "The amount to be transferred, specified in NanoPAC. Must be greater than 0." }, "fee": { "type": "string", "format": "int64", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee." }, "memo": { "type": "string", "description": "A memo string for the transaction." } }, "description": "Request message for retrieving raw details of a transfer transaction." }, "pactusGetRawUnbondTransactionRequest": { "type": "object", "properties": { "lockTime": { "type": "integer", "format": "int64", "description": "The lock time for the transaction. If not set, defaults to the last block height." }, "validatorAddress": { "type": "string", "description": "The address of the validator to unbond from." }, "memo": { "type": "string", "description": "A memo string for the transaction." }, "delegateOwner": { "type": "string", "title": "The address of the delegate owner.\nOptional, but required when the validator is a delegated validator.;" } }, "description": "Request message for retrieving raw details of an unbond transaction." }, "pactusGetRawWithdrawTransactionRequest": { "type": "object", "properties": { "lockTime": { "type": "integer", "format": "int64", "description": "The lock time for the transaction. If not set, defaults to the last block height." }, "validatorAddress": { "type": "string", "description": "The address of the validator to withdraw from." }, "accountAddress": { "type": "string", "description": "The address of the account to withdraw to." }, "amount": { "type": "string", "format": "int64", "description": "The withdrawal amount in NanoPAC. Must be greater than 0." }, "fee": { "type": "string", "format": "int64", "description": "The transaction fee in NanoPAC. If not set, it is set to the estimated fee." }, "memo": { "type": "string", "description": "A memo string for the transaction." } }, "description": "Request message for retrieving raw details of a withdraw transaction." }, "pactusGetTotalBalanceResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the queried wallet." }, "totalBalance": { "type": "string", "format": "int64", "description": "The total balance of the wallet in NanoPAC." } }, "description": "Response message contains the total available balance of the wallet." }, "pactusGetTotalStakeResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the queried wallet." }, "totalStake": { "type": "string", "format": "int64", "description": "The total stake amount in NanoPAC." } }, "description": "Response message contains the total stake of the wallet." }, "pactusGetTransactionResponse": { "type": "object", "properties": { "blockHeight": { "type": "integer", "format": "int64", "description": "The height of the block containing the transaction." }, "blockTime": { "type": "integer", "format": "int64", "description": "The UNIX timestamp of the block containing the transaction." }, "transaction": { "$ref": "#/definitions/pactusTransactionInfo", "description": "Detailed information about the transaction." } }, "description": "Response message contains details of a transaction." }, "pactusGetTxPoolContentResponse": { "type": "object", "properties": { "txs": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusTransactionInfo" }, "description": "List of transactions currently in the pool." } }, "description": "Response message contains transactions in the transaction pool." }, "pactusGetValidatorAddressResponse": { "type": "object", "properties": { "address": { "type": "string", "description": "The validator address associated with the public key." } }, "description": "Response message containing the validator address corresponding to a public key." }, "pactusGetValidatorAddressesResponse": { "type": "object", "properties": { "addresses": { "type": "array", "items": { "type": "string" }, "description": "List of validator addresses." } }, "description": "Response message contains list of validator addresses." }, "pactusGetValidatorResponse": { "type": "object", "properties": { "validator": { "$ref": "#/definitions/pactusValidatorInfo", "description": "Detailed information about the validator." } }, "description": "Response message contains validator information." }, "pactusGetWalletInfoResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet." }, "version": { "type": "integer", "format": "int32", "description": "The wallet format version." }, "network": { "type": "string", "description": "The network the wallet is connected to (e.g., mainnet, testnet)." }, "encrypted": { "type": "boolean", "description": "Indicates if the wallet is encrypted." }, "uuid": { "type": "string", "description": "A unique identifier of the wallet." }, "createdAt": { "type": "string", "format": "int64", "description": "Unix timestamp of wallet creation." }, "defaultFee": { "type": "string", "format": "int64", "description": "The default fee of the wallet." }, "driver": { "type": "string", "description": "The storage driver used by the wallet (e.g., SQLite, Legacy JSON )." }, "path": { "type": "string", "description": "Path to the wallet file or storage location." } }, "description": "Response message contains wallet details." }, "pactusListAddressesResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the queried wallet." }, "addrs": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusAddressInfo" }, "description": "List of all addresses in the wallet with their details." } }, "description": "Response message contains wallet addresses." }, "pactusListTransactionsResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet queried." }, "txs": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusWalletTransactionInfo" }, "description": "List of transactions for the wallet, filtered by the specified address if provided." } }, "description": "Response message containing a list of transactions." }, "pactusListWalletsResponse": { "type": "object", "properties": { "wallets": { "type": "array", "items": { "type": "string" }, "description": "Array of wallet names." } }, "description": "Response message contains wallet names." }, "pactusLoadWalletRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet to load." } }, "description": "Request message for loading an existing wallet.\nDeprecated: It will be removed in a future version." }, "pactusLoadWalletResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the loaded wallet." } }, "description": "Response message confirming wallet loaded.\nDeprecated: It will be removed in a future version." }, "pactusMetricInfo": { "type": "object", "properties": { "totalInvalid": { "$ref": "#/definitions/pactusCounterInfo", "description": "Total number of invalid bundles." }, "totalSent": { "$ref": "#/definitions/pactusCounterInfo", "description": "Total number of bundles sent." }, "totalReceived": { "$ref": "#/definitions/pactusCounterInfo", "description": "Total number of bundles received." }, "messageSent": { "type": "object", "additionalProperties": { "$ref": "#/definitions/pactusCounterInfo" }, "description": "Number of sent bundles categorized by message type." }, "messageReceived": { "type": "object", "additionalProperties": { "$ref": "#/definitions/pactusCounterInfo" }, "description": "Number of received bundles categorized by message type." } }, "description": "MetricInfo contains metrics data regarding network activity." }, "pactusPayloadBatchTransfer": { "type": "object", "properties": { "sender": { "type": "string", "description": "The sender's address." }, "recipients": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/pactusRecipient" }, "description": "The list of recipients with their amounts." } }, "description": "Payload for a batch transfer transaction." }, "pactusPayloadBond": { "type": "object", "properties": { "sender": { "type": "string", "description": "The sender's address." }, "receiver": { "type": "string", "description": "The receiver's address." }, "stake": { "type": "string", "format": "int64", "description": "The stake amount in NanoPAC." }, "publicKey": { "type": "string", "description": "The public key of the validator." }, "isDelegated": { "type": "boolean", "description": "Indicates whether the bond transaction is a delegation." }, "delegateOwner": { "type": "string", "title": "The address of the delegate owner.\nOptional, but required when registering a new validator with delegation.;" }, "delegateShare": { "type": "string", "format": "int64", "description": "The share percentage for the delegate owner.\nOptional, but required when registering a new validator with delegation.;\nMust be between 0 and 0.7 PAC in nano PAC." }, "delegateExpiry": { "type": "integer", "format": "int64", "title": "The expiry height for the delegate relationship.\nOptional, but required when registering a new validator with delegation.;" } }, "description": "Payload for a bond transaction." }, "pactusPayloadSortition": { "type": "object", "properties": { "address": { "type": "string", "description": "The validator address associated with the sortition proof." }, "proof": { "type": "string", "description": "The proof for the sortition." } }, "description": "Payload for a sortition transaction." }, "pactusPayloadTransfer": { "type": "object", "properties": { "sender": { "type": "string", "description": "The sender's address." }, "receiver": { "type": "string", "description": "The receiver's address." }, "amount": { "type": "string", "format": "int64", "description": "The amount to be transferred in NanoPAC." } }, "description": "Payload for a transfer transaction." }, "pactusPayloadType": { "type": "string", "enum": [ "PAYLOAD_TYPE_UNSPECIFIED", "PAYLOAD_TYPE_TRANSFER", "PAYLOAD_TYPE_BOND", "PAYLOAD_TYPE_SORTITION", "PAYLOAD_TYPE_UNBOND", "PAYLOAD_TYPE_WITHDRAW", "PAYLOAD_TYPE_BATCH_TRANSFER" ], "default": "PAYLOAD_TYPE_UNSPECIFIED", "description": "Enumeration for different types of transaction payloads.\n\n - PAYLOAD_TYPE_UNSPECIFIED: Unspecified payload type.\n - PAYLOAD_TYPE_TRANSFER: Transfer payload type.\n - PAYLOAD_TYPE_BOND: Bond payload type.\n - PAYLOAD_TYPE_SORTITION: Sortition payload type.\n - PAYLOAD_TYPE_UNBOND: Unbond payload type.\n - PAYLOAD_TYPE_WITHDRAW: Withdraw payload type.\n - PAYLOAD_TYPE_BATCH_TRANSFER: Batch transfer payload type." }, "pactusPayloadUnbond": { "type": "object", "properties": { "validator": { "type": "string", "description": "The address of the validator to unbond from." }, "delegateOwner": { "type": "string", "title": "The address of the delegate owner.\nOptional, but required when the validator is a delegated validator.;" } }, "description": "Payload for an unbond transaction." }, "pactusPayloadWithdraw": { "type": "object", "properties": { "validatorAddress": { "type": "string", "description": "The address of the validator to withdraw from." }, "accountAddress": { "type": "string", "description": "The address of the account to withdraw to." }, "amount": { "type": "string", "format": "int64", "description": "The withdrawal amount in NanoPAC." } }, "description": "Payload for a withdraw transaction." }, "pactusPingResponse": { "type": "object", "description": "Response message for ping - intentionally empty for measuring round-trip time.\n\nEmpty response payload for measuring round-trip time" }, "pactusProposalInfo": { "type": "object", "properties": { "height": { "type": "integer", "format": "int64", "description": "The height of the proposal." }, "round": { "type": "integer", "format": "int32", "description": "The round of the proposal." }, "blockData": { "type": "string", "description": "The block data of the proposal." }, "signature": { "type": "string", "description": "The signature of the proposal, signed by the proposer." } }, "description": "Message contains information about a proposal." }, "pactusPublicKeyAggregationRequest": { "type": "object", "properties": { "publicKeys": { "type": "array", "items": { "type": "string" }, "description": "List of BLS public keys to be aggregated." } }, "description": "Request message for aggregating multiple BLS public keys." }, "pactusPublicKeyAggregationResponse": { "type": "object", "properties": { "publicKey": { "type": "string", "description": "The aggregated BLS public key." }, "address": { "type": "string", "description": "The blockchain address derived from the aggregated public key." } }, "description": "Response message contains the aggregated BLS public key result." }, "pactusRecipient": { "type": "object", "properties": { "receiver": { "type": "string", "description": "The receiver's address." }, "amount": { "type": "string", "format": "int64", "description": "The amount in NanoPAC." } }, "description": "Recipient is receiver with amount." }, "pactusRestoreWalletRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name for the restored wallet." }, "mnemonic": { "type": "string", "description": "The mnemonic (seed phrase) for wallet recovery." }, "password": { "type": "string", "description": "Password to secure the restored wallet." } }, "description": "Request message for restoring a wallet from mnemonic (seed phrase)." }, "pactusRestoreWalletResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the restored wallet." } }, "description": "Response message confirming wallet restoration." }, "pactusSetAddressLabelResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet where the address label was updated." }, "address": { "type": "string", "description": "The address where the label was updated." }, "label": { "type": "string", "description": "The new label for the address." } }, "description": "Response message for updated address label." }, "pactusSignMessageRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet to sign with." }, "password": { "type": "string", "description": "Wallet password required for signing." }, "address": { "type": "string", "description": "The address whose private key should be used for signing the message." }, "message": { "type": "string", "description": "The arbitrary message to be signed." } }, "description": "Request message to sign an arbitrary message." }, "pactusSignMessageResponse": { "type": "object", "properties": { "signature": { "type": "string", "description": "The signature in hexadecimal format." } }, "description": "Response message contains message signature." }, "pactusSignMessageWithPrivateKeyRequest": { "type": "object", "properties": { "privateKey": { "type": "string", "description": "The private key to sign the message." }, "message": { "type": "string", "description": "The message content to be signed." } }, "description": "Request message for signing a message with a private key." }, "pactusSignMessageWithPrivateKeyResponse": { "type": "object", "properties": { "signature": { "type": "string", "description": "The resulting signature in hexadecimal format." } }, "description": "Response message contains the signature generated from the message." }, "pactusSignRawTransactionRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet used for signing." }, "rawTransaction": { "type": "string", "description": "The raw transaction data to be signed." }, "password": { "type": "string", "description": "Wallet password required for signing." } }, "description": "Request message for signing a raw transaction." }, "pactusSignRawTransactionResponse": { "type": "object", "properties": { "transactionId": { "type": "string", "description": "The ID of the signed transaction." }, "signedRawTransaction": { "type": "string", "description": "The signed raw transaction data." } }, "description": "Response message contains the transaction ID and signed raw transaction." }, "pactusSignatureAggregationRequest": { "type": "object", "properties": { "signatures": { "type": "array", "items": { "type": "string" }, "description": "List of BLS signatures to be aggregated." } }, "description": "Request message for aggregating multiple BLS signatures." }, "pactusSignatureAggregationResponse": { "type": "object", "properties": { "signature": { "type": "string", "description": "The aggregated BLS signature in hexadecimal format." } }, "description": "Response message contains the aggregated BLS signature." }, "pactusTransactionInfo": { "type": "object", "properties": { "id": { "type": "string", "description": "The unique ID of the transaction." }, "data": { "type": "string", "description": "The raw transaction data in hexadecimal format." }, "version": { "type": "integer", "format": "int32", "description": "The version of the transaction." }, "lockTime": { "type": "integer", "format": "int64", "description": "The lock time for the transaction." }, "value": { "type": "string", "format": "int64", "description": "The value of the transaction in NanoPAC." }, "fee": { "type": "string", "format": "int64", "description": "The fee for the transaction in NanoPAC." }, "payloadType": { "$ref": "#/definitions/pactusPayloadType", "description": "The type of transaction payload." }, "transfer": { "$ref": "#/definitions/pactusPayloadTransfer", "description": "Transfer transaction payload." }, "bond": { "$ref": "#/definitions/pactusPayloadBond", "description": "Bond transaction payload." }, "sortition": { "$ref": "#/definitions/pactusPayloadSortition", "description": "Sortition transaction payload." }, "unbond": { "$ref": "#/definitions/pactusPayloadUnbond", "description": "Unbond transaction payload." }, "withdraw": { "$ref": "#/definitions/pactusPayloadWithdraw", "description": "Withdraw transaction payload." }, "batchTransfer": { "$ref": "#/definitions/pactusPayloadBatchTransfer", "description": "Batch Transfer transaction payload." }, "memo": { "type": "string", "description": "A memo string for the transaction." }, "publicKey": { "type": "string", "description": "The public key associated with the transaction." }, "signature": { "type": "string", "description": "The signature for the transaction." }, "blockHeight": { "type": "integer", "format": "int64", "description": "The block height containing the transaction.\nA value of zero means the transaction is unconfirmed and may still in the transaction pool." }, "confirmed": { "type": "boolean", "description": "Indicates whether the transaction is confirmed." }, "confirmations": { "type": "integer", "format": "int32", "description": "The number of blocks that have been added to the chain after this transaction was included in a block.\nA value of zero means the transaction is unconfirmed and may still in the transaction pool." } }, "description": "Information about a transaction." }, "pactusTransactionStatus": { "type": "string", "enum": [ "TRANSACTION_STATUS_PENDING", "TRANSACTION_STATUS_CONFIRMED", "TRANSACTION_STATUS_FAILED" ], "default": "TRANSACTION_STATUS_PENDING", "description": "TransactionStatus defines the status of a transaction.\n\n - TRANSACTION_STATUS_PENDING: Pending status for transactions in the mempool.\n - TRANSACTION_STATUS_CONFIRMED: Confirmed status for transactions included in a block.\n - TRANSACTION_STATUS_FAILED: Failed status for transactions that were not successful." }, "pactusTransactionVerbosity": { "type": "string", "enum": [ "TRANSACTION_VERBOSITY_DATA", "TRANSACTION_VERBOSITY_INFO" ], "default": "TRANSACTION_VERBOSITY_DATA", "description": "Enumeration for verbosity levels when requesting transaction details.\n\n - TRANSACTION_VERBOSITY_DATA: Request transaction data only.\n - TRANSACTION_VERBOSITY_INFO: Request detailed transaction information." }, "pactusTxDirection": { "type": "string", "enum": [ "TX_DIRECTION_ANY", "TX_DIRECTION_INCOMING", "TX_DIRECTION_OUTGOING" ], "default": "TX_DIRECTION_ANY", "description": "TxDirection indicates the direction of a transaction relative to the wallet.\n\n - TX_DIRECTION_ANY: include both incoming and outgoing transactions.\n - TX_DIRECTION_INCOMING: Include only incoming transactions where the wallet receives funds.\n - TX_DIRECTION_OUTGOING: Include only outgoing transactions where the wallet sends funds." }, "pactusUnloadWalletRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet to unload." } }, "description": "Request message for unloading a wallet.\nDeprecated: It will be removed in a future version." }, "pactusUnloadWalletResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the unloaded wallet." } }, "description": "Response message confirming wallet unloading.\nDeprecated: It will be removed in a future version." }, "pactusUpdatePasswordRequest": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet whose password will be updated." }, "oldPassword": { "type": "string", "description": "The current wallet password." }, "newPassword": { "type": "string", "description": "The new wallet password." } }, "description": "Request message for updating wallet password." }, "pactusUpdatePasswordResponse": { "type": "object", "properties": { "walletName": { "type": "string", "description": "The name of the wallet whose password was updated." } }, "description": "Response message confirming wallet password update." }, "pactusValidatorInfo": { "type": "object", "properties": { "hash": { "type": "string", "description": "The hash of the validator." }, "data": { "type": "string", "description": "The serialized data of the validator." }, "publicKey": { "type": "string", "description": "The public key of the validator." }, "number": { "type": "integer", "format": "int32", "description": "The unique number assigned to the validator." }, "stake": { "type": "string", "format": "int64", "description": "The stake of the validator in NanoPAC." }, "lastBondingHeight": { "type": "integer", "format": "int64", "description": "The height at which the validator last bonded." }, "lastSortitionHeight": { "type": "integer", "format": "int64", "description": "The height at which the validator last participated in sortition." }, "unbondingHeight": { "type": "integer", "format": "int64", "description": "The height at which the validator will unbond." }, "address": { "type": "string", "description": "The address of the validator." }, "availabilityScore": { "type": "number", "format": "double", "description": "The availability score of the validator." }, "protocolVersion": { "type": "integer", "format": "int32", "description": "The protocol version of the validator." }, "isDelegated": { "type": "boolean", "description": "Whether the validator is delegated." }, "delegateOwner": { "type": "string", "description": "The address of the stake owner of the validator." }, "delegateShare": { "type": "string", "format": "int64", "description": "The share of the stake owner of the validator." }, "delegateExpiry": { "type": "integer", "format": "int64", "description": "The expiry of the stake owner of the validator." } }, "description": "Message contains information about a validator." }, "pactusVerifyMessageRequest": { "type": "object", "properties": { "message": { "type": "string", "description": "The original message content that was signed." }, "signature": { "type": "string", "description": "The signature to verify in hexadecimal format." }, "publicKey": { "type": "string", "description": "The public key of the signer." } }, "description": "Request message for verifying a message signature." }, "pactusVerifyMessageResponse": { "type": "object", "properties": { "isValid": { "type": "boolean", "description": "Boolean indicating whether the signature is valid for the given message and public key." } }, "description": "Response message contains the verification result." }, "pactusVoteInfo": { "type": "object", "properties": { "type": { "$ref": "#/definitions/pactusVoteType", "description": "The type of the vote." }, "voter": { "type": "string", "description": "The address of the voter." }, "blockHash": { "type": "string", "description": "The hash of the block being voted on." }, "round": { "type": "integer", "format": "int32", "description": "The consensus round of the vote." }, "cpRound": { "type": "integer", "format": "int32", "description": "The change-proposer round of the vote." }, "cpValue": { "type": "integer", "format": "int32", "description": "The change-proposer value of the vote." } }, "description": "Message contains information about a vote." }, "pactusVoteType": { "type": "string", "enum": [ "VOTE_TYPE_UNSPECIFIED", "VOTE_TYPE_PREPARE", "VOTE_TYPE_PRECOMMIT", "VOTE_TYPE_CP_PRE_VOTE", "VOTE_TYPE_CP_MAIN_VOTE", "VOTE_TYPE_CP_DECIDED" ], "default": "VOTE_TYPE_UNSPECIFIED", "description": "Enumeration for types of votes.\n\n - VOTE_TYPE_UNSPECIFIED: Unspecified vote type.\n - VOTE_TYPE_PREPARE: Prepare vote type.\n - VOTE_TYPE_PRECOMMIT: Precommit vote type.\n - VOTE_TYPE_CP_PRE_VOTE: Change-proposer:pre-vote vote type.\n - VOTE_TYPE_CP_MAIN_VOTE: Change-proposer:main-vote vote type.\n - VOTE_TYPE_CP_DECIDED: Change-proposer:decided vote type." }, "pactusWalletTransactionInfo": { "type": "object", "properties": { "no": { "type": "string", "format": "int64", "description": "A sequence number for the transaction in the wallet." }, "txId": { "type": "string", "description": "The unique ID of the transaction." }, "sender": { "type": "string", "description": "The sender's address." }, "receiver": { "type": "string", "description": "The receiver's address." }, "direction": { "$ref": "#/definitions/pactusTxDirection", "description": "The direction of the transaction relative to the wallet." }, "amount": { "type": "string", "format": "int64", "description": "The amount involved in the transaction in NanoPAC." }, "fee": { "type": "string", "format": "int64", "description": "The transaction fee in NanoPAC." }, "memo": { "type": "string", "description": "A memo string for the transaction." }, "status": { "$ref": "#/definitions/pactusTransactionStatus", "description": "The current status of the transaction." }, "blockHeight": { "type": "integer", "format": "int64", "description": "The block height containing the transaction." }, "payloadType": { "$ref": "#/definitions/pactusPayloadType", "description": "The type of transaction payload." }, "data": { "type": "string", "format": "byte", "description": "The raw transaction data." }, "comment": { "type": "string", "description": "A comment associated with the transaction in the wallet." }, "createdAt": { "type": "string", "format": "int64", "description": "Unix timestamp of when the transaction was created." }, "updatedAt": { "type": "string", "format": "int64", "description": "Unix timestamp of when the transaction was last updated." } }, "description": "WalletTransactionInfo contains information about a transaction in a wallet." }, "pactusZMQPublisherInfo": { "type": "object", "properties": { "topic": { "type": "string", "description": "The topic associated with the publisher." }, "address": { "type": "string", "description": "The address of the publisher." }, "hwm": { "type": "integer", "format": "int32", "description": "The high-water mark (HWM) for the publisher, indicating the\nmaximum number of messages to queue before dropping older ones." } }, "description": "ZMQPublisherInfo contains information about a ZeroMQ publisher." }, "protobufAny": { "type": "object", "properties": { "@type": { "type": "string" } }, "additionalProperties": {} }, "rpcStatus": { "type": "object", "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/protobufAny" } } } } }, "securityDefinitions": { "BasicAuth": { "type": "basic" } }, "security": [ { "BasicAuth": [] } ] } ================================================ FILE: www/http/swagger-ui/swagger-initializer.js ================================================ window.onload = function() { // // the following lines will be replaced by docker/configurator, when it runs in a docker-container window.ui = SwaggerUIBundle({ url: "pactus.swagger.json", dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); // }; ================================================ FILE: www/http/swagger-ui/swagger-ui-bundle.js ================================================ /*! For license information please see swagger-ui-bundle.js.LICENSE.txt */ !function webpackUniversalModuleDefinition(s,i){"object"==typeof exports&&"object"==typeof module?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.SwaggerUIBundle=i():s.SwaggerUIBundle=i()}(this,(()=>(()=>{var s,i,u={69119:(s,i)=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BLANK_URL=i.relativeFirstCharacters=i.urlSchemeRegex=i.ctrlCharactersRegex=i.htmlCtrlEntityRegex=i.htmlEntitiesRegex=i.invalidProtocolRegex=void 0,i.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im,i.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g,i.htmlCtrlEntityRegex=/&(newline|tab);/gi,i.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,i.urlSchemeRegex=/^.+(:|:)/gim,i.relativeFirstCharacters=[".","/"],i.BLANK_URL="about:blank"},16750:(s,i,u)=>{"use strict";i.J=void 0;var _=u(69119);i.J=function sanitizeUrl(s){if(!s)return _.BLANK_URL;var i,u,w=s;do{i=(w=(u=w,u.replace(_.ctrlCharactersRegex,"").replace(_.htmlEntitiesRegex,(function(s,i){return String.fromCharCode(i)}))).replace(_.htmlCtrlEntityRegex,"").replace(_.ctrlCharactersRegex,"").trim()).match(_.ctrlCharactersRegex)||w.match(_.htmlEntitiesRegex)||w.match(_.htmlCtrlEntityRegex)}while(i&&i.length>0);var x=w;if(!x)return _.BLANK_URL;if(function isRelativeUrlWithoutProtocol(s){return _.relativeFirstCharacters.indexOf(s[0])>-1}(x))return x;var j=x.match(_.urlSchemeRegex);if(!j)return x;var P=j[0];return _.invalidProtocolRegex.test(P)?_.BLANK_URL:x}},67526:(s,i)=>{"use strict";i.byteLength=function byteLength(s){var i=getLens(s),u=i[0],_=i[1];return 3*(u+_)/4-_},i.toByteArray=function toByteArray(s){var i,u,x=getLens(s),j=x[0],P=x[1],B=new w(function _byteLength(s,i,u){return 3*(i+u)/4-u}(0,j,P)),$=0,U=P>0?j-4:j;for(u=0;u>16&255,B[$++]=i>>8&255,B[$++]=255&i;2===P&&(i=_[s.charCodeAt(u)]<<2|_[s.charCodeAt(u+1)]>>4,B[$++]=255&i);1===P&&(i=_[s.charCodeAt(u)]<<10|_[s.charCodeAt(u+1)]<<4|_[s.charCodeAt(u+2)]>>2,B[$++]=i>>8&255,B[$++]=255&i);return B},i.fromByteArray=function fromByteArray(s){for(var i,_=s.length,w=_%3,x=[],j=16383,P=0,B=_-w;PB?B:P+j));1===w?(i=s[_-1],x.push(u[i>>2]+u[i<<4&63]+"==")):2===w&&(i=(s[_-2]<<8)+s[_-1],x.push(u[i>>10]+u[i>>4&63]+u[i<<2&63]+"="));return x.join("")};for(var u=[],_=[],w="undefined"!=typeof Uint8Array?Uint8Array:Array,x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",j=0;j<64;++j)u[j]=x[j],_[x.charCodeAt(j)]=j;function getLens(s){var i=s.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var u=s.indexOf("=");return-1===u&&(u=i),[u,u===i?0:4-u%4]}function encodeChunk(s,i,_){for(var w,x,j=[],P=i;P<_;P+=3)w=(s[P]<<16&16711680)+(s[P+1]<<8&65280)+(255&s[P+2]),j.push(u[(x=w)>>18&63]+u[x>>12&63]+u[x>>6&63]+u[63&x]);return j.join("")}_["-".charCodeAt(0)]=62,_["_".charCodeAt(0)]=63},48287:(s,i,u)=>{"use strict";const _=u(67526),w=u(251),x="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;i.Buffer=Buffer,i.SlowBuffer=function SlowBuffer(s){+s!=s&&(s=0);return Buffer.alloc(+s)},i.INSPECT_MAX_BYTES=50;const j=2147483647;function createBuffer(s){if(s>j)throw new RangeError('The value "'+s+'" is invalid for option "size"');const i=new Uint8Array(s);return Object.setPrototypeOf(i,Buffer.prototype),i}function Buffer(s,i,u){if("number"==typeof s){if("string"==typeof i)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(s)}return from(s,i,u)}function from(s,i,u){if("string"==typeof s)return function fromString(s,i){"string"==typeof i&&""!==i||(i="utf8");if(!Buffer.isEncoding(i))throw new TypeError("Unknown encoding: "+i);const u=0|byteLength(s,i);let _=createBuffer(u);const w=_.write(s,i);w!==u&&(_=_.slice(0,w));return _}(s,i);if(ArrayBuffer.isView(s))return function fromArrayView(s){if(isInstance(s,Uint8Array)){const i=new Uint8Array(s);return fromArrayBuffer(i.buffer,i.byteOffset,i.byteLength)}return fromArrayLike(s)}(s);if(null==s)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(isInstance(s,ArrayBuffer)||s&&isInstance(s.buffer,ArrayBuffer))return fromArrayBuffer(s,i,u);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(s,SharedArrayBuffer)||s&&isInstance(s.buffer,SharedArrayBuffer)))return fromArrayBuffer(s,i,u);if("number"==typeof s)throw new TypeError('The "value" argument must not be of type number. Received type number');const _=s.valueOf&&s.valueOf();if(null!=_&&_!==s)return Buffer.from(_,i,u);const w=function fromObject(s){if(Buffer.isBuffer(s)){const i=0|checked(s.length),u=createBuffer(i);return 0===u.length||s.copy(u,0,0,i),u}if(void 0!==s.length)return"number"!=typeof s.length||numberIsNaN(s.length)?createBuffer(0):fromArrayLike(s);if("Buffer"===s.type&&Array.isArray(s.data))return fromArrayLike(s.data)}(s);if(w)return w;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof s[Symbol.toPrimitive])return Buffer.from(s[Symbol.toPrimitive]("string"),i,u);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}function assertSize(s){if("number"!=typeof s)throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function allocUnsafe(s){return assertSize(s),createBuffer(s<0?0:0|checked(s))}function fromArrayLike(s){const i=s.length<0?0:0|checked(s.length),u=createBuffer(i);for(let _=0;_=j)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+j.toString(16)+" bytes");return 0|s}function byteLength(s,i){if(Buffer.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||isInstance(s,ArrayBuffer))return s.byteLength;if("string"!=typeof s)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const u=s.length,_=arguments.length>2&&!0===arguments[2];if(!_&&0===u)return 0;let w=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return u;case"utf8":case"utf-8":return utf8ToBytes(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*u;case"hex":return u>>>1;case"base64":return base64ToBytes(s).length;default:if(w)return _?-1:utf8ToBytes(s).length;i=(""+i).toLowerCase(),w=!0}}function slowToString(s,i,u){let _=!1;if((void 0===i||i<0)&&(i=0),i>this.length)return"";if((void 0===u||u>this.length)&&(u=this.length),u<=0)return"";if((u>>>=0)<=(i>>>=0))return"";for(s||(s="utf8");;)switch(s){case"hex":return hexSlice(this,i,u);case"utf8":case"utf-8":return utf8Slice(this,i,u);case"ascii":return asciiSlice(this,i,u);case"latin1":case"binary":return latin1Slice(this,i,u);case"base64":return base64Slice(this,i,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,i,u);default:if(_)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),_=!0}}function swap(s,i,u){const _=s[i];s[i]=s[u],s[u]=_}function bidirectionalIndexOf(s,i,u,_,w){if(0===s.length)return-1;if("string"==typeof u?(_=u,u=0):u>2147483647?u=2147483647:u<-2147483648&&(u=-2147483648),numberIsNaN(u=+u)&&(u=w?0:s.length-1),u<0&&(u=s.length+u),u>=s.length){if(w)return-1;u=s.length-1}else if(u<0){if(!w)return-1;u=0}if("string"==typeof i&&(i=Buffer.from(i,_)),Buffer.isBuffer(i))return 0===i.length?-1:arrayIndexOf(s,i,u,_,w);if("number"==typeof i)return i&=255,"function"==typeof Uint8Array.prototype.indexOf?w?Uint8Array.prototype.indexOf.call(s,i,u):Uint8Array.prototype.lastIndexOf.call(s,i,u):arrayIndexOf(s,[i],u,_,w);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(s,i,u,_,w){let x,j=1,P=s.length,B=i.length;if(void 0!==_&&("ucs2"===(_=String(_).toLowerCase())||"ucs-2"===_||"utf16le"===_||"utf-16le"===_)){if(s.length<2||i.length<2)return-1;j=2,P/=2,B/=2,u/=2}function read(s,i){return 1===j?s[i]:s.readUInt16BE(i*j)}if(w){let _=-1;for(x=u;xP&&(u=P-B),x=u;x>=0;x--){let u=!0;for(let _=0;_w&&(_=w):_=w;const x=i.length;let j;for(_>x/2&&(_=x/2),j=0;j<_;++j){const _=parseInt(i.substr(2*j,2),16);if(numberIsNaN(_))return j;s[u+j]=_}return j}function utf8Write(s,i,u,_){return blitBuffer(utf8ToBytes(i,s.length-u),s,u,_)}function asciiWrite(s,i,u,_){return blitBuffer(function asciiToBytes(s){const i=[];for(let u=0;u>8,w=u%256,x.push(w),x.push(_);return x}(i,s.length-u),s,u,_)}function base64Slice(s,i,u){return 0===i&&u===s.length?_.fromByteArray(s):_.fromByteArray(s.slice(i,u))}function utf8Slice(s,i,u){u=Math.min(s.length,u);const _=[];let w=i;for(;w239?4:i>223?3:i>191?2:1;if(w+j<=u){let u,_,P,B;switch(j){case 1:i<128&&(x=i);break;case 2:u=s[w+1],128==(192&u)&&(B=(31&i)<<6|63&u,B>127&&(x=B));break;case 3:u=s[w+1],_=s[w+2],128==(192&u)&&128==(192&_)&&(B=(15&i)<<12|(63&u)<<6|63&_,B>2047&&(B<55296||B>57343)&&(x=B));break;case 4:u=s[w+1],_=s[w+2],P=s[w+3],128==(192&u)&&128==(192&_)&&128==(192&P)&&(B=(15&i)<<18|(63&u)<<12|(63&_)<<6|63&P,B>65535&&B<1114112&&(x=B))}}null===x?(x=65533,j=1):x>65535&&(x-=65536,_.push(x>>>10&1023|55296),x=56320|1023&x),_.push(x),w+=j}return function decodeCodePointsArray(s){const i=s.length;if(i<=P)return String.fromCharCode.apply(String,s);let u="",_=0;for(;__.length?(Buffer.isBuffer(i)||(i=Buffer.from(i)),i.copy(_,w)):Uint8Array.prototype.set.call(_,i,w);else{if(!Buffer.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(_,w)}w+=i.length}return _},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const s=this.length;if(s%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let i=0;iu&&(s+=" ... "),""},x&&(Buffer.prototype[x]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(s,i,u,_,w){if(isInstance(s,Uint8Array)&&(s=Buffer.from(s,s.offset,s.byteLength)),!Buffer.isBuffer(s))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof s);if(void 0===i&&(i=0),void 0===u&&(u=s?s.length:0),void 0===_&&(_=0),void 0===w&&(w=this.length),i<0||u>s.length||_<0||w>this.length)throw new RangeError("out of range index");if(_>=w&&i>=u)return 0;if(_>=w)return-1;if(i>=u)return 1;if(this===s)return 0;let x=(w>>>=0)-(_>>>=0),j=(u>>>=0)-(i>>>=0);const P=Math.min(x,j),B=this.slice(_,w),$=s.slice(i,u);for(let s=0;s>>=0,isFinite(u)?(u>>>=0,void 0===_&&(_="utf8")):(_=u,u=void 0)}const w=this.length-i;if((void 0===u||u>w)&&(u=w),s.length>0&&(u<0||i<0)||i>this.length)throw new RangeError("Attempt to write outside buffer bounds");_||(_="utf8");let x=!1;for(;;)switch(_){case"hex":return hexWrite(this,s,i,u);case"utf8":case"utf-8":return utf8Write(this,s,i,u);case"ascii":case"latin1":case"binary":return asciiWrite(this,s,i,u);case"base64":return base64Write(this,s,i,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,s,i,u);default:if(x)throw new TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),x=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const P=4096;function asciiSlice(s,i,u){let _="";u=Math.min(s.length,u);for(let w=i;w_)&&(u=_);let w="";for(let _=i;_u)throw new RangeError("Trying to access beyond buffer length")}function checkInt(s,i,u,_,w,x){if(!Buffer.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>w||is.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(s,i,u,_,w){checkIntBI(i,_,w,s,u,7);let x=Number(i&BigInt(4294967295));s[u++]=x,x>>=8,s[u++]=x,x>>=8,s[u++]=x,x>>=8,s[u++]=x;let j=Number(i>>BigInt(32)&BigInt(4294967295));return s[u++]=j,j>>=8,s[u++]=j,j>>=8,s[u++]=j,j>>=8,s[u++]=j,u}function wrtBigUInt64BE(s,i,u,_,w){checkIntBI(i,_,w,s,u,7);let x=Number(i&BigInt(4294967295));s[u+7]=x,x>>=8,s[u+6]=x,x>>=8,s[u+5]=x,x>>=8,s[u+4]=x;let j=Number(i>>BigInt(32)&BigInt(4294967295));return s[u+3]=j,j>>=8,s[u+2]=j,j>>=8,s[u+1]=j,j>>=8,s[u]=j,u+8}function checkIEEE754(s,i,u,_,w,x){if(u+_>s.length)throw new RangeError("Index out of range");if(u<0)throw new RangeError("Index out of range")}function writeFloat(s,i,u,_,x){return i=+i,u>>>=0,x||checkIEEE754(s,0,u,4),w.write(s,i,u,_,23,4),u+4}function writeDouble(s,i,u,_,x){return i=+i,u>>>=0,x||checkIEEE754(s,0,u,8),w.write(s,i,u,_,52,8),u+8}Buffer.prototype.slice=function slice(s,i){const u=this.length;(s=~~s)<0?(s+=u)<0&&(s=0):s>u&&(s=u),(i=void 0===i?u:~~i)<0?(i+=u)<0&&(i=0):i>u&&(i=u),i>>=0,i>>>=0,u||checkOffset(s,i,this.length);let _=this[s],w=1,x=0;for(;++x>>=0,i>>>=0,u||checkOffset(s,i,this.length);let _=this[s+--i],w=1;for(;i>0&&(w*=256);)_+=this[s+--i]*w;return _},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(s,i){return s>>>=0,i||checkOffset(s,1,this.length),this[s]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(s,i){return s>>>=0,i||checkOffset(s,2,this.length),this[s]|this[s+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(s,i){return s>>>=0,i||checkOffset(s,2,this.length),this[s]<<8|this[s+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(s,i){return s>>>=0,i||checkOffset(s,4,this.length),(this[s]|this[s+1]<<8|this[s+2]<<16)+16777216*this[s+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(s,i){return s>>>=0,i||checkOffset(s,4,this.length),16777216*this[s]+(this[s+1]<<16|this[s+2]<<8|this[s+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(s){validateNumber(s>>>=0,"offset");const i=this[s],u=this[s+7];void 0!==i&&void 0!==u||boundsError(s,this.length-8);const _=i+256*this[++s]+65536*this[++s]+this[++s]*2**24,w=this[++s]+256*this[++s]+65536*this[++s]+u*2**24;return BigInt(_)+(BigInt(w)<>>=0,"offset");const i=this[s],u=this[s+7];void 0!==i&&void 0!==u||boundsError(s,this.length-8);const _=i*2**24+65536*this[++s]+256*this[++s]+this[++s],w=this[++s]*2**24+65536*this[++s]+256*this[++s]+u;return(BigInt(_)<>>=0,i>>>=0,u||checkOffset(s,i,this.length);let _=this[s],w=1,x=0;for(;++x=w&&(_-=Math.pow(2,8*i)),_},Buffer.prototype.readIntBE=function readIntBE(s,i,u){s>>>=0,i>>>=0,u||checkOffset(s,i,this.length);let _=i,w=1,x=this[s+--_];for(;_>0&&(w*=256);)x+=this[s+--_]*w;return w*=128,x>=w&&(x-=Math.pow(2,8*i)),x},Buffer.prototype.readInt8=function readInt8(s,i){return s>>>=0,i||checkOffset(s,1,this.length),128&this[s]?-1*(255-this[s]+1):this[s]},Buffer.prototype.readInt16LE=function readInt16LE(s,i){s>>>=0,i||checkOffset(s,2,this.length);const u=this[s]|this[s+1]<<8;return 32768&u?4294901760|u:u},Buffer.prototype.readInt16BE=function readInt16BE(s,i){s>>>=0,i||checkOffset(s,2,this.length);const u=this[s+1]|this[s]<<8;return 32768&u?4294901760|u:u},Buffer.prototype.readInt32LE=function readInt32LE(s,i){return s>>>=0,i||checkOffset(s,4,this.length),this[s]|this[s+1]<<8|this[s+2]<<16|this[s+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(s,i){return s>>>=0,i||checkOffset(s,4,this.length),this[s]<<24|this[s+1]<<16|this[s+2]<<8|this[s+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(s){validateNumber(s>>>=0,"offset");const i=this[s],u=this[s+7];void 0!==i&&void 0!==u||boundsError(s,this.length-8);const _=this[s+4]+256*this[s+5]+65536*this[s+6]+(u<<24);return(BigInt(_)<>>=0,"offset");const i=this[s],u=this[s+7];void 0!==i&&void 0!==u||boundsError(s,this.length-8);const _=(i<<24)+65536*this[++s]+256*this[++s]+this[++s];return(BigInt(_)<>>=0,i||checkOffset(s,4,this.length),w.read(this,s,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(s,i){return s>>>=0,i||checkOffset(s,4,this.length),w.read(this,s,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(s,i){return s>>>=0,i||checkOffset(s,8,this.length),w.read(this,s,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(s,i){return s>>>=0,i||checkOffset(s,8,this.length),w.read(this,s,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(s,i,u,_){if(s=+s,i>>>=0,u>>>=0,!_){checkInt(this,s,i,u,Math.pow(2,8*u)-1,0)}let w=1,x=0;for(this[i]=255&s;++x>>=0,u>>>=0,!_){checkInt(this,s,i,u,Math.pow(2,8*u)-1,0)}let w=u-1,x=1;for(this[i+w]=255&s;--w>=0&&(x*=256);)this[i+w]=s/x&255;return i+u},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,1,255,0),this[i]=255&s,i+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,2,65535,0),this[i]=255&s,this[i+1]=s>>>8,i+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,2,65535,0),this[i]=s>>>8,this[i+1]=255&s,i+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,4,4294967295,0),this[i+3]=s>>>24,this[i+2]=s>>>16,this[i+1]=s>>>8,this[i]=255&s,i+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,4,4294967295,0),this[i]=s>>>24,this[i+1]=s>>>16,this[i+2]=s>>>8,this[i+3]=255&s,i+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(s,i=0){return wrtBigUInt64LE(this,s,i,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(s,i=0){return wrtBigUInt64BE(this,s,i,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeIntLE=function writeIntLE(s,i,u,_){if(s=+s,i>>>=0,!_){const _=Math.pow(2,8*u-1);checkInt(this,s,i,u,_-1,-_)}let w=0,x=1,j=0;for(this[i]=255&s;++w>0)-j&255;return i+u},Buffer.prototype.writeIntBE=function writeIntBE(s,i,u,_){if(s=+s,i>>>=0,!_){const _=Math.pow(2,8*u-1);checkInt(this,s,i,u,_-1,-_)}let w=u-1,x=1,j=0;for(this[i+w]=255&s;--w>=0&&(x*=256);)s<0&&0===j&&0!==this[i+w+1]&&(j=1),this[i+w]=(s/x>>0)-j&255;return i+u},Buffer.prototype.writeInt8=function writeInt8(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,1,127,-128),s<0&&(s=255+s+1),this[i]=255&s,i+1},Buffer.prototype.writeInt16LE=function writeInt16LE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,2,32767,-32768),this[i]=255&s,this[i+1]=s>>>8,i+2},Buffer.prototype.writeInt16BE=function writeInt16BE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,2,32767,-32768),this[i]=s>>>8,this[i+1]=255&s,i+2},Buffer.prototype.writeInt32LE=function writeInt32LE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,4,2147483647,-2147483648),this[i]=255&s,this[i+1]=s>>>8,this[i+2]=s>>>16,this[i+3]=s>>>24,i+4},Buffer.prototype.writeInt32BE=function writeInt32BE(s,i,u){return s=+s,i>>>=0,u||checkInt(this,s,i,4,2147483647,-2147483648),s<0&&(s=4294967295+s+1),this[i]=s>>>24,this[i+1]=s>>>16,this[i+2]=s>>>8,this[i+3]=255&s,i+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(s,i=0){return wrtBigUInt64LE(this,s,i,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(s,i=0){return wrtBigUInt64BE(this,s,i,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeFloatLE=function writeFloatLE(s,i,u){return writeFloat(this,s,i,!0,u)},Buffer.prototype.writeFloatBE=function writeFloatBE(s,i,u){return writeFloat(this,s,i,!1,u)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(s,i,u){return writeDouble(this,s,i,!0,u)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(s,i,u){return writeDouble(this,s,i,!1,u)},Buffer.prototype.copy=function copy(s,i,u,_){if(!Buffer.isBuffer(s))throw new TypeError("argument should be a Buffer");if(u||(u=0),_||0===_||(_=this.length),i>=s.length&&(i=s.length),i||(i=0),_>0&&_=this.length)throw new RangeError("Index out of range");if(_<0)throw new RangeError("sourceEnd out of bounds");_>this.length&&(_=this.length),s.length-i<_-u&&(_=s.length-i+u);const w=_-u;return this===s&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(i,u,_):Uint8Array.prototype.set.call(s,this.subarray(u,_),i),w},Buffer.prototype.fill=function fill(s,i,u,_){if("string"==typeof s){if("string"==typeof i?(_=i,i=0,u=this.length):"string"==typeof u&&(_=u,u=this.length),void 0!==_&&"string"!=typeof _)throw new TypeError("encoding must be a string");if("string"==typeof _&&!Buffer.isEncoding(_))throw new TypeError("Unknown encoding: "+_);if(1===s.length){const i=s.charCodeAt(0);("utf8"===_&&i<128||"latin1"===_)&&(s=i)}}else"number"==typeof s?s&=255:"boolean"==typeof s&&(s=Number(s));if(i<0||this.length>>=0,u=void 0===u?this.length:u>>>0,s||(s=0),"number"==typeof s)for(w=i;w=_+4;u-=3)i=`_${s.slice(u-3,u)}${i}`;return`${s.slice(0,u)}${i}`}function checkIntBI(s,i,u,_,w,x){if(s>u||s3?0===i||i===BigInt(0)?`>= 0${_} and < 2${_} ** ${8*(x+1)}${_}`:`>= -(2${_} ** ${8*(x+1)-1}${_}) and < 2 ** ${8*(x+1)-1}${_}`:`>= ${i}${_} and <= ${u}${_}`,new B.ERR_OUT_OF_RANGE("value",w,s)}!function checkBounds(s,i,u){validateNumber(i,"offset"),void 0!==s[i]&&void 0!==s[i+u]||boundsError(i,s.length-(u+1))}(_,w,x)}function validateNumber(s,i){if("number"!=typeof s)throw new B.ERR_INVALID_ARG_TYPE(i,"number",s)}function boundsError(s,i,u){if(Math.floor(s)!==s)throw validateNumber(s,u),new B.ERR_OUT_OF_RANGE(u||"offset","an integer",s);if(i<0)throw new B.ERR_BUFFER_OUT_OF_BOUNDS;throw new B.ERR_OUT_OF_RANGE(u||"offset",`>= ${u?1:0} and <= ${i}`,s)}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),E("ERR_INVALID_ARG_TYPE",(function(s,i){return`The "${s}" argument must be of type number. Received type ${typeof i}`}),TypeError),E("ERR_OUT_OF_RANGE",(function(s,i,u){let _=`The value of "${s}" is out of range.`,w=u;return Number.isInteger(u)&&Math.abs(u)>2**32?w=addNumericalSeparator(String(u)):"bigint"==typeof u&&(w=String(u),(u>BigInt(2)**BigInt(32)||u<-(BigInt(2)**BigInt(32)))&&(w=addNumericalSeparator(w)),w+="n"),_+=` It must be ${i}. Received ${w}`,_}),RangeError);const $=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(s,i){let u;i=i||1/0;const _=s.length;let w=null;const x=[];for(let j=0;j<_;++j){if(u=s.charCodeAt(j),u>55295&&u<57344){if(!w){if(u>56319){(i-=3)>-1&&x.push(239,191,189);continue}if(j+1===_){(i-=3)>-1&&x.push(239,191,189);continue}w=u;continue}if(u<56320){(i-=3)>-1&&x.push(239,191,189),w=u;continue}u=65536+(w-55296<<10|u-56320)}else w&&(i-=3)>-1&&x.push(239,191,189);if(w=null,u<128){if((i-=1)<0)break;x.push(u)}else if(u<2048){if((i-=2)<0)break;x.push(u>>6|192,63&u|128)}else if(u<65536){if((i-=3)<0)break;x.push(u>>12|224,u>>6&63|128,63&u|128)}else{if(!(u<1114112))throw new Error("Invalid code point");if((i-=4)<0)break;x.push(u>>18|240,u>>12&63|128,u>>6&63|128,63&u|128)}}return x}function base64ToBytes(s){return _.toByteArray(function base64clean(s){if((s=(s=s.split("=")[0]).trim().replace($,"")).length<2)return"";for(;s.length%4!=0;)s+="=";return s}(s))}function blitBuffer(s,i,u,_){let w;for(w=0;w<_&&!(w+u>=i.length||w>=s.length);++w)i[w+u]=s[w];return w}function isInstance(s,i){return s instanceof i||null!=s&&null!=s.constructor&&null!=s.constructor.name&&s.constructor.name===i.name}function numberIsNaN(s){return s!=s}const U=function(){const s="0123456789abcdef",i=new Array(256);for(let u=0;u<16;++u){const _=16*u;for(let w=0;w<16;++w)i[_+w]=s[u]+s[w]}return i}();function defineBigIntMethod(s){return"undefined"==typeof BigInt?BufferBigIntNotDefined:s}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}},38075:(s,i,u)=>{"use strict";var _=u(70453),w=u(10487),x=w(_("String.prototype.indexOf"));s.exports=function callBoundIntrinsic(s,i){var u=_(s,!!i);return"function"==typeof u&&x(s,".prototype.")>-1?w(u):u}},10487:(s,i,u)=>{"use strict";var _=u(66743),w=u(70453),x=u(96897),j=u(69675),P=w("%Function.prototype.apply%"),B=w("%Function.prototype.call%"),$=w("%Reflect.apply%",!0)||_.call(B,P),U=u(30655),Y=w("%Math.max%");s.exports=function callBind(s){if("function"!=typeof s)throw new j("a function is required");var i=$(_,B,arguments);return x(i,1+Y(0,s.length-(arguments.length-1)),!0)};var X=function applyBind(){return $(_,P,arguments)};U?U(s.exports,"apply",{value:X}):s.exports.apply=X},57427:(s,i)=>{"use strict";i.parse=function parse(s,i){if("string"!=typeof s)throw new TypeError("argument str must be a string");var u={},_=(i||{}).decode||decode,w=0;for(;w{"use strict";var _=u(16426),w={"text/plain":"Text","text/html":"Url",default:"Text"};s.exports=function copy(s,i){var u,x,j,P,B,$,U=!1;i||(i={}),u=i.debug||!1;try{if(j=_(),P=document.createRange(),B=document.getSelection(),($=document.createElement("span")).textContent=s,$.ariaHidden="true",$.style.all="unset",$.style.position="fixed",$.style.top=0,$.style.clip="rect(0, 0, 0, 0)",$.style.whiteSpace="pre",$.style.webkitUserSelect="text",$.style.MozUserSelect="text",$.style.msUserSelect="text",$.style.userSelect="text",$.addEventListener("copy",(function(_){if(_.stopPropagation(),i.format)if(_.preventDefault(),void 0===_.clipboardData){u&&console.warn("unable to use e.clipboardData"),u&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var x=w[i.format]||w.default;window.clipboardData.setData(x,s)}else _.clipboardData.clearData(),_.clipboardData.setData(i.format,s);i.onCopy&&(_.preventDefault(),i.onCopy(_.clipboardData))})),document.body.appendChild($),P.selectNodeContents($),B.addRange(P),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");U=!0}catch(_){u&&console.error("unable to copy using execCommand: ",_),u&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(i.format||"text",s),i.onCopy&&i.onCopy(window.clipboardData),U=!0}catch(_){u&&console.error("unable to copy using clipboardData: ",_),u&&console.error("falling back to prompt"),x=function format(s){var i=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return s.replace(/#{\s*key\s*}/g,i)}("message"in i?i.message:"Copy to clipboard: #{key}, Enter"),window.prompt(x,s)}}finally{B&&("function"==typeof B.removeRange?B.removeRange(P):B.removeAllRanges()),$&&document.body.removeChild($),j()}return U}},2205:function(s,i,u){var _;_=void 0!==u.g?u.g:this,s.exports=function(s){if(s.CSS&&s.CSS.escape)return s.CSS.escape;var cssEscape=function(s){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var i,u=String(s),_=u.length,w=-1,x="",j=u.charCodeAt(0);++w<_;)0!=(i=u.charCodeAt(w))?x+=i>=1&&i<=31||127==i||0==w&&i>=48&&i<=57||1==w&&i>=48&&i<=57&&45==j?"\\"+i.toString(16)+" ":0==w&&1==_&&45==i||!(i>=128||45==i||95==i||i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122)?"\\"+u.charAt(w):u.charAt(w):x+="�";return x};return s.CSS||(s.CSS={}),s.CSS.escape=cssEscape,cssEscape}(_)},81919:(s,i,u)=>{"use strict";var _=u(48287).Buffer;function isSpecificValue(s){return s instanceof _||s instanceof Date||s instanceof RegExp}function cloneSpecificValue(s){if(s instanceof _){var i=_.alloc?_.alloc(s.length):new _(s.length);return s.copy(i),i}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s);throw new Error("Unexpected situation")}function deepCloneArray(s){var i=[];return s.forEach((function(s,u){"object"==typeof s&&null!==s?Array.isArray(s)?i[u]=deepCloneArray(s):isSpecificValue(s)?i[u]=cloneSpecificValue(s):i[u]=w({},s):i[u]=s})),i}function safeGetProperty(s,i){return"__proto__"===i?void 0:s[i]}var w=s.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var s,i,u=arguments[0];return Array.prototype.slice.call(arguments,1).forEach((function(_){"object"!=typeof _||null===_||Array.isArray(_)||Object.keys(_).forEach((function(x){return i=safeGetProperty(u,x),(s=safeGetProperty(_,x))===u?void 0:"object"!=typeof s||null===s?void(u[x]=s):Array.isArray(s)?void(u[x]=deepCloneArray(s)):isSpecificValue(s)?void(u[x]=cloneSpecificValue(s)):"object"!=typeof i||null===i||Array.isArray(i)?void(u[x]=w({},s)):void(u[x]=w(i,s))}))})),u}},14744:s=>{"use strict";var i=function isMergeableObject(s){return function isNonNullObject(s){return!!s&&"object"==typeof s}(s)&&!function isSpecial(s){var i=Object.prototype.toString.call(s);return"[object RegExp]"===i||"[object Date]"===i||function isReactElement(s){return s.$$typeof===u}(s)}(s)};var u="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function cloneUnlessOtherwiseSpecified(s,i){return!1!==i.clone&&i.isMergeableObject(s)?deepmerge(function emptyTarget(s){return Array.isArray(s)?[]:{}}(s),s,i):s}function defaultArrayMerge(s,i,u){return s.concat(i).map((function(s){return cloneUnlessOtherwiseSpecified(s,u)}))}function getKeys(s){return Object.keys(s).concat(function getEnumerableOwnPropertySymbols(s){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(s).filter((function(i){return Object.propertyIsEnumerable.call(s,i)})):[]}(s))}function propertyIsOnObject(s,i){try{return i in s}catch(s){return!1}}function mergeObject(s,i,u){var _={};return u.isMergeableObject(s)&&getKeys(s).forEach((function(i){_[i]=cloneUnlessOtherwiseSpecified(s[i],u)})),getKeys(i).forEach((function(w){(function propertyIsUnsafe(s,i){return propertyIsOnObject(s,i)&&!(Object.hasOwnProperty.call(s,i)&&Object.propertyIsEnumerable.call(s,i))})(s,w)||(propertyIsOnObject(s,w)&&u.isMergeableObject(i[w])?_[w]=function getMergeFunction(s,i){if(!i.customMerge)return deepmerge;var u=i.customMerge(s);return"function"==typeof u?u:deepmerge}(w,u)(s[w],i[w],u):_[w]=cloneUnlessOtherwiseSpecified(i[w],u))})),_}function deepmerge(s,u,_){(_=_||{}).arrayMerge=_.arrayMerge||defaultArrayMerge,_.isMergeableObject=_.isMergeableObject||i,_.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var w=Array.isArray(u);return w===Array.isArray(s)?w?_.arrayMerge(s,u,_):mergeObject(s,u,_):cloneUnlessOtherwiseSpecified(u,_)}deepmerge.all=function deepmergeAll(s,i){if(!Array.isArray(s))throw new Error("first argument should be an array");return s.reduce((function(s,u){return deepmerge(s,u,i)}),{})};var _=deepmerge;s.exports=_},30041:(s,i,u)=>{"use strict";var _=u(30655),w=u(58068),x=u(69675),j=u(75795);s.exports=function defineDataProperty(s,i,u){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new x("`obj` must be an object or a function`");if("string"!=typeof i&&"symbol"!=typeof i)throw new x("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new x("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new x("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new x("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new x("`loose`, if provided, must be a boolean");var P=arguments.length>3?arguments[3]:null,B=arguments.length>4?arguments[4]:null,$=arguments.length>5?arguments[5]:null,U=arguments.length>6&&arguments[6],Y=!!j&&j(s,i);if(_)_(s,i,{configurable:null===$&&Y?Y.configurable:!$,enumerable:null===P&&Y?Y.enumerable:!P,value:u,writable:null===B&&Y?Y.writable:!B});else{if(!U&&(P||B||$))throw new w("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");s[i]=u}}},42838:function(s){s.exports=function(){"use strict";const{entries:s,setPrototypeOf:i,isFrozen:u,getPrototypeOf:_,getOwnPropertyDescriptor:w}=Object;let{freeze:x,seal:j,create:P}=Object,{apply:B,construct:$}="undefined"!=typeof Reflect&&Reflect;x||(x=function freeze(s){return s}),j||(j=function seal(s){return s}),B||(B=function apply(s,i,u){return s.apply(i,u)}),$||($=function construct(s,i){return new s(...i)});const U=unapply(Array.prototype.forEach),Y=unapply(Array.prototype.pop),X=unapply(Array.prototype.push),Z=unapply(String.prototype.toLowerCase),ee=unapply(String.prototype.toString),ie=unapply(String.prototype.match),ae=unapply(String.prototype.replace),le=unapply(String.prototype.indexOf),ce=unapply(String.prototype.trim),pe=unapply(Object.prototype.hasOwnProperty),de=unapply(RegExp.prototype.test),fe=unconstruct(TypeError);function unapply(s){return function(i){for(var u=arguments.length,_=new Array(u>1?u-1:0),w=1;w2&&void 0!==arguments[2]?arguments[2]:Z;i&&i(s,null);let x=_.length;for(;x--;){let i=_[x];if("string"==typeof i){const s=w(i);s!==i&&(u(_)||(_[x]=s),i=s)}s[i]=!0}return s}function cleanArray(s){for(let i=0;i/gm),He=j(/\${[\w\W]*}/gm),Ye=j(/^data-[\-\w.\u00B7-\uFFFF]/),Xe=j(/^aria-[\-\w]+$/),Qe=j(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),et=j(/^(?:\w+script|data):/i),tt=j(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),rt=j(/^html$/i),nt=j(/^[a-z][.\w]*(-[.\w]+)+$/i);var ot=Object.freeze({__proto__:null,MUSTACHE_EXPR:ze,ERB_EXPR:We,TMPLIT_EXPR:He,DATA_ATTR:Ye,ARIA_ATTR:Xe,IS_ALLOWED_URI:Qe,IS_SCRIPT_OR_DATA:et,ATTR_WHITESPACE:tt,DOCTYPE_NAME:rt,CUSTOM_ELEMENT:nt});const st=function getGlobal(){return"undefined"==typeof window?null:window},it=function _createTrustedTypesPolicy(s,i){if("object"!=typeof s||"function"!=typeof s.createPolicy)return null;let u=null;const _="data-tt-policy-suffix";i&&i.hasAttribute(_)&&(u=i.getAttribute(_));const w="dompurify"+(u?"#"+u:"");try{return s.createPolicy(w,{createHTML:s=>s,createScriptURL:s=>s})}catch(s){return console.warn("TrustedTypes policy "+w+" could not be created."),null}};function createDOMPurify(){let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:st();const DOMPurify=s=>createDOMPurify(s);if(DOMPurify.version="3.0.11",DOMPurify.removed=[],!i||!i.document||9!==i.document.nodeType)return DOMPurify.isSupported=!1,DOMPurify;let{document:u}=i;const _=u,w=_.currentScript,{DocumentFragment:j,HTMLTemplateElement:B,Node:$,Element:ze,NodeFilter:We,NamedNodeMap:He=i.NamedNodeMap||i.MozNamedAttrMap,HTMLFormElement:Ye,DOMParser:Xe,trustedTypes:et}=i,tt=ze.prototype,nt=lookupGetter(tt,"cloneNode"),at=lookupGetter(tt,"nextSibling"),lt=lookupGetter(tt,"childNodes"),ct=lookupGetter(tt,"parentNode");if("function"==typeof B){const s=u.createElement("template");s.content&&s.content.ownerDocument&&(u=s.content.ownerDocument)}let ut,pt="";const{implementation:ht,createNodeIterator:dt,createDocumentFragment:mt,getElementsByTagName:gt}=u,{importNode:yt}=_;let vt={};DOMPurify.isSupported="function"==typeof s&&"function"==typeof ct&&ht&&void 0!==ht.createHTMLDocument;const{MUSTACHE_EXPR:bt,ERB_EXPR:_t,TMPLIT_EXPR:Et,DATA_ATTR:wt,ARIA_ATTR:St,IS_SCRIPT_OR_DATA:xt,ATTR_WHITESPACE:kt,CUSTOM_ELEMENT:Ot}=ot;let{IS_ALLOWED_URI:Ct}=ot,At=null;const jt=addToSet({},[...ye,...be,..._e,...Se,...Pe]);let Pt=null;const It=addToSet({},[...Te,...Re,...qe,...$e]);let Nt=Object.seal(P(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Mt=null,Tt=null,Rt=!0,Dt=!0,Bt=!1,Lt=!0,Ft=!1,qt=!1,$t=!1,Ut=!1,zt=!1,Vt=!1,Wt=!1,Kt=!0,Ht=!1;const Jt="user-content-";let Gt=!0,Yt=!1,Xt={},Qt=null;const Zt=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let er=null;const tr=addToSet({},["audio","video","img","source","image","track"]);let rr=null;const nr=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),sr="http://www.w3.org/1998/Math/MathML",ir="http://www.w3.org/2000/svg",ar="http://www.w3.org/1999/xhtml";let lr=ar,cr=!1,ur=null;const pr=addToSet({},[sr,ir,ar],ee);let dr=null;const fr=["application/xhtml+xml","text/html"],mr="text/html";let gr=null,yr=null;const vr=u.createElement("form"),br=function isRegexOrFunction(s){return s instanceof RegExp||s instanceof Function},_r=function _parseConfig(){let s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!yr||yr!==s){if(s&&"object"==typeof s||(s={}),s=clone(s),dr=-1===fr.indexOf(s.PARSER_MEDIA_TYPE)?mr:s.PARSER_MEDIA_TYPE,gr="application/xhtml+xml"===dr?ee:Z,At=pe(s,"ALLOWED_TAGS")?addToSet({},s.ALLOWED_TAGS,gr):jt,Pt=pe(s,"ALLOWED_ATTR")?addToSet({},s.ALLOWED_ATTR,gr):It,ur=pe(s,"ALLOWED_NAMESPACES")?addToSet({},s.ALLOWED_NAMESPACES,ee):pr,rr=pe(s,"ADD_URI_SAFE_ATTR")?addToSet(clone(nr),s.ADD_URI_SAFE_ATTR,gr):nr,er=pe(s,"ADD_DATA_URI_TAGS")?addToSet(clone(tr),s.ADD_DATA_URI_TAGS,gr):tr,Qt=pe(s,"FORBID_CONTENTS")?addToSet({},s.FORBID_CONTENTS,gr):Zt,Mt=pe(s,"FORBID_TAGS")?addToSet({},s.FORBID_TAGS,gr):{},Tt=pe(s,"FORBID_ATTR")?addToSet({},s.FORBID_ATTR,gr):{},Xt=!!pe(s,"USE_PROFILES")&&s.USE_PROFILES,Rt=!1!==s.ALLOW_ARIA_ATTR,Dt=!1!==s.ALLOW_DATA_ATTR,Bt=s.ALLOW_UNKNOWN_PROTOCOLS||!1,Lt=!1!==s.ALLOW_SELF_CLOSE_IN_ATTR,Ft=s.SAFE_FOR_TEMPLATES||!1,qt=s.WHOLE_DOCUMENT||!1,zt=s.RETURN_DOM||!1,Vt=s.RETURN_DOM_FRAGMENT||!1,Wt=s.RETURN_TRUSTED_TYPE||!1,Ut=s.FORCE_BODY||!1,Kt=!1!==s.SANITIZE_DOM,Ht=s.SANITIZE_NAMED_PROPS||!1,Gt=!1!==s.KEEP_CONTENT,Yt=s.IN_PLACE||!1,Ct=s.ALLOWED_URI_REGEXP||Qe,lr=s.NAMESPACE||ar,Nt=s.CUSTOM_ELEMENT_HANDLING||{},s.CUSTOM_ELEMENT_HANDLING&&br(s.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Nt.tagNameCheck=s.CUSTOM_ELEMENT_HANDLING.tagNameCheck),s.CUSTOM_ELEMENT_HANDLING&&br(s.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Nt.attributeNameCheck=s.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),s.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof s.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Nt.allowCustomizedBuiltInElements=s.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ft&&(Dt=!1),Vt&&(zt=!0),Xt&&(At=addToSet({},Pe),Pt=[],!0===Xt.html&&(addToSet(At,ye),addToSet(Pt,Te)),!0===Xt.svg&&(addToSet(At,be),addToSet(Pt,Re),addToSet(Pt,$e)),!0===Xt.svgFilters&&(addToSet(At,_e),addToSet(Pt,Re),addToSet(Pt,$e)),!0===Xt.mathMl&&(addToSet(At,Se),addToSet(Pt,qe),addToSet(Pt,$e))),s.ADD_TAGS&&(At===jt&&(At=clone(At)),addToSet(At,s.ADD_TAGS,gr)),s.ADD_ATTR&&(Pt===It&&(Pt=clone(Pt)),addToSet(Pt,s.ADD_ATTR,gr)),s.ADD_URI_SAFE_ATTR&&addToSet(rr,s.ADD_URI_SAFE_ATTR,gr),s.FORBID_CONTENTS&&(Qt===Zt&&(Qt=clone(Qt)),addToSet(Qt,s.FORBID_CONTENTS,gr)),Gt&&(At["#text"]=!0),qt&&addToSet(At,["html","head","body"]),At.table&&(addToSet(At,["tbody"]),delete Mt.tbody),s.TRUSTED_TYPES_POLICY){if("function"!=typeof s.TRUSTED_TYPES_POLICY.createHTML)throw fe('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof s.TRUSTED_TYPES_POLICY.createScriptURL)throw fe('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ut=s.TRUSTED_TYPES_POLICY,pt=ut.createHTML("")}else void 0===ut&&(ut=it(et,w)),null!==ut&&"string"==typeof pt&&(pt=ut.createHTML(""));x&&x(s),yr=s}},Er=addToSet({},["mi","mo","mn","ms","mtext"]),wr=addToSet({},["foreignobject","desc","title","annotation-xml"]),Sr=addToSet({},["title","style","font","a","script"]),xr=addToSet({},[...be,..._e,...we]),kr=addToSet({},[...Se,...xe]),Or=function _checkValidNamespace(s){let i=ct(s);i&&i.tagName||(i={namespaceURI:lr,tagName:"template"});const u=Z(s.tagName),_=Z(i.tagName);return!!ur[s.namespaceURI]&&(s.namespaceURI===ir?i.namespaceURI===ar?"svg"===u:i.namespaceURI===sr?"svg"===u&&("annotation-xml"===_||Er[_]):Boolean(xr[u]):s.namespaceURI===sr?i.namespaceURI===ar?"math"===u:i.namespaceURI===ir?"math"===u&&wr[_]:Boolean(kr[u]):s.namespaceURI===ar?!(i.namespaceURI===ir&&!wr[_])&&!(i.namespaceURI===sr&&!Er[_])&&!kr[u]&&(Sr[u]||!xr[u]):!("application/xhtml+xml"!==dr||!ur[s.namespaceURI]))},Cr=function _forceRemove(s){X(DOMPurify.removed,{element:s});try{s.parentNode.removeChild(s)}catch(i){s.remove()}},Ar=function _removeAttribute(s,i){try{X(DOMPurify.removed,{attribute:i.getAttributeNode(s),from:i})}catch(s){X(DOMPurify.removed,{attribute:null,from:i})}if(i.removeAttribute(s),"is"===s&&!Pt[s])if(zt||Vt)try{Cr(i)}catch(s){}else try{i.setAttribute(s,"")}catch(s){}},jr=function _initDocument(s){let i=null,_=null;if(Ut)s=""+s;else{const i=ie(s,/^[\r\n\t ]+/);_=i&&i[0]}"application/xhtml+xml"===dr&&lr===ar&&(s=''+s+"");const w=ut?ut.createHTML(s):s;if(lr===ar)try{i=(new Xe).parseFromString(w,dr)}catch(s){}if(!i||!i.documentElement){i=ht.createDocument(lr,"template",null);try{i.documentElement.innerHTML=cr?pt:w}catch(s){}}const x=i.body||i.documentElement;return s&&_&&x.insertBefore(u.createTextNode(_),x.childNodes[0]||null),lr===ar?gt.call(i,qt?"html":"body")[0]:qt?i.documentElement:x},Pr=function _createNodeIterator(s){return dt.call(s.ownerDocument||s,s,We.SHOW_ELEMENT|We.SHOW_COMMENT|We.SHOW_TEXT|We.SHOW_PROCESSING_INSTRUCTION|We.SHOW_CDATA_SECTION,null)},Ir=function _isClobbered(s){return s instanceof Ye&&("string"!=typeof s.nodeName||"string"!=typeof s.textContent||"function"!=typeof s.removeChild||!(s.attributes instanceof He)||"function"!=typeof s.removeAttribute||"function"!=typeof s.setAttribute||"string"!=typeof s.namespaceURI||"function"!=typeof s.insertBefore||"function"!=typeof s.hasChildNodes)},Nr=function _isNode(s){return"function"==typeof $&&s instanceof $},Mr=function _executeHook(s,i,u){vt[s]&&U(vt[s],(s=>{s.call(DOMPurify,i,u,yr)}))},Tr=function _sanitizeElements(s){let i=null;if(Mr("beforeSanitizeElements",s,null),Ir(s))return Cr(s),!0;const u=gr(s.nodeName);if(Mr("uponSanitizeElement",s,{tagName:u,allowedTags:At}),s.hasChildNodes()&&!Nr(s.firstElementChild)&&de(/<[/\w]/g,s.innerHTML)&&de(/<[/\w]/g,s.textContent))return Cr(s),!0;if(7===s.nodeType)return Cr(s),!0;if(!At[u]||Mt[u]){if(!Mt[u]&&Dr(u)){if(Nt.tagNameCheck instanceof RegExp&&de(Nt.tagNameCheck,u))return!1;if(Nt.tagNameCheck instanceof Function&&Nt.tagNameCheck(u))return!1}if(Gt&&!Qt[u]){const i=ct(s)||s.parentNode,u=lt(s)||s.childNodes;if(u&&i)for(let _=u.length-1;_>=0;--_)i.insertBefore(nt(u[_],!0),at(s))}return Cr(s),!0}return s instanceof ze&&!Or(s)?(Cr(s),!0):"noscript"!==u&&"noembed"!==u&&"noframes"!==u||!de(/<\/no(script|embed|frames)/i,s.innerHTML)?(Ft&&3===s.nodeType&&(i=s.textContent,U([bt,_t,Et],(s=>{i=ae(i,s," ")})),s.textContent!==i&&(X(DOMPurify.removed,{element:s.cloneNode()}),s.textContent=i)),Mr("afterSanitizeElements",s,null),!1):(Cr(s),!0)},Rr=function _isValidAttribute(s,i,_){if(Kt&&("id"===i||"name"===i)&&(_ in u||_ in vr))return!1;if(Dt&&!Tt[i]&&de(wt,i));else if(Rt&&de(St,i));else if(!Pt[i]||Tt[i]){if(!(Dr(s)&&(Nt.tagNameCheck instanceof RegExp&&de(Nt.tagNameCheck,s)||Nt.tagNameCheck instanceof Function&&Nt.tagNameCheck(s))&&(Nt.attributeNameCheck instanceof RegExp&&de(Nt.attributeNameCheck,i)||Nt.attributeNameCheck instanceof Function&&Nt.attributeNameCheck(i))||"is"===i&&Nt.allowCustomizedBuiltInElements&&(Nt.tagNameCheck instanceof RegExp&&de(Nt.tagNameCheck,_)||Nt.tagNameCheck instanceof Function&&Nt.tagNameCheck(_))))return!1}else if(rr[i]);else if(de(Ct,ae(_,kt,"")));else if("src"!==i&&"xlink:href"!==i&&"href"!==i||"script"===s||0!==le(_,"data:")||!er[s])if(Bt&&!de(xt,ae(_,kt,"")));else if(_)return!1;return!0},Dr=function _isBasicCustomElement(s){return"annotation-xml"!==s&&ie(s,Ot)},Br=function _sanitizeAttributes(s){Mr("beforeSanitizeAttributes",s,null);const{attributes:i}=s;if(!i)return;const u={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Pt};let _=i.length;for(;_--;){const w=i[_],{name:x,namespaceURI:j,value:P}=w,B=gr(x);let $="value"===x?P:ce(P);if(u.attrName=B,u.attrValue=$,u.keepAttr=!0,u.forceKeepAttr=void 0,Mr("uponSanitizeAttribute",s,u),$=u.attrValue,u.forceKeepAttr)continue;if(Ar(x,s),!u.keepAttr)continue;if(!Lt&&de(/\/>/i,$)){Ar(x,s);continue}Ft&&U([bt,_t,Et],(s=>{$=ae($,s," ")}));const X=gr(s.nodeName);if(Rr(X,B,$)){if(!Ht||"id"!==B&&"name"!==B||(Ar(x,s),$=Jt+$),ut&&"object"==typeof et&&"function"==typeof et.getAttributeType)if(j);else switch(et.getAttributeType(X,B)){case"TrustedHTML":$=ut.createHTML($);break;case"TrustedScriptURL":$=ut.createScriptURL($)}try{j?s.setAttributeNS(j,x,$):s.setAttribute(x,$),Y(DOMPurify.removed)}catch(s){}}}Mr("afterSanitizeAttributes",s,null)},Lr=function _sanitizeShadowDOM(s){let i=null;const u=Pr(s);for(Mr("beforeSanitizeShadowDOM",s,null);i=u.nextNode();)Mr("uponSanitizeShadowNode",i,null),Tr(i)||(i.content instanceof j&&_sanitizeShadowDOM(i.content),Br(i));Mr("afterSanitizeShadowDOM",s,null)};return DOMPurify.sanitize=function(s){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},u=null,w=null,x=null,P=null;if(cr=!s,cr&&(s="\x3c!--\x3e"),"string"!=typeof s&&!Nr(s)){if("function"!=typeof s.toString)throw fe("toString is not a function");if("string"!=typeof(s=s.toString()))throw fe("dirty is not a string, aborting")}if(!DOMPurify.isSupported)return s;if($t||_r(i),DOMPurify.removed=[],"string"==typeof s&&(Yt=!1),Yt){if(s.nodeName){const i=gr(s.nodeName);if(!At[i]||Mt[i])throw fe("root node is forbidden and cannot be sanitized in-place")}}else if(s instanceof $)u=jr("\x3c!----\x3e"),w=u.ownerDocument.importNode(s,!0),1===w.nodeType&&"BODY"===w.nodeName||"HTML"===w.nodeName?u=w:u.appendChild(w);else{if(!zt&&!Ft&&!qt&&-1===s.indexOf("<"))return ut&&Wt?ut.createHTML(s):s;if(u=jr(s),!u)return zt?null:Wt?pt:""}u&&Ut&&Cr(u.firstChild);const B=Pr(Yt?s:u);for(;x=B.nextNode();)Tr(x)||(x.content instanceof j&&Lr(x.content),Br(x));if(Yt)return s;if(zt){if(Vt)for(P=mt.call(u.ownerDocument);u.firstChild;)P.appendChild(u.firstChild);else P=u;return(Pt.shadowroot||Pt.shadowrootmode)&&(P=yt.call(_,P,!0)),P}let Y=qt?u.outerHTML:u.innerHTML;return qt&&At["!doctype"]&&u.ownerDocument&&u.ownerDocument.doctype&&u.ownerDocument.doctype.name&&de(rt,u.ownerDocument.doctype.name)&&(Y="\n"+Y),Ft&&U([bt,_t,Et],(s=>{Y=ae(Y,s," ")})),ut&&Wt?ut.createHTML(Y):Y},DOMPurify.setConfig=function(){_r(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),$t=!0},DOMPurify.clearConfig=function(){yr=null,$t=!1},DOMPurify.isValidAttribute=function(s,i,u){yr||_r({});const _=gr(s),w=gr(i);return Rr(_,w,u)},DOMPurify.addHook=function(s,i){"function"==typeof i&&(vt[s]=vt[s]||[],X(vt[s],i))},DOMPurify.removeHook=function(s){if(vt[s])return Y(vt[s])},DOMPurify.removeHooks=function(s){vt[s]&&(vt[s]=[])},DOMPurify.removeAllHooks=function(){vt={}},DOMPurify}return createDOMPurify()}()},78004:s=>{"use strict";class SubRange{constructor(s,i){this.low=s,this.high=i,this.length=1+i-s}overlaps(s){return!(this.highs.high)}touches(s){return!(this.high+1s.high)}add(s){return new SubRange(Math.min(this.low,s.low),Math.max(this.high,s.high))}subtract(s){return s.low<=this.low&&s.high>=this.high?[]:s.low>this.low&&s.highs+i.length),0)}add(s,i){var _add=s=>{for(var i=0;i{for(var i=0;i{for(var i=0;i{for(var u=i.low;u<=i.high;)s.push(u),u++;return s}),[])}subranges(){return this.ranges.map((s=>({low:s.low,high:s.high,length:1+s.high-s.low})))}}s.exports=DRange},30655:(s,i,u)=>{"use strict";var _=u(70453)("%Object.defineProperty%",!0)||!1;if(_)try{_({},"a",{value:1})}catch(s){_=!1}s.exports=_},41237:s=>{"use strict";s.exports=EvalError},69383:s=>{"use strict";s.exports=Error},79290:s=>{"use strict";s.exports=RangeError},79538:s=>{"use strict";s.exports=ReferenceError},58068:s=>{"use strict";s.exports=SyntaxError},69675:s=>{"use strict";s.exports=TypeError},35345:s=>{"use strict";s.exports=URIError},37007:s=>{"use strict";var i,u="object"==typeof Reflect?Reflect:null,_=u&&"function"==typeof u.apply?u.apply:function ReflectApply(s,i,u){return Function.prototype.apply.call(s,i,u)};i=u&&"function"==typeof u.ownKeys?u.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s)};var w=Number.isNaN||function NumberIsNaN(s){return s!=s};function EventEmitter(){EventEmitter.init.call(this)}s.exports=EventEmitter,s.exports.once=function once(s,i){return new Promise((function(u,_){function errorListener(u){s.removeListener(i,resolver),_(u)}function resolver(){"function"==typeof s.removeListener&&s.removeListener("error",errorListener),u([].slice.call(arguments))}eventTargetAgnosticAddListener(s,i,resolver,{once:!0}),"error"!==i&&function addErrorHandlerIfEventEmitter(s,i,u){"function"==typeof s.on&&eventTargetAgnosticAddListener(s,"error",i,u)}(s,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var x=10;function checkListener(s){if("function"!=typeof s)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}function _getMaxListeners(s){return void 0===s._maxListeners?EventEmitter.defaultMaxListeners:s._maxListeners}function _addListener(s,i,u,_){var w,x,j;if(checkListener(u),void 0===(x=s._events)?(x=s._events=Object.create(null),s._eventsCount=0):(void 0!==x.newListener&&(s.emit("newListener",i,u.listener?u.listener:u),x=s._events),j=x[i]),void 0===j)j=x[i]=u,++s._eventsCount;else if("function"==typeof j?j=x[i]=_?[u,j]:[j,u]:_?j.unshift(u):j.push(u),(w=_getMaxListeners(s))>0&&j.length>w&&!j.warned){j.warned=!0;var P=new Error("Possible EventEmitter memory leak detected. "+j.length+" "+String(i)+" listeners added. Use emitter.setMaxListeners() to increase limit");P.name="MaxListenersExceededWarning",P.emitter=s,P.type=i,P.count=j.length,function ProcessEmitWarning(s){console&&console.warn&&console.warn(s)}(P)}return s}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(s,i,u){var _={fired:!1,wrapFn:void 0,target:s,type:i,listener:u},w=onceWrapper.bind(_);return w.listener=u,_.wrapFn=w,w}function _listeners(s,i,u){var _=s._events;if(void 0===_)return[];var w=_[i];return void 0===w?[]:"function"==typeof w?u?[w.listener||w]:[w]:u?function unwrapListeners(s){for(var i=new Array(s.length),u=0;u0&&(j=i[0]),j instanceof Error)throw j;var P=new Error("Unhandled error."+(j?" ("+j.message+")":""));throw P.context=j,P}var B=x[s];if(void 0===B)return!1;if("function"==typeof B)_(B,this,i);else{var $=B.length,U=arrayClone(B,$);for(u=0;u<$;++u)_(U[u],this,i)}return!0},EventEmitter.prototype.addListener=function addListener(s,i){return _addListener(this,s,i,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function prependListener(s,i){return _addListener(this,s,i,!0)},EventEmitter.prototype.once=function once(s,i){return checkListener(i),this.on(s,_onceWrap(this,s,i)),this},EventEmitter.prototype.prependOnceListener=function prependOnceListener(s,i){return checkListener(i),this.prependListener(s,_onceWrap(this,s,i)),this},EventEmitter.prototype.removeListener=function removeListener(s,i){var u,_,w,x,j;if(checkListener(i),void 0===(_=this._events))return this;if(void 0===(u=_[s]))return this;if(u===i||u.listener===i)0==--this._eventsCount?this._events=Object.create(null):(delete _[s],_.removeListener&&this.emit("removeListener",s,u.listener||i));else if("function"!=typeof u){for(w=-1,x=u.length-1;x>=0;x--)if(u[x]===i||u[x].listener===i){j=u[x].listener,w=x;break}if(w<0)return this;0===w?u.shift():function spliceOne(s,i){for(;i+1=0;_--)this.removeListener(s,i[_]);return this},EventEmitter.prototype.listeners=function listeners(s){return _listeners(this,s,!0)},EventEmitter.prototype.rawListeners=function rawListeners(s){return _listeners(this,s,!1)},EventEmitter.listenerCount=function(s,i){return"function"==typeof s.listenerCount?s.listenerCount(i):listenerCount.call(s,i)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?i(this._events):[]}},85587:(s,i,u)=>{"use strict";var _=u(26311),w=create(Error);function create(s){return FormattedError.displayName=s.displayName||s.name,FormattedError;function FormattedError(i){return i&&(i=_.apply(null,arguments)),new s(i)}}s.exports=w,w.eval=create(EvalError),w.range=create(RangeError),w.reference=create(ReferenceError),w.syntax=create(SyntaxError),w.type=create(TypeError),w.uri=create(URIError),w.create=create},26311:s=>{!function(){var i;function format(s){for(var i,u,_,w,x=1,j=[].slice.call(arguments),P=0,B=s.length,$="",U=!1,Y=!1,nextArg=function(){return j[x++]},slurpNumber=function(){for(var u="";/\d/.test(s[P]);)u+=s[P++],i=s[P];return u.length>0?parseInt(u):null};P{"use strict";var i=Object.prototype.toString,u=Math.max,_=function concatty(s,i){for(var u=[],_=0;_{"use strict";var _=u(89353);s.exports=Function.prototype.bind||_},70453:(s,i,u)=>{"use strict";var _,w=u(69383),x=u(41237),j=u(79290),P=u(79538),B=u(58068),$=u(69675),U=u(35345),Y=Function,getEvalledConstructor=function(s){try{return Y('"use strict"; return ('+s+").constructor;")()}catch(s){}},X=Object.getOwnPropertyDescriptor;if(X)try{X({},"")}catch(s){X=null}var throwTypeError=function(){throw new $},Z=X?function(){try{return throwTypeError}catch(s){try{return X(arguments,"callee").get}catch(s){return throwTypeError}}}():throwTypeError,ee=u(64039)(),ie=u(80024)(),ae=Object.getPrototypeOf||(ie?function(s){return s.__proto__}:null),le={},ce="undefined"!=typeof Uint8Array&&ae?ae(Uint8Array):_,pe={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?_:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?_:ArrayBuffer,"%ArrayIteratorPrototype%":ee&&ae?ae([][Symbol.iterator]()):_,"%AsyncFromSyncIteratorPrototype%":_,"%AsyncFunction%":le,"%AsyncGenerator%":le,"%AsyncGeneratorFunction%":le,"%AsyncIteratorPrototype%":le,"%Atomics%":"undefined"==typeof Atomics?_:Atomics,"%BigInt%":"undefined"==typeof BigInt?_:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?_:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?_:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?_:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":w,"%eval%":eval,"%EvalError%":x,"%Float32Array%":"undefined"==typeof Float32Array?_:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?_:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?_:FinalizationRegistry,"%Function%":Y,"%GeneratorFunction%":le,"%Int8Array%":"undefined"==typeof Int8Array?_:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?_:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?_:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":ee&&ae?ae(ae([][Symbol.iterator]())):_,"%JSON%":"object"==typeof JSON?JSON:_,"%Map%":"undefined"==typeof Map?_:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&ee&&ae?ae((new Map)[Symbol.iterator]()):_,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?_:Promise,"%Proxy%":"undefined"==typeof Proxy?_:Proxy,"%RangeError%":j,"%ReferenceError%":P,"%Reflect%":"undefined"==typeof Reflect?_:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?_:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&ee&&ae?ae((new Set)[Symbol.iterator]()):_,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?_:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":ee&&ae?ae(""[Symbol.iterator]()):_,"%Symbol%":ee?Symbol:_,"%SyntaxError%":B,"%ThrowTypeError%":Z,"%TypedArray%":ce,"%TypeError%":$,"%Uint8Array%":"undefined"==typeof Uint8Array?_:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?_:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?_:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?_:Uint32Array,"%URIError%":U,"%WeakMap%":"undefined"==typeof WeakMap?_:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?_:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?_:WeakSet};if(ae)try{null.error}catch(s){var de=ae(ae(s));pe["%Error.prototype%"]=de}var fe=function doEval(s){var i;if("%AsyncFunction%"===s)i=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===s)i=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===s)i=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===s){var u=doEval("%AsyncGeneratorFunction%");u&&(i=u.prototype)}else if("%AsyncIteratorPrototype%"===s){var _=doEval("%AsyncGenerator%");_&&ae&&(i=ae(_.prototype))}return pe[s]=i,i},ye={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},be=u(66743),_e=u(9957),we=be.call(Function.call,Array.prototype.concat),Se=be.call(Function.apply,Array.prototype.splice),xe=be.call(Function.call,String.prototype.replace),Pe=be.call(Function.call,String.prototype.slice),Te=be.call(Function.call,RegExp.prototype.exec),Re=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,qe=/\\(\\)?/g,$e=function getBaseIntrinsic(s,i){var u,_=s;if(_e(ye,_)&&(_="%"+(u=ye[_])[0]+"%"),_e(pe,_)){var w=pe[_];if(w===le&&(w=fe(_)),void 0===w&&!i)throw new $("intrinsic "+s+" exists, but is not available. Please file an issue!");return{alias:u,name:_,value:w}}throw new B("intrinsic "+s+" does not exist!")};s.exports=function GetIntrinsic(s,i){if("string"!=typeof s||0===s.length)throw new $("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof i)throw new $('"allowMissing" argument must be a boolean');if(null===Te(/^%?[^%]*%?$/,s))throw new B("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var u=function stringToPath(s){var i=Pe(s,0,1),u=Pe(s,-1);if("%"===i&&"%"!==u)throw new B("invalid intrinsic syntax, expected closing `%`");if("%"===u&&"%"!==i)throw new B("invalid intrinsic syntax, expected opening `%`");var _=[];return xe(s,Re,(function(s,i,u,w){_[_.length]=u?xe(w,qe,"$1"):i||s})),_}(s),_=u.length>0?u[0]:"",w=$e("%"+_+"%",i),x=w.name,j=w.value,P=!1,U=w.alias;U&&(_=U[0],Se(u,we([0,1],U)));for(var Y=1,Z=!0;Y=u.length){var le=X(j,ee);j=(Z=!!le)&&"get"in le&&!("originalValue"in le.get)?le.get:j[ee]}else Z=_e(j,ee),j=j[ee];Z&&!P&&(pe[x]=j)}}return j}},75795:(s,i,u)=>{"use strict";var _=u(70453)("%Object.getOwnPropertyDescriptor%",!0);if(_)try{_([],"length")}catch(s){_=null}s.exports=_},30592:(s,i,u)=>{"use strict";var _=u(30655),w=function hasPropertyDescriptors(){return!!_};w.hasArrayLengthDefineBug=function hasArrayLengthDefineBug(){if(!_)return null;try{return 1!==_([],"length",{value:1}).length}catch(s){return!0}},s.exports=w},80024:s=>{"use strict";var i={__proto__:null,foo:{}},u=Object;s.exports=function hasProto(){return{__proto__:i}.foo===i.foo&&!(i instanceof u)}},64039:(s,i,u)=>{"use strict";var _="undefined"!=typeof Symbol&&Symbol,w=u(41333);s.exports=function hasNativeSymbols(){return"function"==typeof _&&("function"==typeof Symbol&&("symbol"==typeof _("foo")&&("symbol"==typeof Symbol("bar")&&w())))}},41333:s=>{"use strict";s.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var s={},i=Symbol("test"),u=Object(i);if("string"==typeof i)return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;if("[object Symbol]"!==Object.prototype.toString.call(u))return!1;for(i in s[i]=42,s)return!1;if("function"==typeof Object.keys&&0!==Object.keys(s).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(s).length)return!1;var _=Object.getOwnPropertySymbols(s);if(1!==_.length||_[0]!==i)return!1;if(!Object.prototype.propertyIsEnumerable.call(s,i))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var w=Object.getOwnPropertyDescriptor(s,i);if(42!==w.value||!0!==w.enumerable)return!1}return!0}},9957:(s,i,u)=>{"use strict";var _=Function.prototype.call,w=Object.prototype.hasOwnProperty,x=u(66743);s.exports=x.call(_,w)},45981:s=>{function deepFreeze(s){return s instanceof Map?s.clear=s.delete=s.set=function(){throw new Error("map is read-only")}:s instanceof Set&&(s.add=s.clear=s.delete=function(){throw new Error("set is read-only")}),Object.freeze(s),Object.getOwnPropertyNames(s).forEach((function(i){var u=s[i];"object"!=typeof u||Object.isFrozen(u)||deepFreeze(u)})),s}var i=deepFreeze,u=deepFreeze;i.default=u;class Response{constructor(s){void 0===s.data&&(s.data={}),this.data=s.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function escapeHTML(s){return s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function inherit(s,...i){const u=Object.create(null);for(const i in s)u[i]=s[i];return i.forEach((function(s){for(const i in s)u[i]=s[i]})),u}const emitsWrappingTags=s=>!!s.kind;class HTMLRenderer{constructor(s,i){this.buffer="",this.classPrefix=i.classPrefix,s.walk(this)}addText(s){this.buffer+=escapeHTML(s)}openNode(s){if(!emitsWrappingTags(s))return;let i=s.kind;s.sublanguage||(i=`${this.classPrefix}${i}`),this.span(i)}closeNode(s){emitsWrappingTags(s)&&(this.buffer+="")}value(){return this.buffer}span(s){this.buffer+=``}}class TokenTree{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(s){this.top.children.push(s)}openNode(s){const i={kind:s,children:[]};this.add(i),this.stack.push(i)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(s){return this.constructor._walk(s,this.rootNode)}static _walk(s,i){return"string"==typeof i?s.addText(i):i.children&&(s.openNode(i),i.children.forEach((i=>this._walk(s,i))),s.closeNode(i)),s}static _collapse(s){"string"!=typeof s&&s.children&&(s.children.every((s=>"string"==typeof s))?s.children=[s.children.join("")]:s.children.forEach((s=>{TokenTree._collapse(s)})))}}class TokenTreeEmitter extends TokenTree{constructor(s){super(),this.options=s}addKeyword(s,i){""!==s&&(this.openNode(i),this.addText(s),this.closeNode())}addText(s){""!==s&&this.add(s)}addSublanguage(s,i){const u=s.root;u.kind=i,u.sublanguage=!0,this.add(u)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return!0}}function source(s){return s?"string"==typeof s?s:s.source:null}const _=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;const w="[a-zA-Z]\\w*",x="[a-zA-Z_]\\w*",j="\\b\\d+(\\.\\d+)?",P="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",B="\\b(0b[01]+)",$={begin:"\\\\[\\s\\S]",relevance:0},U={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[$]},Y={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[$]},X={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},COMMENT=function(s,i,u={}){const _=inherit({className:"comment",begin:s,end:i,contains:[]},u);return _.contains.push(X),_.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),_},Z=COMMENT("//","$"),ee=COMMENT("/\\*","\\*/"),ie=COMMENT("#","$"),ae={className:"number",begin:j,relevance:0},le={className:"number",begin:P,relevance:0},ce={className:"number",begin:B,relevance:0},pe={className:"number",begin:j+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},de={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[$,{begin:/\[/,end:/\]/,relevance:0,contains:[$]}]}]},fe={className:"title",begin:w,relevance:0},ye={className:"title",begin:x,relevance:0},be={begin:"\\.\\s*"+x,relevance:0};var _e=Object.freeze({__proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:w,UNDERSCORE_IDENT_RE:x,NUMBER_RE:j,C_NUMBER_RE:P,BINARY_NUMBER_RE:B,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(s={})=>{const i=/^#![ ]*\//;return s.binary&&(s.begin=function concat(...s){return s.map((s=>source(s))).join("")}(i,/.*\b/,s.binary,/\b.*/)),inherit({className:"meta",begin:i,end:/$/,relevance:0,"on:begin":(s,i)=>{0!==s.index&&i.ignoreMatch()}},s)},BACKSLASH_ESCAPE:$,APOS_STRING_MODE:U,QUOTE_STRING_MODE:Y,PHRASAL_WORDS_MODE:X,COMMENT,C_LINE_COMMENT_MODE:Z,C_BLOCK_COMMENT_MODE:ee,HASH_COMMENT_MODE:ie,NUMBER_MODE:ae,C_NUMBER_MODE:le,BINARY_NUMBER_MODE:ce,CSS_NUMBER_MODE:pe,REGEXP_MODE:de,TITLE_MODE:fe,UNDERSCORE_TITLE_MODE:ye,METHOD_GUARD:be,END_SAME_AS_BEGIN:function(s){return Object.assign(s,{"on:begin":(s,i)=>{i.data._beginMatch=s[1]},"on:end":(s,i)=>{i.data._beginMatch!==s[1]&&i.ignoreMatch()}})}});function skipIfhasPrecedingDot(s,i){"."===s.input[s.index-1]&&i.ignoreMatch()}function beginKeywords(s,i){i&&s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",s.__beforeBegin=skipIfhasPrecedingDot,s.keywords=s.keywords||s.beginKeywords,delete s.beginKeywords,void 0===s.relevance&&(s.relevance=0))}function compileIllegal(s,i){Array.isArray(s.illegal)&&(s.illegal=function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}(...s.illegal))}function compileMatch(s,i){if(s.match){if(s.begin||s.end)throw new Error("begin & end are not supported with match");s.begin=s.match,delete s.match}}function compileRelevance(s,i){void 0===s.relevance&&(s.relevance=1)}const we=["of","and","for","in","not","or","if","then","parent","list","value"],Se="keyword";function compileKeywords(s,i,u=Se){const _={};return"string"==typeof s?compileList(u,s.split(" ")):Array.isArray(s)?compileList(u,s):Object.keys(s).forEach((function(u){Object.assign(_,compileKeywords(s[u],i,u))})),_;function compileList(s,u){i&&(u=u.map((s=>s.toLowerCase()))),u.forEach((function(i){const u=i.split("|");_[u[0]]=[s,scoreForKeyword(u[0],u[1])]}))}}function scoreForKeyword(s,i){return i?Number(i):function commonKeyword(s){return we.includes(s.toLowerCase())}(s)?0:1}function compileLanguage(s,{plugins:i}){function langRe(i,u){return new RegExp(source(i),"m"+(s.case_insensitive?"i":"")+(u?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(s,i){i.position=this.position++,this.matchIndexes[this.matchAt]=i,this.regexes.push([i,s]),this.matchAt+=function countMatchGroups(s){return new RegExp(s.toString()+"|").exec("").length-1}(s)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const s=this.regexes.map((s=>s[1]));this.matcherRe=langRe(function join(s,i="|"){let u=0;return s.map((s=>{u+=1;const i=u;let w=source(s),x="";for(;w.length>0;){const s=_.exec(w);if(!s){x+=w;break}x+=w.substring(0,s.index),w=w.substring(s.index+s[0].length),"\\"===s[0][0]&&s[1]?x+="\\"+String(Number(s[1])+i):(x+=s[0],"("===s[0]&&u++)}return x})).map((s=>`(${s})`)).join(i)}(s),!0),this.lastIndex=0}exec(s){this.matcherRe.lastIndex=this.lastIndex;const i=this.matcherRe.exec(s);if(!i)return null;const u=i.findIndex(((s,i)=>i>0&&void 0!==s)),_=this.matchIndexes[u];return i.splice(0,u),Object.assign(i,_)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(s){if(this.multiRegexes[s])return this.multiRegexes[s];const i=new MultiRegex;return this.rules.slice(s).forEach((([s,u])=>i.addRule(s,u))),i.compile(),this.multiRegexes[s]=i,i}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(s,i){this.rules.push([s,i]),"begin"===i.type&&this.count++}exec(s){const i=this.getMatcher(this.regexIndex);i.lastIndex=this.lastIndex;let u=i.exec(s);if(this.resumingScanAtSamePosition())if(u&&u.index===this.lastIndex);else{const i=this.getMatcher(0);i.lastIndex=this.lastIndex+1,u=i.exec(s)}return u&&(this.regexIndex+=u.position+1,this.regexIndex===this.count&&this.considerAll()),u}}if(s.compilerExtensions||(s.compilerExtensions=[]),s.contains&&s.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return s.classNameAliases=inherit(s.classNameAliases||{}),function compileMode(i,u){const _=i;if(i.isCompiled)return _;[compileMatch].forEach((s=>s(i,u))),s.compilerExtensions.forEach((s=>s(i,u))),i.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach((s=>s(i,u))),i.isCompiled=!0;let w=null;if("object"==typeof i.keywords&&(w=i.keywords.$pattern,delete i.keywords.$pattern),i.keywords&&(i.keywords=compileKeywords(i.keywords,s.case_insensitive)),i.lexemes&&w)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return w=w||i.lexemes||/\w+/,_.keywordPatternRe=langRe(w,!0),u&&(i.begin||(i.begin=/\B|\b/),_.beginRe=langRe(i.begin),i.endSameAsBegin&&(i.end=i.begin),i.end||i.endsWithParent||(i.end=/\B|\b/),i.end&&(_.endRe=langRe(i.end)),_.terminatorEnd=source(i.end)||"",i.endsWithParent&&u.terminatorEnd&&(_.terminatorEnd+=(i.end?"|":"")+u.terminatorEnd)),i.illegal&&(_.illegalRe=langRe(i.illegal)),i.contains||(i.contains=[]),i.contains=[].concat(...i.contains.map((function(s){return function expandOrCloneMode(s){s.variants&&!s.cachedVariants&&(s.cachedVariants=s.variants.map((function(i){return inherit(s,{variants:null},i)})));if(s.cachedVariants)return s.cachedVariants;if(dependencyOnParent(s))return inherit(s,{starts:s.starts?inherit(s.starts):null});if(Object.isFrozen(s))return inherit(s);return s}("self"===s?i:s)}))),i.contains.forEach((function(s){compileMode(s,_)})),i.starts&&compileMode(i.starts,u),_.matcher=function buildModeRegex(s){const i=new ResumableMultiRegex;return s.contains.forEach((s=>i.addRule(s.begin,{rule:s,type:"begin"}))),s.terminatorEnd&&i.addRule(s.terminatorEnd,{type:"end"}),s.illegal&&i.addRule(s.illegal,{type:"illegal"}),i}(_),_}(s)}function dependencyOnParent(s){return!!s&&(s.endsWithParent||dependencyOnParent(s.starts))}function BuildVuePlugin(s){const i={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!s.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,escapeHTML(this.code);let i={};return this.autoDetect?(i=s.highlightAuto(this.code),this.detectedLanguage=i.language):(i=s.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),i.value},autoDetect(){return!this.language||function hasValueOrEmptyAttribute(s){return Boolean(s||""===s)}(this.autodetect)},ignoreIllegals:()=>!0},render(s){return s("pre",{},[s("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:i,VuePlugin:{install(s){s.component("highlightjs",i)}}}}const xe={"after:highlightElement":({el:s,result:i,text:u})=>{const _=nodeStream(s);if(!_.length)return;const w=document.createElement("div");w.innerHTML=i.value,i.value=function mergeStreams(s,i,u){let _=0,w="";const x=[];function selectStream(){return s.length&&i.length?s[0].offset!==i[0].offset?s[0].offset"}function close(s){w+=""}function render(s){("start"===s.event?open:close)(s.node)}for(;s.length||i.length;){let i=selectStream();if(w+=escapeHTML(u.substring(_,i[0].offset)),_=i[0].offset,i===s){x.reverse().forEach(close);do{render(i.splice(0,1)[0]),i=selectStream()}while(i===s&&i.length&&i[0].offset===_);x.reverse().forEach(open)}else"start"===i[0].event?x.push(i[0].node):x.pop(),render(i.splice(0,1)[0])}return w+escapeHTML(u.substr(_))}(_,nodeStream(w),u)}};function tag(s){return s.nodeName.toLowerCase()}function nodeStream(s){const i=[];return function _nodeStream(s,u){for(let _=s.firstChild;_;_=_.nextSibling)3===_.nodeType?u+=_.nodeValue.length:1===_.nodeType&&(i.push({event:"start",offset:u,node:_}),u=_nodeStream(_,u),tag(_).match(/br|hr|img|input/)||i.push({event:"stop",offset:u,node:_}));return u}(s,0),i}const Pe={},error=s=>{console.error(s)},warn=(s,...i)=>{console.log(`WARN: ${s}`,...i)},deprecated=(s,i)=>{Pe[`${s}/${i}`]||(console.log(`Deprecated as of ${s}. ${i}`),Pe[`${s}/${i}`]=!0)},Te=escapeHTML,Re=inherit,qe=Symbol("nomatch");var $e=function(s){const u=Object.create(null),_=Object.create(null),w=[];let x=!0;const j=/(^(<[^>]+>|\t|)+|\n)/gm,P="Could not find the language '{}', did you forget to load/include a language module?",B={disableAutodetect:!0,name:"Plain text",contains:[]};let $={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(s){return $.noHighlightRe.test(s)}function highlight(s,i,u,_){let w="",x="";"object"==typeof i?(w=s,u=i.ignoreIllegals,x=i.language,_=void 0):(deprecated("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),x=s,w=i);const j={code:w,language:x};fire("before:highlight",j);const P=j.result?j.result:_highlight(j.language,j.code,u,_);return P.code=j.code,fire("after:highlight",P),P}function _highlight(s,i,_,j){function keywordData(s,i){const u=U.case_insensitive?i[0].toLowerCase():i[0];return Object.prototype.hasOwnProperty.call(s.keywords,u)&&s.keywords[u]}function processBuffer(){null!=Z.subLanguage?function processSubLanguage(){if(""===ae)return;let s=null;if("string"==typeof Z.subLanguage){if(!u[Z.subLanguage])return void ie.addText(ae);s=_highlight(Z.subLanguage,ae,!0,ee[Z.subLanguage]),ee[Z.subLanguage]=s.top}else s=highlightAuto(ae,Z.subLanguage.length?Z.subLanguage:null);Z.relevance>0&&(le+=s.relevance),ie.addSublanguage(s.emitter,s.language)}():function processKeywords(){if(!Z.keywords)return void ie.addText(ae);let s=0;Z.keywordPatternRe.lastIndex=0;let i=Z.keywordPatternRe.exec(ae),u="";for(;i;){u+=ae.substring(s,i.index);const _=keywordData(Z,i);if(_){const[s,w]=_;if(ie.addText(u),u="",le+=w,s.startsWith("_"))u+=i[0];else{const u=U.classNameAliases[s]||s;ie.addKeyword(i[0],u)}}else u+=i[0];s=Z.keywordPatternRe.lastIndex,i=Z.keywordPatternRe.exec(ae)}u+=ae.substr(s),ie.addText(u)}(),ae=""}function startNewMode(s){return s.className&&ie.openNode(U.classNameAliases[s.className]||s.className),Z=Object.create(s,{parent:{value:Z}}),Z}function endOfMode(s,i,u){let _=function startsWith(s,i){const u=s&&s.exec(i);return u&&0===u.index}(s.endRe,u);if(_){if(s["on:end"]){const u=new Response(s);s["on:end"](i,u),u.isMatchIgnored&&(_=!1)}if(_){for(;s.endsParent&&s.parent;)s=s.parent;return s}}if(s.endsWithParent)return endOfMode(s.parent,i,u)}function doIgnore(s){return 0===Z.matcher.regexIndex?(ae+=s[0],1):(de=!0,0)}function doBeginMatch(s){const i=s[0],u=s.rule,_=new Response(u),w=[u.__beforeBegin,u["on:begin"]];for(const u of w)if(u&&(u(s,_),_.isMatchIgnored))return doIgnore(i);return u&&u.endSameAsBegin&&(u.endRe=function escape(s){return new RegExp(s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(i)),u.skip?ae+=i:(u.excludeBegin&&(ae+=i),processBuffer(),u.returnBegin||u.excludeBegin||(ae=i)),startNewMode(u),u.returnBegin?0:i.length}function doEndMatch(s){const u=s[0],_=i.substr(s.index),w=endOfMode(Z,s,_);if(!w)return qe;const x=Z;x.skip?ae+=u:(x.returnEnd||x.excludeEnd||(ae+=u),processBuffer(),x.excludeEnd&&(ae=u));do{Z.className&&ie.closeNode(),Z.skip||Z.subLanguage||(le+=Z.relevance),Z=Z.parent}while(Z!==w.parent);return w.starts&&(w.endSameAsBegin&&(w.starts.endRe=w.endRe),startNewMode(w.starts)),x.returnEnd?0:u.length}let B={};function processLexeme(u,w){const j=w&&w[0];if(ae+=u,null==j)return processBuffer(),0;if("begin"===B.type&&"end"===w.type&&B.index===w.index&&""===j){if(ae+=i.slice(w.index,w.index+1),!x){const i=new Error("0 width match regex");throw i.languageName=s,i.badRule=B.rule,i}return 1}if(B=w,"begin"===w.type)return doBeginMatch(w);if("illegal"===w.type&&!_){const s=new Error('Illegal lexeme "'+j+'" for mode "'+(Z.className||"")+'"');throw s.mode=Z,s}if("end"===w.type){const s=doEndMatch(w);if(s!==qe)return s}if("illegal"===w.type&&""===j)return 1;if(pe>1e5&&pe>3*w.index){throw new Error("potential infinite loop, way more iterations than matches")}return ae+=j,j.length}const U=getLanguage(s);if(!U)throw error(P.replace("{}",s)),new Error('Unknown language: "'+s+'"');const Y=compileLanguage(U,{plugins:w});let X="",Z=j||Y;const ee={},ie=new $.__emitter($);!function processContinuations(){const s=[];for(let i=Z;i!==U;i=i.parent)i.className&&s.unshift(i.className);s.forEach((s=>ie.openNode(s)))}();let ae="",le=0,ce=0,pe=0,de=!1;try{for(Z.matcher.considerAll();;){pe++,de?de=!1:Z.matcher.considerAll(),Z.matcher.lastIndex=ce;const s=Z.matcher.exec(i);if(!s)break;const u=processLexeme(i.substring(ce,s.index),s);ce=s.index+u}return processLexeme(i.substr(ce)),ie.closeAllNodes(),ie.finalize(),X=ie.toHTML(),{relevance:Math.floor(le),value:X,language:s,illegal:!1,emitter:ie,top:Z}}catch(u){if(u.message&&u.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:u.message,context:i.slice(ce-100,ce+100),mode:u.mode},sofar:X,relevance:0,value:Te(i),emitter:ie};if(x)return{illegal:!1,relevance:0,value:Te(i),emitter:ie,language:s,top:Z,errorRaised:u};throw u}}function highlightAuto(s,i){i=i||$.languages||Object.keys(u);const _=function justTextHighlightResult(s){const i={relevance:0,emitter:new $.__emitter($),value:Te(s),illegal:!1,top:B};return i.emitter.addText(s),i}(s),w=i.filter(getLanguage).filter(autoDetection).map((i=>_highlight(i,s,!1)));w.unshift(_);const x=w.sort(((s,i)=>{if(s.relevance!==i.relevance)return i.relevance-s.relevance;if(s.language&&i.language){if(getLanguage(s.language).supersetOf===i.language)return 1;if(getLanguage(i.language).supersetOf===s.language)return-1}return 0})),[j,P]=x,U=j;return U.second_best=P,U}const U={"before:highlightElement":({el:s})=>{$.useBR&&(s.innerHTML=s.innerHTML.replace(/\n/g,"").replace(//g,"\n"))},"after:highlightElement":({result:s})=>{$.useBR&&(s.value=s.value.replace(/\n/g,"
"))}},Y=/^(<[^>]+>|\t)+/gm,X={"after:highlightElement":({result:s})=>{$.tabReplace&&(s.value=s.value.replace(Y,(s=>s.replace(/\t/g,$.tabReplace))))}};function highlightElement(s){let i=null;const u=function blockLanguage(s){let i=s.className+" ";i+=s.parentNode?s.parentNode.className:"";const u=$.languageDetectRe.exec(i);if(u){const i=getLanguage(u[1]);return i||(warn(P.replace("{}",u[1])),warn("Falling back to no-highlight mode for this block.",s)),i?u[1]:"no-highlight"}return i.split(/\s+/).find((s=>shouldNotHighlight(s)||getLanguage(s)))}(s);if(shouldNotHighlight(u))return;fire("before:highlightElement",{el:s,language:u}),i=s;const w=i.textContent,x=u?highlight(w,{language:u,ignoreIllegals:!0}):highlightAuto(w);fire("after:highlightElement",{el:s,result:x,text:w}),s.innerHTML=x.value,function updateClassName(s,i,u){const w=i?_[i]:u;s.classList.add("hljs"),w&&s.classList.add(w)}(s,u,x.language),s.result={language:x.language,re:x.relevance,relavance:x.relevance},x.second_best&&(s.second_best={language:x.second_best.language,re:x.second_best.relevance,relavance:x.second_best.relevance})}const initHighlighting=()=>{if(initHighlighting.called)return;initHighlighting.called=!0,deprecated("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead.");document.querySelectorAll("pre code").forEach(highlightElement)};let Z=!1;function highlightAll(){if("loading"===document.readyState)return void(Z=!0);document.querySelectorAll("pre code").forEach(highlightElement)}function getLanguage(s){return s=(s||"").toLowerCase(),u[s]||u[_[s]]}function registerAliases(s,{languageName:i}){"string"==typeof s&&(s=[s]),s.forEach((s=>{_[s.toLowerCase()]=i}))}function autoDetection(s){const i=getLanguage(s);return i&&!i.disableAutodetect}function fire(s,i){const u=s;w.forEach((function(s){s[u]&&s[u](i)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function boot(){Z&&highlightAll()}),!1),Object.assign(s,{highlight,highlightAuto,highlightAll,fixMarkup:function deprecateFixMarkup(s){return deprecated("10.2.0","fixMarkup will be removed entirely in v11.0"),deprecated("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),function fixMarkup(s){return $.tabReplace||$.useBR?s.replace(j,(s=>"\n"===s?$.useBR?"
":s:$.tabReplace?s.replace(/\t/g,$.tabReplace):s)):s}(s)},highlightElement,highlightBlock:function deprecateHighlightBlock(s){return deprecated("10.7.0","highlightBlock will be removed entirely in v12.0"),deprecated("10.7.0","Please use highlightElement now."),highlightElement(s)},configure:function configure(s){s.useBR&&(deprecated("10.3.0","'useBR' will be removed entirely in v11.0"),deprecated("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),$=Re($,s)},initHighlighting,initHighlightingOnLoad:function initHighlightingOnLoad(){deprecated("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),Z=!0},registerLanguage:function registerLanguage(i,_){let w=null;try{w=_(s)}catch(s){if(error("Language definition for '{}' could not be registered.".replace("{}",i)),!x)throw s;error(s),w=B}w.name||(w.name=i),u[i]=w,w.rawDefinition=_.bind(null,s),w.aliases&®isterAliases(w.aliases,{languageName:i})},unregisterLanguage:function unregisterLanguage(s){delete u[s];for(const i of Object.keys(_))_[i]===s&&delete _[i]},listLanguages:function listLanguages(){return Object.keys(u)},getLanguage,registerAliases,requireLanguage:function requireLanguage(s){deprecated("10.4.0","requireLanguage will be removed entirely in v11."),deprecated("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");const i=getLanguage(s);if(i)return i;throw new Error("The '{}' language is required, but not loaded.".replace("{}",s))},autoDetection,inherit:Re,addPlugin:function addPlugin(s){!function upgradePluginAPI(s){s["before:highlightBlock"]&&!s["before:highlightElement"]&&(s["before:highlightElement"]=i=>{s["before:highlightBlock"](Object.assign({block:i.el},i))}),s["after:highlightBlock"]&&!s["after:highlightElement"]&&(s["after:highlightElement"]=i=>{s["after:highlightBlock"](Object.assign({block:i.el},i))})}(s),w.push(s)},vuePlugin:BuildVuePlugin(s).VuePlugin}),s.debugMode=function(){x=!1},s.safeMode=function(){x=!0},s.versionString="10.7.3";for(const s in _e)"object"==typeof _e[s]&&i(_e[s]);return Object.assign(s,_e),s.addPlugin(U),s.addPlugin(xe),s.addPlugin(X),s}({});s.exports=$e},35344:s=>{function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function bash(s){const i={},u={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[i]}]};Object.assign(i,{className:"variable",variants:[{begin:concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},u]});const _={className:"subst",begin:/\$\(/,end:/\)/,contains:[s.BACKSLASH_ESCAPE]},w={begin:/<<-?\s*(?=\w+)/,starts:{contains:[s.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},x={className:"string",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE,i,_]};_.contains.push(x);const j={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},s.NUMBER_MODE,i]},P=s.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),B={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[s.inherit(s.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[P,s.SHEBANG(),B,j,s.HASH_COMMENT_MODE,w,x,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},i]}}},73402:s=>{function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function http(s){const i="HTTP/(2|1\\.[01])",u={className:"attribute",begin:concat("^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},_=[u,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+i+" \\d{3})",end:/$/,contains:[{className:"meta",begin:i},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:_}},{begin:"(?=^[A-Z]+ (.*?) "+i+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:i},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:_}},s.inherit(u,{relevance:0})]}}},95089:s=>{const i="[A-Za-z$_][0-9A-Za-z$_]*",u=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],_=["true","false","null","undefined","NaN","Infinity"],w=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer","BigInt64Array","BigUint64Array","BigInt"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function javascript(s){const x=i,j="<>",P="",B={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(s,i)=>{const u=s[0].length+s.index,_=s.input[u];"<"!==_?">"===_&&(((s,{after:i})=>{const u="",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:s.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:$,contains:fe}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:j,end:P},{begin:B.begin,"on:begin":B.isTrulyOpeningTag,end:B.end}],subLanguage:"xml",contains:[{begin:B.begin,end:B.end,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:$,contains:["self",s.inherit(s.TITLE_MODE,{begin:x}),ye],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:s.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[ye,s.inherit(s.TITLE_MODE,{begin:x})]},{variants:[{begin:"\\."+x},{begin:"\\$"+x}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},s.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[s.inherit(s.TITLE_MODE,{begin:x}),"self",ye]},{begin:"(get|set)\\s+(?="+x+"\\()",end:/\{/,keywords:"get set",contains:[s.inherit(s.TITLE_MODE,{begin:x}),{begin:/\(\)/},ye]},{begin:/\$[(.]/}]}}},65772:s=>{s.exports=function json(s){const i={literal:"true false null"},u=[s.C_LINE_COMMENT_MODE,s.C_BLOCK_COMMENT_MODE],_=[s.QUOTE_STRING_MODE,s.C_NUMBER_MODE],w={end:",",endsWithParent:!0,excludeEnd:!0,contains:_,keywords:i},x={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE],illegal:"\\n"},s.inherit(w,{begin:/:/})].concat(u),illegal:"\\S"},j={begin:"\\[",end:"\\]",contains:[s.inherit(w)],illegal:"\\S"};return _.push(x,j),u.forEach((function(s){_.push(s)})),{name:"JSON",contains:_,keywords:i,illegal:"\\S"}}},26571:s=>{s.exports=function powershell(s){const i={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},u={begin:"`[\\s\\S]",relevance:0},_={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},w={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[u,_,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},x={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},j=s.inherit(s.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),P={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},B={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[s.TITLE_MODE]},$={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[_]}]},U={begin:/using\s/,end:/$/,returnBegin:!0,contains:[w,x,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},Y={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-)[\w\d]+/,relevance:0}]},X={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(i.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},s.inherit(s.TITLE_MODE,{endsParent:!0})]},Z=[X,j,u,s.NUMBER_MODE,w,x,P,_,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],ee={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",Z,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return X.contains.unshift(ee),{name:"PowerShell",aliases:["ps","ps1"],case_insensitive:!0,keywords:i,contains:Z.concat(B,$,U,Y,ee)}}},17285:s=>{function source(s){return s?"string"==typeof s?s:s.source:null}function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>source(s))).join("")}function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}s.exports=function xml(s){const i=concat(/[A-Z_]/,function optional(s){return concat("(",s,")?")}(/[A-Z0-9_.-]*:/),/[A-Z0-9_.-]*/),u={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},_={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},w=s.inherit(_,{begin:/\(/,end:/\)/}),x=s.inherit(s.APOS_STRING_MODE,{className:"meta-string"}),j=s.inherit(s.QUOTE_STRING_MODE,{className:"meta-string"}),P={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[_,j,x,w,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[_,w,j,x]}]}]},s.COMMENT(//,{relevance:10}),{begin://,relevance:10},u,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[P],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[P],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:i,relevance:0,starts:P}]},{className:"tag",begin:concat(/<\//,lookahead(concat(i,/>/))),contains:[{className:"name",begin:i,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17533:s=>{s.exports=function yaml(s){var i="true false yes no null",u="[\\w#;/?:@&=+$,.~*'()[\\]]+",_={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[s.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},w=s.inherit(_,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),x={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},j={end:",",endsWithParent:!0,excludeEnd:!0,keywords:i,relevance:0},P={begin:/\{/,end:/\}/,contains:[j],illegal:"\\n",relevance:0},B={begin:"\\[",end:"\\]",contains:[j],illegal:"\\n",relevance:0},$=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+u},{className:"type",begin:"!<"+u+">"},{className:"type",begin:"!"+u},{className:"type",begin:"!!"+u},{className:"meta",begin:"&"+s.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+s.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},s.HASH_COMMENT_MODE,{beginKeywords:i,keywords:{literal:i}},x,{className:"number",begin:s.C_NUMBER_RE+"\\b",relevance:0},P,B,_],U=[...$];return U.pop(),U.push(w),j.contains=U,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:$}}},251:(s,i)=>{i.read=function(s,i,u,_,w){var x,j,P=8*w-_-1,B=(1<>1,U=-7,Y=u?w-1:0,X=u?-1:1,Z=s[i+Y];for(Y+=X,x=Z&(1<<-U)-1,Z>>=-U,U+=P;U>0;x=256*x+s[i+Y],Y+=X,U-=8);for(j=x&(1<<-U)-1,x>>=-U,U+=_;U>0;j=256*j+s[i+Y],Y+=X,U-=8);if(0===x)x=1-$;else{if(x===B)return j?NaN:1/0*(Z?-1:1);j+=Math.pow(2,_),x-=$}return(Z?-1:1)*j*Math.pow(2,x-_)},i.write=function(s,i,u,_,w,x){var j,P,B,$=8*x-w-1,U=(1<<$)-1,Y=U>>1,X=23===w?Math.pow(2,-24)-Math.pow(2,-77):0,Z=_?0:x-1,ee=_?1:-1,ie=i<0||0===i&&1/i<0?1:0;for(i=Math.abs(i),isNaN(i)||i===1/0?(P=isNaN(i)?1:0,j=U):(j=Math.floor(Math.log(i)/Math.LN2),i*(B=Math.pow(2,-j))<1&&(j--,B*=2),(i+=j+Y>=1?X/B:X*Math.pow(2,1-Y))*B>=2&&(j++,B/=2),j+Y>=U?(P=0,j=U):j+Y>=1?(P=(i*B-1)*Math.pow(2,w),j+=Y):(P=i*Math.pow(2,Y-1)*Math.pow(2,w),j=0));w>=8;s[u+Z]=255&P,Z+=ee,P/=256,w-=8);for(j=j<0;s[u+Z]=255&j,Z+=ee,j/=256,$-=8);s[u+Z-ee]|=128*ie}},9404:function(s){s.exports=function(){"use strict";var s=Array.prototype.slice;function createClass(s,i){i&&(s.prototype=Object.create(i.prototype)),s.prototype.constructor=s}function Iterable(s){return isIterable(s)?s:Seq(s)}function KeyedIterable(s){return isKeyed(s)?s:KeyedSeq(s)}function IndexedIterable(s){return isIndexed(s)?s:IndexedSeq(s)}function SetIterable(s){return isIterable(s)&&!isAssociative(s)?s:SetSeq(s)}function isIterable(s){return!(!s||!s[i])}function isKeyed(s){return!(!s||!s[u])}function isIndexed(s){return!(!s||!s[_])}function isAssociative(s){return isKeyed(s)||isIndexed(s)}function isOrdered(s){return!(!s||!s[w])}createClass(KeyedIterable,Iterable),createClass(IndexedIterable,Iterable),createClass(SetIterable,Iterable),Iterable.isIterable=isIterable,Iterable.isKeyed=isKeyed,Iterable.isIndexed=isIndexed,Iterable.isAssociative=isAssociative,Iterable.isOrdered=isOrdered,Iterable.Keyed=KeyedIterable,Iterable.Indexed=IndexedIterable,Iterable.Set=SetIterable;var i="@@__IMMUTABLE_ITERABLE__@@",u="@@__IMMUTABLE_KEYED__@@",_="@@__IMMUTABLE_INDEXED__@@",w="@@__IMMUTABLE_ORDERED__@@",x="delete",j=5,P=1<>>0;if(""+u!==i||4294967295===u)return NaN;i=u}return i<0?ensureSize(s)+i:i}function returnTrue(){return!0}function wholeSlice(s,i,u){return(0===s||void 0!==u&&s<=-u)&&(void 0===i||void 0!==u&&i>=u)}function resolveBegin(s,i){return resolveIndex(s,i,0)}function resolveEnd(s,i){return resolveIndex(s,i,i)}function resolveIndex(s,i,u){return void 0===s?u:s<0?Math.max(0,i+s):void 0===i?s:Math.min(i,s)}var X=0,Z=1,ee=2,ie="function"==typeof Symbol&&Symbol.iterator,ae="@@iterator",le=ie||ae;function Iterator(s){this.next=s}function iteratorValue(s,i,u,_){var w=0===s?i:1===s?u:[i,u];return _?_.value=w:_={value:w,done:!1},_}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(s){return!!getIteratorFn(s)}function isIterator(s){return s&&"function"==typeof s.next}function getIterator(s){var i=getIteratorFn(s);return i&&i.call(s)}function getIteratorFn(s){var i=s&&(ie&&s[ie]||s[ae]);if("function"==typeof i)return i}function isArrayLike(s){return s&&"number"==typeof s.length}function Seq(s){return null==s?emptySequence():isIterable(s)?s.toSeq():seqFromValue(s)}function KeyedSeq(s){return null==s?emptySequence().toKeyedSeq():isIterable(s)?isKeyed(s)?s.toSeq():s.fromEntrySeq():keyedSeqFromValue(s)}function IndexedSeq(s){return null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s.toIndexedSeq():indexedSeqFromValue(s)}function SetSeq(s){return(null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s:indexedSeqFromValue(s)).toSetSeq()}Iterator.prototype.toString=function(){return"[Iterator]"},Iterator.KEYS=X,Iterator.VALUES=Z,Iterator.ENTRIES=ee,Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()},Iterator.prototype[le]=function(){return this},createClass(Seq,Iterable),Seq.of=function(){return Seq(arguments)},Seq.prototype.toSeq=function(){return this},Seq.prototype.toString=function(){return this.__toString("Seq {","}")},Seq.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},Seq.prototype.__iterate=function(s,i){return seqIterate(this,s,i,!0)},Seq.prototype.__iterator=function(s,i){return seqIterator(this,s,i,!0)},createClass(KeyedSeq,Seq),KeyedSeq.prototype.toKeyedSeq=function(){return this},createClass(IndexedSeq,Seq),IndexedSeq.of=function(){return IndexedSeq(arguments)},IndexedSeq.prototype.toIndexedSeq=function(){return this},IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")},IndexedSeq.prototype.__iterate=function(s,i){return seqIterate(this,s,i,!1)},IndexedSeq.prototype.__iterator=function(s,i){return seqIterator(this,s,i,!1)},createClass(SetSeq,Seq),SetSeq.of=function(){return SetSeq(arguments)},SetSeq.prototype.toSetSeq=function(){return this},Seq.isSeq=isSeq,Seq.Keyed=KeyedSeq,Seq.Set=SetSeq,Seq.Indexed=IndexedSeq;var ce,pe,de,fe="@@__IMMUTABLE_SEQ__@@";function ArraySeq(s){this._array=s,this.size=s.length}function ObjectSeq(s){var i=Object.keys(s);this._object=s,this._keys=i,this.size=i.length}function IterableSeq(s){this._iterable=s,this.size=s.length||s.size}function IteratorSeq(s){this._iterator=s,this._iteratorCache=[]}function isSeq(s){return!(!s||!s[fe])}function emptySequence(){return ce||(ce=new ArraySeq([]))}function keyedSeqFromValue(s){var i=Array.isArray(s)?new ArraySeq(s).fromEntrySeq():isIterator(s)?new IteratorSeq(s).fromEntrySeq():hasIterator(s)?new IterableSeq(s).fromEntrySeq():"object"==typeof s?new ObjectSeq(s):void 0;if(!i)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+s);return i}function indexedSeqFromValue(s){var i=maybeIndexedSeqFromValue(s);if(!i)throw new TypeError("Expected Array or iterable object of values: "+s);return i}function seqFromValue(s){var i=maybeIndexedSeqFromValue(s)||"object"==typeof s&&new ObjectSeq(s);if(!i)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+s);return i}function maybeIndexedSeqFromValue(s){return isArrayLike(s)?new ArraySeq(s):isIterator(s)?new IteratorSeq(s):hasIterator(s)?new IterableSeq(s):void 0}function seqIterate(s,i,u,_){var w=s._cache;if(w){for(var x=w.length-1,j=0;j<=x;j++){var P=w[u?x-j:j];if(!1===i(P[1],_?P[0]:j,s))return j+1}return j}return s.__iterateUncached(i,u)}function seqIterator(s,i,u,_){var w=s._cache;if(w){var x=w.length-1,j=0;return new Iterator((function(){var s=w[u?x-j:j];return j++>x?iteratorDone():iteratorValue(i,_?s[0]:j-1,s[1])}))}return s.__iteratorUncached(i,u)}function fromJS(s,i){return i?fromJSWith(i,s,"",{"":s}):fromJSDefault(s)}function fromJSWith(s,i,u,_){return Array.isArray(i)?s.call(_,u,IndexedSeq(i).map((function(u,_){return fromJSWith(s,u,_,i)}))):isPlainObj(i)?s.call(_,u,KeyedSeq(i).map((function(u,_){return fromJSWith(s,u,_,i)}))):i}function fromJSDefault(s){return Array.isArray(s)?IndexedSeq(s).map(fromJSDefault).toList():isPlainObj(s)?KeyedSeq(s).map(fromJSDefault).toMap():s}function isPlainObj(s){return s&&(s.constructor===Object||void 0===s.constructor)}function is(s,i){if(s===i||s!=s&&i!=i)return!0;if(!s||!i)return!1;if("function"==typeof s.valueOf&&"function"==typeof i.valueOf){if((s=s.valueOf())===(i=i.valueOf())||s!=s&&i!=i)return!0;if(!s||!i)return!1}return!("function"!=typeof s.equals||"function"!=typeof i.equals||!s.equals(i))}function deepEqual(s,i){if(s===i)return!0;if(!isIterable(i)||void 0!==s.size&&void 0!==i.size&&s.size!==i.size||void 0!==s.__hash&&void 0!==i.__hash&&s.__hash!==i.__hash||isKeyed(s)!==isKeyed(i)||isIndexed(s)!==isIndexed(i)||isOrdered(s)!==isOrdered(i))return!1;if(0===s.size&&0===i.size)return!0;var u=!isAssociative(s);if(isOrdered(s)){var _=s.entries();return i.every((function(s,i){var w=_.next().value;return w&&is(w[1],s)&&(u||is(w[0],i))}))&&_.next().done}var w=!1;if(void 0===s.size)if(void 0===i.size)"function"==typeof s.cacheResult&&s.cacheResult();else{w=!0;var x=s;s=i,i=x}var j=!0,P=i.__iterate((function(i,_){if(u?!s.has(i):w?!is(i,s.get(_,$)):!is(s.get(_,$),i))return j=!1,!1}));return j&&s.size===P}function Repeat(s,i){if(!(this instanceof Repeat))return new Repeat(s,i);if(this._value=s,this.size=void 0===i?1/0:Math.max(0,i),0===this.size){if(pe)return pe;pe=this}}function invariant(s,i){if(!s)throw new Error(i)}function Range(s,i,u){if(!(this instanceof Range))return new Range(s,i,u);if(invariant(0!==u,"Cannot step a Range by 0"),s=s||0,void 0===i&&(i=1/0),u=void 0===u?1:Math.abs(u),i_?iteratorDone():iteratorValue(s,w,u[i?_-w++:w++])}))},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(s,i){return void 0===i||this.has(s)?this._object[s]:i},ObjectSeq.prototype.has=function(s){return this._object.hasOwnProperty(s)},ObjectSeq.prototype.__iterate=function(s,i){for(var u=this._object,_=this._keys,w=_.length-1,x=0;x<=w;x++){var j=_[i?w-x:x];if(!1===s(u[j],j,this))return x+1}return x},ObjectSeq.prototype.__iterator=function(s,i){var u=this._object,_=this._keys,w=_.length-1,x=0;return new Iterator((function(){var j=_[i?w-x:x];return x++>w?iteratorDone():iteratorValue(s,j,u[j])}))},ObjectSeq.prototype[w]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(s,i){if(i)return this.cacheResult().__iterate(s,i);var u=getIterator(this._iterable),_=0;if(isIterator(u))for(var w;!(w=u.next()).done&&!1!==s(w.value,_++,this););return _},IterableSeq.prototype.__iteratorUncached=function(s,i){if(i)return this.cacheResult().__iterator(s,i);var u=getIterator(this._iterable);if(!isIterator(u))return new Iterator(iteratorDone);var _=0;return new Iterator((function(){var i=u.next();return i.done?i:iteratorValue(s,_++,i.value)}))},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(s,i){if(i)return this.cacheResult().__iterate(s,i);for(var u,_=this._iterator,w=this._iteratorCache,x=0;x=_.length){var i=u.next();if(i.done)return i;_[w]=i.value}return iteratorValue(s,w,_[w++])}))},createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(s,i){return this.has(s)?this._value:i},Repeat.prototype.includes=function(s){return is(this._value,s)},Repeat.prototype.slice=function(s,i){var u=this.size;return wholeSlice(s,i,u)?this:new Repeat(this._value,resolveEnd(i,u)-resolveBegin(s,u))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(s){return is(this._value,s)?0:-1},Repeat.prototype.lastIndexOf=function(s){return is(this._value,s)?this.size:-1},Repeat.prototype.__iterate=function(s,i){for(var u=0;u=0&&i=0&&uu?iteratorDone():iteratorValue(s,x++,j)}))},Range.prototype.equals=function(s){return s instanceof Range?this._start===s._start&&this._end===s._end&&this._step===s._step:deepEqual(this,s)},createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var ye="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function imul(s,i){var u=65535&(s|=0),_=65535&(i|=0);return u*_+((s>>>16)*_+u*(i>>>16)<<16>>>0)|0};function smi(s){return s>>>1&1073741824|3221225471&s}function hash(s){if(!1===s||null==s)return 0;if("function"==typeof s.valueOf&&(!1===(s=s.valueOf())||null==s))return 0;if(!0===s)return 1;var i=typeof s;if("number"===i){if(s!=s||s===1/0)return 0;var u=0|s;for(u!==s&&(u^=4294967295*s);s>4294967295;)u^=s/=4294967295;return smi(u)}if("string"===i)return s.length>Te?cachedHashString(s):hashString(s);if("function"==typeof s.hashCode)return s.hashCode();if("object"===i)return hashJSObj(s);if("function"==typeof s.toString)return hashString(s.toString());throw new Error("Value type "+i+" cannot be hashed.")}function cachedHashString(s){var i=$e[s];return void 0===i&&(i=hashString(s),qe===Re&&(qe=0,$e={}),qe++,$e[s]=i),i}function hashString(s){for(var i=0,u=0;u0)switch(s.nodeType){case 1:return s.uniqueID;case 9:return s.documentElement&&s.documentElement.uniqueID}}var we,Se="function"==typeof WeakMap;Se&&(we=new WeakMap);var xe=0,Pe="__immutablehash__";"function"==typeof Symbol&&(Pe=Symbol(Pe));var Te=16,Re=255,qe=0,$e={};function assertNotInfinite(s){invariant(s!==1/0,"Cannot perform this action with an infinite size.")}function Map(s){return null==s?emptyMap():isMap(s)&&!isOrdered(s)?s:emptyMap().withMutations((function(i){var u=KeyedIterable(s);assertNotInfinite(u.size),u.forEach((function(s,u){return i.set(u,s)}))}))}function isMap(s){return!(!s||!s[We])}createClass(Map,KeyedCollection),Map.of=function(){var i=s.call(arguments,0);return emptyMap().withMutations((function(s){for(var u=0;u=i.length)throw new Error("Missing value for key: "+i[u]);s.set(i[u],i[u+1])}}))},Map.prototype.toString=function(){return this.__toString("Map {","}")},Map.prototype.get=function(s,i){return this._root?this._root.get(0,void 0,s,i):i},Map.prototype.set=function(s,i){return updateMap(this,s,i)},Map.prototype.setIn=function(s,i){return this.updateIn(s,$,(function(){return i}))},Map.prototype.remove=function(s){return updateMap(this,s,$)},Map.prototype.deleteIn=function(s){return this.updateIn(s,(function(){return $}))},Map.prototype.update=function(s,i,u){return 1===arguments.length?s(this):this.updateIn([s],i,u)},Map.prototype.updateIn=function(s,i,u){u||(u=i,i=void 0);var _=updateInDeepMap(this,forceIterator(s),i,u);return _===$?void 0:_},Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},Map.prototype.mergeWith=function(i){return mergeIntoMapWith(this,i,s.call(arguments,1))},Map.prototype.mergeIn=function(i){var u=s.call(arguments,1);return this.updateIn(i,emptyMap(),(function(s){return"function"==typeof s.merge?s.merge.apply(s,u):u[u.length-1]}))},Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)},Map.prototype.mergeDeepWith=function(i){var u=s.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(i),u)},Map.prototype.mergeDeepIn=function(i){var u=s.call(arguments,1);return this.updateIn(i,emptyMap(),(function(s){return"function"==typeof s.mergeDeep?s.mergeDeep.apply(s,u):u[u.length-1]}))},Map.prototype.sort=function(s){return OrderedMap(sortFactory(this,s))},Map.prototype.sortBy=function(s,i){return OrderedMap(sortFactory(this,i,s))},Map.prototype.withMutations=function(s){var i=this.asMutable();return s(i),i.wasAltered()?i.__ensureOwner(this.__ownerID):this},Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},Map.prototype.asImmutable=function(){return this.__ensureOwner()},Map.prototype.wasAltered=function(){return this.__altered},Map.prototype.__iterator=function(s,i){return new MapIterator(this,s,i)},Map.prototype.__iterate=function(s,i){var u=this,_=0;return this._root&&this._root.iterate((function(i){return _++,s(i[1],i[0],u)}),i),_},Map.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeMap(this.size,this._root,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Map.isMap=isMap;var ze,We="@@__IMMUTABLE_MAP__@@",He=Map.prototype;function ArrayMapNode(s,i){this.ownerID=s,this.entries=i}function BitmapIndexedNode(s,i,u){this.ownerID=s,this.bitmap=i,this.nodes=u}function HashArrayMapNode(s,i,u){this.ownerID=s,this.count=i,this.nodes=u}function HashCollisionNode(s,i,u){this.ownerID=s,this.keyHash=i,this.entries=u}function ValueNode(s,i,u){this.ownerID=s,this.keyHash=i,this.entry=u}function MapIterator(s,i,u){this._type=i,this._reverse=u,this._stack=s._root&&mapIteratorFrame(s._root)}function mapIteratorValue(s,i){return iteratorValue(s,i[0],i[1])}function mapIteratorFrame(s,i){return{node:s,index:0,__prev:i}}function makeMap(s,i,u,_){var w=Object.create(He);return w.size=s,w._root=i,w.__ownerID=u,w.__hash=_,w.__altered=!1,w}function emptyMap(){return ze||(ze=makeMap(0))}function updateMap(s,i,u){var _,w;if(s._root){var x=MakeRef(U),j=MakeRef(Y);if(_=updateNode(s._root,s.__ownerID,0,void 0,i,u,x,j),!j.value)return s;w=s.size+(x.value?u===$?-1:1:0)}else{if(u===$)return s;w=1,_=new ArrayMapNode(s.__ownerID,[[i,u]])}return s.__ownerID?(s.size=w,s._root=_,s.__hash=void 0,s.__altered=!0,s):_?makeMap(w,_):emptyMap()}function updateNode(s,i,u,_,w,x,j,P){return s?s.update(i,u,_,w,x,j,P):x===$?s:(SetRef(P),SetRef(j),new ValueNode(i,_,[w,x]))}function isLeafNode(s){return s.constructor===ValueNode||s.constructor===HashCollisionNode}function mergeIntoNode(s,i,u,_,w){if(s.keyHash===_)return new HashCollisionNode(i,_,[s.entry,w]);var x,P=(0===u?s.keyHash:s.keyHash>>>u)&B,$=(0===u?_:_>>>u)&B;return new BitmapIndexedNode(i,1<>>=1)j[B]=1&u?i[x++]:void 0;return j[_]=w,new HashArrayMapNode(s,x+1,j)}function mergeIntoMapWith(s,i,u){for(var _=[],w=0;w>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135,s+=s>>8,127&(s+=s>>16)}function setIn(s,i,u,_){var w=_?s:arrCopy(s);return w[i]=u,w}function spliceIn(s,i,u,_){var w=s.length+1;if(_&&i+1===w)return s[i]=u,s;for(var x=new Array(w),j=0,P=0;P=Ye)return createNodes(s,B,_,w);var Z=s&&s===this.ownerID,ee=Z?B:arrCopy(B);return X?P?U===Y-1?ee.pop():ee[U]=ee.pop():ee[U]=[_,w]:ee.push([_,w]),Z?(this.entries=ee,this):new ArrayMapNode(s,ee)}},BitmapIndexedNode.prototype.get=function(s,i,u,_){void 0===i&&(i=hash(u));var w=1<<((0===s?i:i>>>s)&B),x=this.bitmap;return 0==(x&w)?_:this.nodes[popCount(x&w-1)].get(s+j,i,u,_)},BitmapIndexedNode.prototype.update=function(s,i,u,_,w,x,P){void 0===u&&(u=hash(_));var U=(0===i?u:u>>>i)&B,Y=1<=Xe)return expandNodes(s,ie,X,U,le);if(Z&&!le&&2===ie.length&&isLeafNode(ie[1^ee]))return ie[1^ee];if(Z&&le&&1===ie.length&&isLeafNode(le))return le;var ce=s&&s===this.ownerID,pe=Z?le?X:X^Y:X|Y,de=Z?le?setIn(ie,ee,le,ce):spliceOut(ie,ee,ce):spliceIn(ie,ee,le,ce);return ce?(this.bitmap=pe,this.nodes=de,this):new BitmapIndexedNode(s,pe,de)},HashArrayMapNode.prototype.get=function(s,i,u,_){void 0===i&&(i=hash(u));var w=(0===s?i:i>>>s)&B,x=this.nodes[w];return x?x.get(s+j,i,u,_):_},HashArrayMapNode.prototype.update=function(s,i,u,_,w,x,P){void 0===u&&(u=hash(_));var U=(0===i?u:u>>>i)&B,Y=w===$,X=this.nodes,Z=X[U];if(Y&&!Z)return this;var ee=updateNode(Z,s,i+j,u,_,w,x,P);if(ee===Z)return this;var ie=this.count;if(Z){if(!ee&&--ie0&&_=0&&s>>i&B;if(_>=this.array.length)return new VNode([],s);var w,x=0===_;if(i>0){var P=this.array[_];if((w=P&&P.removeBefore(s,i-j,u))===P&&x)return this}if(x&&!w)return this;var $=editableVNode(this,s);if(!x)for(var U=0;U<_;U++)$.array[U]=void 0;return w&&($.array[_]=w),$},VNode.prototype.removeAfter=function(s,i,u){if(u===(i?1<>>i&B;if(w>=this.array.length)return this;if(i>0){var x=this.array[w];if((_=x&&x.removeAfter(s,i-j,u))===x&&w===this.array.length-1)return this}var P=editableVNode(this,s);return P.array.splice(w+1),_&&(P.array[w]=_),P};var rt,nt,ot={};function iterateList(s,i){var u=s._origin,_=s._capacity,w=getTailOffset(_),x=s._tail;return iterateNodeOrLeaf(s._root,s._level,0);function iterateNodeOrLeaf(s,i,u){return 0===i?iterateLeaf(s,u):iterateNode(s,i,u)}function iterateLeaf(s,j){var B=j===w?x&&x.array:s&&s.array,$=j>u?0:u-j,U=_-j;return U>P&&(U=P),function(){if($===U)return ot;var s=i?--U:$++;return B&&B[s]}}function iterateNode(s,w,x){var B,$=s&&s.array,U=x>u?0:u-x>>w,Y=1+(_-x>>w);return Y>P&&(Y=P),function(){for(;;){if(B){var s=B();if(s!==ot)return s;B=null}if(U===Y)return ot;var u=i?--Y:U++;B=iterateNodeOrLeaf($&&$[u],w-j,x+(u<=s.size||i<0)return s.withMutations((function(s){i<0?setListBounds(s,i).set(0,u):setListBounds(s,0,i+1).set(i,u)}));i+=s._origin;var _=s._tail,w=s._root,x=MakeRef(Y);return i>=getTailOffset(s._capacity)?_=updateVNode(_,s.__ownerID,0,i,u,x):w=updateVNode(w,s.__ownerID,s._level,i,u,x),x.value?s.__ownerID?(s._root=w,s._tail=_,s.__hash=void 0,s.__altered=!0,s):makeList(s._origin,s._capacity,s._level,w,_):s}function updateVNode(s,i,u,_,w,x){var P,$=_>>>u&B,U=s&&$0){var Y=s&&s.array[$],X=updateVNode(Y,i,u-j,_,w,x);return X===Y?s:((P=editableVNode(s,i)).array[$]=X,P)}return U&&s.array[$]===w?s:(SetRef(x),P=editableVNode(s,i),void 0===w&&$===P.array.length-1?P.array.pop():P.array[$]=w,P)}function editableVNode(s,i){return i&&s&&i===s.ownerID?s:new VNode(s?s.array.slice():[],i)}function listNodeFor(s,i){if(i>=getTailOffset(s._capacity))return s._tail;if(i<1<0;)u=u.array[i>>>_&B],_-=j;return u}}function setListBounds(s,i,u){void 0!==i&&(i|=0),void 0!==u&&(u|=0);var _=s.__ownerID||new OwnerID,w=s._origin,x=s._capacity,P=w+i,$=void 0===u?x:u<0?x+u:w+u;if(P===w&&$===x)return s;if(P>=$)return s.clear();for(var U=s._level,Y=s._root,X=0;P+X<0;)Y=new VNode(Y&&Y.array.length?[void 0,Y]:[],_),X+=1<<(U+=j);X&&(P+=X,w+=X,$+=X,x+=X);for(var Z=getTailOffset(x),ee=getTailOffset($);ee>=1<Z?new VNode([],_):ie;if(ie&&ee>Z&&Pj;ce-=j){var pe=Z>>>ce&B;le=le.array[pe]=editableVNode(le.array[pe],_)}le.array[Z>>>j&B]=ie}if($=ee)P-=ee,$-=ee,U=j,Y=null,ae=ae&&ae.removeBefore(_,0,P);else if(P>w||ee>>U&B;if(de!==ee>>>U&B)break;de&&(X+=(1<w&&(Y=Y.removeBefore(_,U,P-X)),Y&&eew&&(w=P.size),isIterable(j)||(P=P.map((function(s){return fromJS(s)}))),_.push(P)}return w>s.size&&(s=s.setSize(w)),mergeIntoCollectionWith(s,i,_)}function getTailOffset(s){return s>>j<=P&&j.size>=2*x.size?(_=(w=j.filter((function(s,i){return void 0!==s&&B!==i}))).toKeyedSeq().map((function(s){return s[0]})).flip().toMap(),s.__ownerID&&(_.__ownerID=w.__ownerID=s.__ownerID)):(_=x.remove(i),w=B===j.size-1?j.pop():j.set(B,void 0))}else if(U){if(u===j.get(B)[1])return s;_=x,w=j.set(B,[i,u])}else _=x.set(i,j.size),w=j.set(j.size,[i,u]);return s.__ownerID?(s.size=_.size,s._map=_,s._list=w,s.__hash=void 0,s):makeOrderedMap(_,w)}function ToKeyedSequence(s,i){this._iter=s,this._useKeys=i,this.size=s.size}function ToIndexedSequence(s){this._iter=s,this.size=s.size}function ToSetSequence(s){this._iter=s,this.size=s.size}function FromEntriesSequence(s){this._iter=s,this.size=s.size}function flipFactory(s){var i=makeSequence(s);return i._iter=s,i.size=s.size,i.flip=function(){return s},i.reverse=function(){var i=s.reverse.apply(this);return i.flip=function(){return s.reverse()},i},i.has=function(i){return s.includes(i)},i.includes=function(i){return s.has(i)},i.cacheResult=cacheResultThrough,i.__iterateUncached=function(i,u){var _=this;return s.__iterate((function(s,u){return!1!==i(u,s,_)}),u)},i.__iteratorUncached=function(i,u){if(i===ee){var _=s.__iterator(i,u);return new Iterator((function(){var s=_.next();if(!s.done){var i=s.value[0];s.value[0]=s.value[1],s.value[1]=i}return s}))}return s.__iterator(i===Z?X:Z,u)},i}function mapFactory(s,i,u){var _=makeSequence(s);return _.size=s.size,_.has=function(i){return s.has(i)},_.get=function(_,w){var x=s.get(_,$);return x===$?w:i.call(u,x,_,s)},_.__iterateUncached=function(_,w){var x=this;return s.__iterate((function(s,w,j){return!1!==_(i.call(u,s,w,j),w,x)}),w)},_.__iteratorUncached=function(_,w){var x=s.__iterator(ee,w);return new Iterator((function(){var w=x.next();if(w.done)return w;var j=w.value,P=j[0];return iteratorValue(_,P,i.call(u,j[1],P,s),w)}))},_}function reverseFactory(s,i){var u=makeSequence(s);return u._iter=s,u.size=s.size,u.reverse=function(){return s},s.flip&&(u.flip=function(){var i=flipFactory(s);return i.reverse=function(){return s.flip()},i}),u.get=function(u,_){return s.get(i?u:-1-u,_)},u.has=function(u){return s.has(i?u:-1-u)},u.includes=function(i){return s.includes(i)},u.cacheResult=cacheResultThrough,u.__iterate=function(i,u){var _=this;return s.__iterate((function(s,u){return i(s,u,_)}),!u)},u.__iterator=function(i,u){return s.__iterator(i,!u)},u}function filterFactory(s,i,u,_){var w=makeSequence(s);return _&&(w.has=function(_){var w=s.get(_,$);return w!==$&&!!i.call(u,w,_,s)},w.get=function(_,w){var x=s.get(_,$);return x!==$&&i.call(u,x,_,s)?x:w}),w.__iterateUncached=function(w,x){var j=this,P=0;return s.__iterate((function(s,x,B){if(i.call(u,s,x,B))return P++,w(s,_?x:P-1,j)}),x),P},w.__iteratorUncached=function(w,x){var j=s.__iterator(ee,x),P=0;return new Iterator((function(){for(;;){var x=j.next();if(x.done)return x;var B=x.value,$=B[0],U=B[1];if(i.call(u,U,$,s))return iteratorValue(w,_?$:P++,U,x)}}))},w}function countByFactory(s,i,u){var _=Map().asMutable();return s.__iterate((function(w,x){_.update(i.call(u,w,x,s),0,(function(s){return s+1}))})),_.asImmutable()}function groupByFactory(s,i,u){var _=isKeyed(s),w=(isOrdered(s)?OrderedMap():Map()).asMutable();s.__iterate((function(x,j){w.update(i.call(u,x,j,s),(function(s){return(s=s||[]).push(_?[j,x]:x),s}))}));var x=iterableClass(s);return w.map((function(i){return reify(s,x(i))}))}function sliceFactory(s,i,u,_){var w=s.size;if(void 0!==i&&(i|=0),void 0!==u&&(u===1/0?u=w:u|=0),wholeSlice(i,u,w))return s;var x=resolveBegin(i,w),j=resolveEnd(u,w);if(x!=x||j!=j)return sliceFactory(s.toSeq().cacheResult(),i,u,_);var P,B=j-x;B==B&&(P=B<0?0:B);var $=makeSequence(s);return $.size=0===P?P:s.size&&P||void 0,!_&&isSeq(s)&&P>=0&&($.get=function(i,u){return(i=wrapIndex(this,i))>=0&&iP)return iteratorDone();var s=w.next();return _||i===Z?s:iteratorValue(i,B-1,i===X?void 0:s.value[1],s)}))},$}function takeWhileFactory(s,i,u){var _=makeSequence(s);return _.__iterateUncached=function(_,w){var x=this;if(w)return this.cacheResult().__iterate(_,w);var j=0;return s.__iterate((function(s,w,P){return i.call(u,s,w,P)&&++j&&_(s,w,x)})),j},_.__iteratorUncached=function(_,w){var x=this;if(w)return this.cacheResult().__iterator(_,w);var j=s.__iterator(ee,w),P=!0;return new Iterator((function(){if(!P)return iteratorDone();var s=j.next();if(s.done)return s;var w=s.value,B=w[0],$=w[1];return i.call(u,$,B,x)?_===ee?s:iteratorValue(_,B,$,s):(P=!1,iteratorDone())}))},_}function skipWhileFactory(s,i,u,_){var w=makeSequence(s);return w.__iterateUncached=function(w,x){var j=this;if(x)return this.cacheResult().__iterate(w,x);var P=!0,B=0;return s.__iterate((function(s,x,$){if(!P||!(P=i.call(u,s,x,$)))return B++,w(s,_?x:B-1,j)})),B},w.__iteratorUncached=function(w,x){var j=this;if(x)return this.cacheResult().__iterator(w,x);var P=s.__iterator(ee,x),B=!0,$=0;return new Iterator((function(){var s,x,U;do{if((s=P.next()).done)return _||w===Z?s:iteratorValue(w,$++,w===X?void 0:s.value[1],s);var Y=s.value;x=Y[0],U=Y[1],B&&(B=i.call(u,U,x,j))}while(B);return w===ee?s:iteratorValue(w,x,U,s)}))},w}function concatFactory(s,i){var u=isKeyed(s),_=[s].concat(i).map((function(s){return isIterable(s)?u&&(s=KeyedIterable(s)):s=u?keyedSeqFromValue(s):indexedSeqFromValue(Array.isArray(s)?s:[s]),s})).filter((function(s){return 0!==s.size}));if(0===_.length)return s;if(1===_.length){var w=_[0];if(w===s||u&&isKeyed(w)||isIndexed(s)&&isIndexed(w))return w}var x=new ArraySeq(_);return u?x=x.toKeyedSeq():isIndexed(s)||(x=x.toSetSeq()),(x=x.flatten(!0)).size=_.reduce((function(s,i){if(void 0!==s){var u=i.size;if(void 0!==u)return s+u}}),0),x}function flattenFactory(s,i,u){var _=makeSequence(s);return _.__iterateUncached=function(_,w){var x=0,j=!1;function flatDeep(s,P){var B=this;s.__iterate((function(s,w){return(!i||P0}function zipWithFactory(s,i,u){var _=makeSequence(s);return _.size=new ArraySeq(u).map((function(s){return s.size})).min(),_.__iterate=function(s,i){for(var u,_=this.__iterator(Z,i),w=0;!(u=_.next()).done&&!1!==s(u.value,w++,this););return w},_.__iteratorUncached=function(s,_){var w=u.map((function(s){return s=Iterable(s),getIterator(_?s.reverse():s)})),x=0,j=!1;return new Iterator((function(){var u;return j||(u=w.map((function(s){return s.next()})),j=u.some((function(s){return s.done}))),j?iteratorDone():iteratorValue(s,x++,i.apply(null,u.map((function(s){return s.value}))))}))},_}function reify(s,i){return isSeq(s)?i:s.constructor(i)}function validateEntry(s){if(s!==Object(s))throw new TypeError("Expected [K, V] tuple: "+s)}function resolveSize(s){return assertNotInfinite(s.size),ensureSize(s)}function iterableClass(s){return isKeyed(s)?KeyedIterable:isIndexed(s)?IndexedIterable:SetIterable}function makeSequence(s){return Object.create((isKeyed(s)?KeyedSeq:isIndexed(s)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(s,i){return s>i?1:s=0;u--)i={value:arguments[u],next:i};return this.__ownerID?(this.size=s,this._head=i,this.__hash=void 0,this.__altered=!0,this):makeStack(s,i)},Stack.prototype.pushAll=function(s){if(0===(s=IndexedIterable(s)).size)return this;assertNotInfinite(s.size);var i=this.size,u=this._head;return s.reverse().forEach((function(s){i++,u={value:s,next:u}})),this.__ownerID?(this.size=i,this._head=u,this.__hash=void 0,this.__altered=!0,this):makeStack(i,u)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(s){return this.pushAll(s)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(s,i){if(wholeSlice(s,i,this.size))return this;var u=resolveBegin(s,this.size);if(resolveEnd(i,this.size)!==this.size)return IndexedCollection.prototype.slice.call(this,s,i);for(var _=this.size-u,w=this._head;u--;)w=w.next;return this.__ownerID?(this.size=_,this._head=w,this.__hash=void 0,this.__altered=!0,this):makeStack(_,w)},Stack.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeStack(this.size,this._head,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Stack.prototype.__iterate=function(s,i){if(i)return this.reverse().__iterate(s);for(var u=0,_=this._head;_&&!1!==s(_.value,u++,this);)_=_.next;return u},Stack.prototype.__iterator=function(s,i){if(i)return this.reverse().__iterator(s);var u=0,_=this._head;return new Iterator((function(){if(_){var i=_.value;return _=_.next,iteratorValue(s,u++,i)}return iteratorDone()}))},Stack.isStack=isStack;var pt,ht="@@__IMMUTABLE_STACK__@@",dt=Stack.prototype;function makeStack(s,i,u,_){var w=Object.create(dt);return w.size=s,w._head=i,w.__ownerID=u,w.__hash=_,w.__altered=!1,w}function emptyStack(){return pt||(pt=makeStack(0))}function mixin(s,i){var keyCopier=function(u){s.prototype[u]=i[u]};return Object.keys(i).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(i).forEach(keyCopier),s}dt[ht]=!0,dt.withMutations=He.withMutations,dt.asMutable=He.asMutable,dt.asImmutable=He.asImmutable,dt.wasAltered=He.wasAltered,Iterable.Iterator=Iterator,mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var s=new Array(this.size||0);return this.valueSeq().__iterate((function(i,u){s[u]=i})),s},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJS?s.toJS():s})).__toJS()},toJSON:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJSON?s.toJSON():s})).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,!0)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var s={};return this.__iterate((function(i,u){s[u]=i})),s},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(s,i){return 0===this.size?s+i:s+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+i},concat:function(){return reify(this,concatFactory(this,s.call(arguments,0)))},includes:function(s){return this.some((function(i){return is(i,s)}))},entries:function(){return this.__iterator(ee)},every:function(s,i){assertNotInfinite(this.size);var u=!0;return this.__iterate((function(_,w,x){if(!s.call(i,_,w,x))return u=!1,!1})),u},filter:function(s,i){return reify(this,filterFactory(this,s,i,!0))},find:function(s,i,u){var _=this.findEntry(s,i);return _?_[1]:u},forEach:function(s,i){return assertNotInfinite(this.size),this.__iterate(i?s.bind(i):s)},join:function(s){assertNotInfinite(this.size),s=void 0!==s?""+s:",";var i="",u=!0;return this.__iterate((function(_){u?u=!1:i+=s,i+=null!=_?_.toString():""})),i},keys:function(){return this.__iterator(X)},map:function(s,i){return reify(this,mapFactory(this,s,i))},reduce:function(s,i,u){var _,w;return assertNotInfinite(this.size),arguments.length<2?w=!0:_=i,this.__iterate((function(i,x,j){w?(w=!1,_=i):_=s.call(u,_,i,x,j)})),_},reduceRight:function(s,i,u){var _=this.toKeyedSeq().reverse();return _.reduce.apply(_,arguments)},reverse:function(){return reify(this,reverseFactory(this,!0))},slice:function(s,i){return reify(this,sliceFactory(this,s,i,!0))},some:function(s,i){return!this.every(not(s),i)},sort:function(s){return reify(this,sortFactory(this,s))},values:function(){return this.__iterator(Z)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(s,i){return ensureSize(s?this.toSeq().filter(s,i):this)},countBy:function(s,i){return countByFactory(this,s,i)},equals:function(s){return deepEqual(this,s)},entrySeq:function(){var s=this;if(s._cache)return new ArraySeq(s._cache);var i=s.toSeq().map(entryMapper).toIndexedSeq();return i.fromEntrySeq=function(){return s.toSeq()},i},filterNot:function(s,i){return this.filter(not(s),i)},findEntry:function(s,i,u){var _=u;return this.__iterate((function(u,w,x){if(s.call(i,u,w,x))return _=[w,u],!1})),_},findKey:function(s,i){var u=this.findEntry(s,i);return u&&u[0]},findLast:function(s,i,u){return this.toKeyedSeq().reverse().find(s,i,u)},findLastEntry:function(s,i,u){return this.toKeyedSeq().reverse().findEntry(s,i,u)},findLastKey:function(s,i){return this.toKeyedSeq().reverse().findKey(s,i)},first:function(){return this.find(returnTrue)},flatMap:function(s,i){return reify(this,flatMapFactory(this,s,i))},flatten:function(s){return reify(this,flattenFactory(this,s,!0))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(s,i){return this.find((function(i,u){return is(u,s)}),void 0,i)},getIn:function(s,i){for(var u,_=this,w=forceIterator(s);!(u=w.next()).done;){var x=u.value;if((_=_&&_.get?_.get(x,$):$)===$)return i}return _},groupBy:function(s,i){return groupByFactory(this,s,i)},has:function(s){return this.get(s,$)!==$},hasIn:function(s){return this.getIn(s,$)!==$},isSubset:function(s){return s="function"==typeof s.includes?s:Iterable(s),this.every((function(i){return s.includes(i)}))},isSuperset:function(s){return(s="function"==typeof s.isSubset?s:Iterable(s)).isSubset(this)},keyOf:function(s){return this.findKey((function(i){return is(i,s)}))},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(s){return this.toKeyedSeq().reverse().keyOf(s)},max:function(s){return maxFactory(this,s)},maxBy:function(s,i){return maxFactory(this,i,s)},min:function(s){return maxFactory(this,s?neg(s):defaultNegComparator)},minBy:function(s,i){return maxFactory(this,i?neg(i):defaultNegComparator,s)},rest:function(){return this.slice(1)},skip:function(s){return this.slice(Math.max(0,s))},skipLast:function(s){return reify(this,this.toSeq().reverse().skip(s).reverse())},skipWhile:function(s,i){return reify(this,skipWhileFactory(this,s,i,!0))},skipUntil:function(s,i){return this.skipWhile(not(s),i)},sortBy:function(s,i){return reify(this,sortFactory(this,i,s))},take:function(s){return this.slice(0,Math.max(0,s))},takeLast:function(s){return reify(this,this.toSeq().reverse().take(s).reverse())},takeWhile:function(s,i){return reify(this,takeWhileFactory(this,s,i))},takeUntil:function(s,i){return this.takeWhile(not(s),i)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var mt=Iterable.prototype;mt[i]=!0,mt[le]=mt.values,mt.__toJS=mt.toArray,mt.__toStringMapper=quoteString,mt.inspect=mt.toSource=function(){return this.toString()},mt.chain=mt.flatMap,mt.contains=mt.includes,mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(s,i){var u=this,_=0;return reify(this,this.toSeq().map((function(w,x){return s.call(i,[x,w],_++,u)})).fromEntrySeq())},mapKeys:function(s,i){var u=this;return reify(this,this.toSeq().flip().map((function(_,w){return s.call(i,_,w,u)})).flip())}});var gt=KeyedIterable.prototype;function keyMapper(s,i){return i}function entryMapper(s,i){return[i,s]}function not(s){return function(){return!s.apply(this,arguments)}}function neg(s){return function(){return-s.apply(this,arguments)}}function quoteString(s){return"string"==typeof s?JSON.stringify(s):String(s)}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(s,i){return si?-1:0}function hashIterable(s){if(s.size===1/0)return 0;var i=isOrdered(s),u=isKeyed(s),_=i?1:0;return murmurHashOfSize(s.__iterate(u?i?function(s,i){_=31*_+hashMerge(hash(s),hash(i))|0}:function(s,i){_=_+hashMerge(hash(s),hash(i))|0}:i?function(s){_=31*_+hash(s)|0}:function(s){_=_+hash(s)|0}),_)}function murmurHashOfSize(s,i){return i=ye(i,3432918353),i=ye(i<<15|i>>>-15,461845907),i=ye(i<<13|i>>>-13,5),i=ye((i=(i+3864292196|0)^s)^i>>>16,2246822507),i=smi((i=ye(i^i>>>13,3266489909))^i>>>16)}function hashMerge(s,i){return s^i+2654435769+(s<<6)+(s>>2)|0}return gt[u]=!0,gt[le]=mt.entries,gt.__toJS=mt.toObject,gt.__toStringMapper=function(s,i){return JSON.stringify(i)+": "+quoteString(s)},mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,!1)},filter:function(s,i){return reify(this,filterFactory(this,s,i,!1))},findIndex:function(s,i){var u=this.findEntry(s,i);return u?u[0]:-1},indexOf:function(s){var i=this.keyOf(s);return void 0===i?-1:i},lastIndexOf:function(s){var i=this.lastKeyOf(s);return void 0===i?-1:i},reverse:function(){return reify(this,reverseFactory(this,!1))},slice:function(s,i){return reify(this,sliceFactory(this,s,i,!1))},splice:function(s,i){var u=arguments.length;if(i=Math.max(0|i,0),0===u||2===u&&!i)return this;s=resolveBegin(s,s<0?this.count():this.size);var _=this.slice(0,s);return reify(this,1===u?_:_.concat(arrCopy(arguments,2),this.slice(s+i)))},findLastIndex:function(s,i){var u=this.findLastEntry(s,i);return u?u[0]:-1},first:function(){return this.get(0)},flatten:function(s){return reify(this,flattenFactory(this,s,!1))},get:function(s,i){return(s=wrapIndex(this,s))<0||this.size===1/0||void 0!==this.size&&s>this.size?i:this.find((function(i,u){return u===s}),void 0,i)},has:function(s){return(s=wrapIndex(this,s))>=0&&(void 0!==this.size?this.size===1/0||s{"function"==typeof Object.create?s.exports=function inherits(s,i){i&&(s.super_=i,s.prototype=Object.create(i.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}))}:s.exports=function inherits(s,i){if(i){s.super_=i;var TempCtor=function(){};TempCtor.prototype=i.prototype,s.prototype=new TempCtor,s.prototype.constructor=s}}},5419:s=>{s.exports=function(s,i,u,_){var w=new Blob(void 0!==_?[_,s]:[s],{type:u||"application/octet-stream"});if(void 0!==window.navigator.msSaveBlob)window.navigator.msSaveBlob(w,i);else{var x=window.URL&&window.URL.createObjectURL?window.URL.createObjectURL(w):window.webkitURL.createObjectURL(w),j=document.createElement("a");j.style.display="none",j.href=x,j.setAttribute("download",i),void 0===j.download&&j.setAttribute("target","_blank"),document.body.appendChild(j),j.click(),setTimeout((function(){document.body.removeChild(j),window.URL.revokeObjectURL(x)}),200)}}},20181:(s,i,u)=>{var _=NaN,w="[object Symbol]",x=/^\s+|\s+$/g,j=/^[-+]0x[0-9a-f]+$/i,P=/^0b[01]+$/i,B=/^0o[0-7]+$/i,$=parseInt,U="object"==typeof u.g&&u.g&&u.g.Object===Object&&u.g,Y="object"==typeof self&&self&&self.Object===Object&&self,X=U||Y||Function("return this")(),Z=Object.prototype.toString,ee=Math.max,ie=Math.min,now=function(){return X.Date.now()};function isObject(s){var i=typeof s;return!!s&&("object"==i||"function"==i)}function toNumber(s){if("number"==typeof s)return s;if(function isSymbol(s){return"symbol"==typeof s||function isObjectLike(s){return!!s&&"object"==typeof s}(s)&&Z.call(s)==w}(s))return _;if(isObject(s)){var i="function"==typeof s.valueOf?s.valueOf():s;s=isObject(i)?i+"":i}if("string"!=typeof s)return 0===s?s:+s;s=s.replace(x,"");var u=P.test(s);return u||B.test(s)?$(s.slice(2),u?2:8):j.test(s)?_:+s}s.exports=function debounce(s,i,u){var _,w,x,j,P,B,$=0,U=!1,Y=!1,X=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function invokeFunc(i){var u=_,x=w;return _=w=void 0,$=i,j=s.apply(x,u)}function shouldInvoke(s){var u=s-B;return void 0===B||u>=i||u<0||Y&&s-$>=x}function timerExpired(){var s=now();if(shouldInvoke(s))return trailingEdge(s);P=setTimeout(timerExpired,function remainingWait(s){var u=i-(s-B);return Y?ie(u,x-(s-$)):u}(s))}function trailingEdge(s){return P=void 0,X&&_?invokeFunc(s):(_=w=void 0,j)}function debounced(){var s=now(),u=shouldInvoke(s);if(_=arguments,w=this,B=s,u){if(void 0===P)return function leadingEdge(s){return $=s,P=setTimeout(timerExpired,i),U?invokeFunc(s):j}(B);if(Y)return P=setTimeout(timerExpired,i),invokeFunc(B)}return void 0===P&&(P=setTimeout(timerExpired,i)),j}return i=toNumber(i)||0,isObject(u)&&(U=!!u.leading,x=(Y="maxWait"in u)?ee(toNumber(u.maxWait)||0,i):x,X="trailing"in u?!!u.trailing:X),debounced.cancel=function cancel(){void 0!==P&&clearTimeout(P),$=0,_=B=w=P=void 0},debounced.flush=function flush(){return void 0===P?j:trailingEdge(now())},debounced}},55580:(s,i,u)=>{var _=u(56110)(u(9325),"DataView");s.exports=_},21549:(s,i,u)=>{var _=u(22032),w=u(63862),x=u(66721),j=u(12749),P=u(35749);function Hash(s){var i=-1,u=null==s?0:s.length;for(this.clear();++i{var _=u(39344),w=u(94033);function LazyWrapper(s){this.__wrapped__=s,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}LazyWrapper.prototype=_(w.prototype),LazyWrapper.prototype.constructor=LazyWrapper,s.exports=LazyWrapper},80079:(s,i,u)=>{var _=u(63702),w=u(70080),x=u(24739),j=u(48655),P=u(31175);function ListCache(s){var i=-1,u=null==s?0:s.length;for(this.clear();++i{var _=u(39344),w=u(94033);function LodashWrapper(s,i){this.__wrapped__=s,this.__actions__=[],this.__chain__=!!i,this.__index__=0,this.__values__=void 0}LodashWrapper.prototype=_(w.prototype),LodashWrapper.prototype.constructor=LodashWrapper,s.exports=LodashWrapper},68223:(s,i,u)=>{var _=u(56110)(u(9325),"Map");s.exports=_},53661:(s,i,u)=>{var _=u(63040),w=u(17670),x=u(90289),j=u(4509),P=u(72949);function MapCache(s){var i=-1,u=null==s?0:s.length;for(this.clear();++i{var _=u(56110)(u(9325),"Promise");s.exports=_},76545:(s,i,u)=>{var _=u(56110)(u(9325),"Set");s.exports=_},38859:(s,i,u)=>{var _=u(53661),w=u(31380),x=u(51459);function SetCache(s){var i=-1,u=null==s?0:s.length;for(this.__data__=new _;++i{var _=u(80079),w=u(51420),x=u(90938),j=u(63605),P=u(29817),B=u(80945);function Stack(s){var i=this.__data__=new _(s);this.size=i.size}Stack.prototype.clear=w,Stack.prototype.delete=x,Stack.prototype.get=j,Stack.prototype.has=P,Stack.prototype.set=B,s.exports=Stack},51873:(s,i,u)=>{var _=u(9325).Symbol;s.exports=_},37828:(s,i,u)=>{var _=u(9325).Uint8Array;s.exports=_},28303:(s,i,u)=>{var _=u(56110)(u(9325),"WeakMap");s.exports=_},91033:s=>{s.exports=function apply(s,i,u){switch(u.length){case 0:return s.call(i);case 1:return s.call(i,u[0]);case 2:return s.call(i,u[0],u[1]);case 3:return s.call(i,u[0],u[1],u[2])}return s.apply(i,u)}},83729:s=>{s.exports=function arrayEach(s,i){for(var u=-1,_=null==s?0:s.length;++u<_&&!1!==i(s[u],u,s););return s}},79770:s=>{s.exports=function arrayFilter(s,i){for(var u=-1,_=null==s?0:s.length,w=0,x=[];++u<_;){var j=s[u];i(j,u,s)&&(x[w++]=j)}return x}},15325:(s,i,u)=>{var _=u(96131);s.exports=function arrayIncludes(s,i){return!!(null==s?0:s.length)&&_(s,i,0)>-1}},70695:(s,i,u)=>{var _=u(78096),w=u(72428),x=u(56449),j=u(3656),P=u(30361),B=u(37167),$=Object.prototype.hasOwnProperty;s.exports=function arrayLikeKeys(s,i){var u=x(s),U=!u&&w(s),Y=!u&&!U&&j(s),X=!u&&!U&&!Y&&B(s),Z=u||U||Y||X,ee=Z?_(s.length,String):[],ie=ee.length;for(var ae in s)!i&&!$.call(s,ae)||Z&&("length"==ae||Y&&("offset"==ae||"parent"==ae)||X&&("buffer"==ae||"byteLength"==ae||"byteOffset"==ae)||P(ae,ie))||ee.push(ae);return ee}},34932:s=>{s.exports=function arrayMap(s,i){for(var u=-1,_=null==s?0:s.length,w=Array(_);++u<_;)w[u]=i(s[u],u,s);return w}},14528:s=>{s.exports=function arrayPush(s,i){for(var u=-1,_=i.length,w=s.length;++u<_;)s[w+u]=i[u];return s}},40882:s=>{s.exports=function arrayReduce(s,i,u,_){var w=-1,x=null==s?0:s.length;for(_&&x&&(u=s[++w]);++w{s.exports=function arraySome(s,i){for(var u=-1,_=null==s?0:s.length;++u<_;)if(i(s[u],u,s))return!0;return!1}},61074:s=>{s.exports=function asciiToArray(s){return s.split("")}},1733:s=>{var i=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;s.exports=function asciiWords(s){return s.match(i)||[]}},87805:(s,i,u)=>{var _=u(43360),w=u(75288);s.exports=function assignMergeValue(s,i,u){(void 0!==u&&!w(s[i],u)||void 0===u&&!(i in s))&&_(s,i,u)}},16547:(s,i,u)=>{var _=u(43360),w=u(75288),x=Object.prototype.hasOwnProperty;s.exports=function assignValue(s,i,u){var j=s[i];x.call(s,i)&&w(j,u)&&(void 0!==u||i in s)||_(s,i,u)}},26025:(s,i,u)=>{var _=u(75288);s.exports=function assocIndexOf(s,i){for(var u=s.length;u--;)if(_(s[u][0],i))return u;return-1}},74733:(s,i,u)=>{var _=u(21791),w=u(95950);s.exports=function baseAssign(s,i){return s&&_(i,w(i),s)}},43838:(s,i,u)=>{var _=u(21791),w=u(37241);s.exports=function baseAssignIn(s,i){return s&&_(i,w(i),s)}},43360:(s,i,u)=>{var _=u(93243);s.exports=function baseAssignValue(s,i,u){"__proto__"==i&&_?_(s,i,{configurable:!0,enumerable:!0,value:u,writable:!0}):s[i]=u}},9999:(s,i,u)=>{var _=u(37217),w=u(83729),x=u(16547),j=u(74733),P=u(43838),B=u(93290),$=u(23007),U=u(92271),Y=u(48948),X=u(50002),Z=u(83349),ee=u(5861),ie=u(76189),ae=u(77199),le=u(35529),ce=u(56449),pe=u(3656),de=u(87730),fe=u(23805),ye=u(38440),be=u(95950),_e=u(37241),we="[object Arguments]",Se="[object Function]",xe="[object Object]",Pe={};Pe[we]=Pe["[object Array]"]=Pe["[object ArrayBuffer]"]=Pe["[object DataView]"]=Pe["[object Boolean]"]=Pe["[object Date]"]=Pe["[object Float32Array]"]=Pe["[object Float64Array]"]=Pe["[object Int8Array]"]=Pe["[object Int16Array]"]=Pe["[object Int32Array]"]=Pe["[object Map]"]=Pe["[object Number]"]=Pe[xe]=Pe["[object RegExp]"]=Pe["[object Set]"]=Pe["[object String]"]=Pe["[object Symbol]"]=Pe["[object Uint8Array]"]=Pe["[object Uint8ClampedArray]"]=Pe["[object Uint16Array]"]=Pe["[object Uint32Array]"]=!0,Pe["[object Error]"]=Pe[Se]=Pe["[object WeakMap]"]=!1,s.exports=function baseClone(s,i,u,Te,Re,qe){var $e,ze=1&i,We=2&i,He=4&i;if(u&&($e=Re?u(s,Te,Re,qe):u(s)),void 0!==$e)return $e;if(!fe(s))return s;var Ye=ce(s);if(Ye){if($e=ie(s),!ze)return $(s,$e)}else{var Xe=ee(s),Qe=Xe==Se||"[object GeneratorFunction]"==Xe;if(pe(s))return B(s,ze);if(Xe==xe||Xe==we||Qe&&!Re){if($e=We||Qe?{}:le(s),!ze)return We?Y(s,P($e,s)):U(s,j($e,s))}else{if(!Pe[Xe])return Re?s:{};$e=ae(s,Xe,ze)}}qe||(qe=new _);var et=qe.get(s);if(et)return et;qe.set(s,$e),ye(s)?s.forEach((function(_){$e.add(baseClone(_,i,u,_,s,qe))})):de(s)&&s.forEach((function(_,w){$e.set(w,baseClone(_,i,u,w,s,qe))}));var tt=Ye?void 0:(He?We?Z:X:We?_e:be)(s);return w(tt||s,(function(_,w){tt&&(_=s[w=_]),x($e,w,baseClone(_,i,u,w,s,qe))})),$e}},39344:(s,i,u)=>{var _=u(23805),w=Object.create,x=function(){function object(){}return function(s){if(!_(s))return{};if(w)return w(s);object.prototype=s;var i=new object;return object.prototype=void 0,i}}();s.exports=x},80909:(s,i,u)=>{var _=u(30641),w=u(38329)(_);s.exports=w},2523:s=>{s.exports=function baseFindIndex(s,i,u,_){for(var w=s.length,x=u+(_?1:-1);_?x--:++x{var _=u(14528),w=u(45891);s.exports=function baseFlatten(s,i,u,x,j){var P=-1,B=s.length;for(u||(u=w),j||(j=[]);++P0&&u($)?i>1?baseFlatten($,i-1,u,x,j):_(j,$):x||(j[j.length]=$)}return j}},86649:(s,i,u)=>{var _=u(83221)();s.exports=_},30641:(s,i,u)=>{var _=u(86649),w=u(95950);s.exports=function baseForOwn(s,i){return s&&_(s,i,w)}},47422:(s,i,u)=>{var _=u(31769),w=u(77797);s.exports=function baseGet(s,i){for(var u=0,x=(i=_(i,s)).length;null!=s&&u{var _=u(14528),w=u(56449);s.exports=function baseGetAllKeys(s,i,u){var x=i(s);return w(s)?x:_(x,u(s))}},72552:(s,i,u)=>{var _=u(51873),w=u(659),x=u(59350),j=_?_.toStringTag:void 0;s.exports=function baseGetTag(s){return null==s?void 0===s?"[object Undefined]":"[object Null]":j&&j in Object(s)?w(s):x(s)}},28077:s=>{s.exports=function baseHasIn(s,i){return null!=s&&i in Object(s)}},96131:(s,i,u)=>{var _=u(2523),w=u(85463),x=u(76959);s.exports=function baseIndexOf(s,i,u){return i==i?x(s,i,u):_(s,w,u)}},27534:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function baseIsArguments(s){return w(s)&&"[object Arguments]"==_(s)}},60270:(s,i,u)=>{var _=u(87068),w=u(40346);s.exports=function baseIsEqual(s,i,u,x,j){return s===i||(null==s||null==i||!w(s)&&!w(i)?s!=s&&i!=i:_(s,i,u,x,baseIsEqual,j))}},87068:(s,i,u)=>{var _=u(37217),w=u(25911),x=u(21986),j=u(50689),P=u(5861),B=u(56449),$=u(3656),U=u(37167),Y="[object Arguments]",X="[object Array]",Z="[object Object]",ee=Object.prototype.hasOwnProperty;s.exports=function baseIsEqualDeep(s,i,u,ie,ae,le){var ce=B(s),pe=B(i),de=ce?X:P(s),fe=pe?X:P(i),ye=(de=de==Y?Z:de)==Z,be=(fe=fe==Y?Z:fe)==Z,_e=de==fe;if(_e&&$(s)){if(!$(i))return!1;ce=!0,ye=!1}if(_e&&!ye)return le||(le=new _),ce||U(s)?w(s,i,u,ie,ae,le):x(s,i,de,u,ie,ae,le);if(!(1&u)){var we=ye&&ee.call(s,"__wrapped__"),Se=be&&ee.call(i,"__wrapped__");if(we||Se){var xe=we?s.value():s,Pe=Se?i.value():i;return le||(le=new _),ae(xe,Pe,u,ie,le)}}return!!_e&&(le||(le=new _),j(s,i,u,ie,ae,le))}},29172:(s,i,u)=>{var _=u(5861),w=u(40346);s.exports=function baseIsMap(s){return w(s)&&"[object Map]"==_(s)}},41799:(s,i,u)=>{var _=u(37217),w=u(60270);s.exports=function baseIsMatch(s,i,u,x){var j=u.length,P=j,B=!x;if(null==s)return!P;for(s=Object(s);j--;){var $=u[j];if(B&&$[2]?$[1]!==s[$[0]]:!($[0]in s))return!1}for(;++j{s.exports=function baseIsNaN(s){return s!=s}},45083:(s,i,u)=>{var _=u(1882),w=u(87296),x=u(23805),j=u(47473),P=/^\[object .+?Constructor\]$/,B=Function.prototype,$=Object.prototype,U=B.toString,Y=$.hasOwnProperty,X=RegExp("^"+U.call(Y).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");s.exports=function baseIsNative(s){return!(!x(s)||w(s))&&(_(s)?X:P).test(j(s))}},16038:(s,i,u)=>{var _=u(5861),w=u(40346);s.exports=function baseIsSet(s){return w(s)&&"[object Set]"==_(s)}},4901:(s,i,u)=>{var _=u(72552),w=u(30294),x=u(40346),j={};j["[object Float32Array]"]=j["[object Float64Array]"]=j["[object Int8Array]"]=j["[object Int16Array]"]=j["[object Int32Array]"]=j["[object Uint8Array]"]=j["[object Uint8ClampedArray]"]=j["[object Uint16Array]"]=j["[object Uint32Array]"]=!0,j["[object Arguments]"]=j["[object Array]"]=j["[object ArrayBuffer]"]=j["[object Boolean]"]=j["[object DataView]"]=j["[object Date]"]=j["[object Error]"]=j["[object Function]"]=j["[object Map]"]=j["[object Number]"]=j["[object Object]"]=j["[object RegExp]"]=j["[object Set]"]=j["[object String]"]=j["[object WeakMap]"]=!1,s.exports=function baseIsTypedArray(s){return x(s)&&w(s.length)&&!!j[_(s)]}},15389:(s,i,u)=>{var _=u(93663),w=u(87978),x=u(83488),j=u(56449),P=u(50583);s.exports=function baseIteratee(s){return"function"==typeof s?s:null==s?x:"object"==typeof s?j(s)?w(s[0],s[1]):_(s):P(s)}},88984:(s,i,u)=>{var _=u(55527),w=u(3650),x=Object.prototype.hasOwnProperty;s.exports=function baseKeys(s){if(!_(s))return w(s);var i=[];for(var u in Object(s))x.call(s,u)&&"constructor"!=u&&i.push(u);return i}},72903:(s,i,u)=>{var _=u(23805),w=u(55527),x=u(90181),j=Object.prototype.hasOwnProperty;s.exports=function baseKeysIn(s){if(!_(s))return x(s);var i=w(s),u=[];for(var P in s)("constructor"!=P||!i&&j.call(s,P))&&u.push(P);return u}},94033:s=>{s.exports=function baseLodash(){}},93663:(s,i,u)=>{var _=u(41799),w=u(10776),x=u(67197);s.exports=function baseMatches(s){var i=w(s);return 1==i.length&&i[0][2]?x(i[0][0],i[0][1]):function(u){return u===s||_(u,s,i)}}},87978:(s,i,u)=>{var _=u(60270),w=u(58156),x=u(80631),j=u(28586),P=u(30756),B=u(67197),$=u(77797);s.exports=function baseMatchesProperty(s,i){return j(s)&&P(i)?B($(s),i):function(u){var j=w(u,s);return void 0===j&&j===i?x(u,s):_(i,j,3)}}},85250:(s,i,u)=>{var _=u(37217),w=u(87805),x=u(86649),j=u(42824),P=u(23805),B=u(37241),$=u(14974);s.exports=function baseMerge(s,i,u,U,Y){s!==i&&x(i,(function(x,B){if(Y||(Y=new _),P(x))j(s,i,B,u,baseMerge,U,Y);else{var X=U?U($(s,B),x,B+"",s,i,Y):void 0;void 0===X&&(X=x),w(s,B,X)}}),B)}},42824:(s,i,u)=>{var _=u(87805),w=u(93290),x=u(71961),j=u(23007),P=u(35529),B=u(72428),$=u(56449),U=u(83693),Y=u(3656),X=u(1882),Z=u(23805),ee=u(11331),ie=u(37167),ae=u(14974),le=u(69884);s.exports=function baseMergeDeep(s,i,u,ce,pe,de,fe){var ye=ae(s,u),be=ae(i,u),_e=fe.get(be);if(_e)_(s,u,_e);else{var we=de?de(ye,be,u+"",s,i,fe):void 0,Se=void 0===we;if(Se){var xe=$(be),Pe=!xe&&Y(be),Te=!xe&&!Pe&&ie(be);we=be,xe||Pe||Te?$(ye)?we=ye:U(ye)?we=j(ye):Pe?(Se=!1,we=w(be,!0)):Te?(Se=!1,we=x(be,!0)):we=[]:ee(be)||B(be)?(we=ye,B(ye)?we=le(ye):Z(ye)&&!X(ye)||(we=P(be))):Se=!1}Se&&(fe.set(be,we),pe(we,be,ce,de,fe),fe.delete(be)),_(s,u,we)}}},47237:s=>{s.exports=function baseProperty(s){return function(i){return null==i?void 0:i[s]}}},17255:(s,i,u)=>{var _=u(47422);s.exports=function basePropertyDeep(s){return function(i){return _(i,s)}}},54552:s=>{s.exports=function basePropertyOf(s){return function(i){return null==s?void 0:s[i]}}},85558:s=>{s.exports=function baseReduce(s,i,u,_,w){return w(s,(function(s,w,x){u=_?(_=!1,s):i(u,s,w,x)})),u}},69302:(s,i,u)=>{var _=u(83488),w=u(56757),x=u(32865);s.exports=function baseRest(s,i){return x(w(s,i,_),s+"")}},73170:(s,i,u)=>{var _=u(16547),w=u(31769),x=u(30361),j=u(23805),P=u(77797);s.exports=function baseSet(s,i,u,B){if(!j(s))return s;for(var $=-1,U=(i=w(i,s)).length,Y=U-1,X=s;null!=X&&++${var _=u(83488),w=u(48152),x=w?function(s,i){return w.set(s,i),s}:_;s.exports=x},19570:(s,i,u)=>{var _=u(37334),w=u(93243),x=u(83488),j=w?function(s,i){return w(s,"toString",{configurable:!0,enumerable:!1,value:_(i),writable:!0})}:x;s.exports=j},25160:s=>{s.exports=function baseSlice(s,i,u){var _=-1,w=s.length;i<0&&(i=-i>w?0:w+i),(u=u>w?w:u)<0&&(u+=w),w=i>u?0:u-i>>>0,i>>>=0;for(var x=Array(w);++_{var _=u(80909);s.exports=function baseSome(s,i){var u;return _(s,(function(s,_,w){return!(u=i(s,_,w))})),!!u}},78096:s=>{s.exports=function baseTimes(s,i){for(var u=-1,_=Array(s);++u{var _=u(51873),w=u(34932),x=u(56449),j=u(44394),P=_?_.prototype:void 0,B=P?P.toString:void 0;s.exports=function baseToString(s){if("string"==typeof s)return s;if(x(s))return w(s,baseToString)+"";if(j(s))return B?B.call(s):"";var i=s+"";return"0"==i&&1/s==-Infinity?"-0":i}},54128:(s,i,u)=>{var _=u(31800),w=/^\s+/;s.exports=function baseTrim(s){return s?s.slice(0,_(s)+1).replace(w,""):s}},27301:s=>{s.exports=function baseUnary(s){return function(i){return s(i)}}},19931:(s,i,u)=>{var _=u(31769),w=u(68090),x=u(68969),j=u(77797);s.exports=function baseUnset(s,i){return i=_(i,s),null==(s=x(s,i))||delete s[j(w(i))]}},51234:s=>{s.exports=function baseZipObject(s,i,u){for(var _=-1,w=s.length,x=i.length,j={};++_{s.exports=function cacheHas(s,i){return s.has(i)}},31769:(s,i,u)=>{var _=u(56449),w=u(28586),x=u(61802),j=u(13222);s.exports=function castPath(s,i){return _(s)?s:w(s,i)?[s]:x(j(s))}},28754:(s,i,u)=>{var _=u(25160);s.exports=function castSlice(s,i,u){var w=s.length;return u=void 0===u?w:u,!i&&u>=w?s:_(s,i,u)}},49653:(s,i,u)=>{var _=u(37828);s.exports=function cloneArrayBuffer(s){var i=new s.constructor(s.byteLength);return new _(i).set(new _(s)),i}},93290:(s,i,u)=>{s=u.nmd(s);var _=u(9325),w=i&&!i.nodeType&&i,x=w&&s&&!s.nodeType&&s,j=x&&x.exports===w?_.Buffer:void 0,P=j?j.allocUnsafe:void 0;s.exports=function cloneBuffer(s,i){if(i)return s.slice();var u=s.length,_=P?P(u):new s.constructor(u);return s.copy(_),_}},76169:(s,i,u)=>{var _=u(49653);s.exports=function cloneDataView(s,i){var u=i?_(s.buffer):s.buffer;return new s.constructor(u,s.byteOffset,s.byteLength)}},73201:s=>{var i=/\w*$/;s.exports=function cloneRegExp(s){var u=new s.constructor(s.source,i.exec(s));return u.lastIndex=s.lastIndex,u}},93736:(s,i,u)=>{var _=u(51873),w=_?_.prototype:void 0,x=w?w.valueOf:void 0;s.exports=function cloneSymbol(s){return x?Object(x.call(s)):{}}},71961:(s,i,u)=>{var _=u(49653);s.exports=function cloneTypedArray(s,i){var u=i?_(s.buffer):s.buffer;return new s.constructor(u,s.byteOffset,s.length)}},91596:s=>{var i=Math.max;s.exports=function composeArgs(s,u,_,w){for(var x=-1,j=s.length,P=_.length,B=-1,$=u.length,U=i(j-P,0),Y=Array($+U),X=!w;++B<$;)Y[B]=u[B];for(;++x{var i=Math.max;s.exports=function composeArgsRight(s,u,_,w){for(var x=-1,j=s.length,P=-1,B=_.length,$=-1,U=u.length,Y=i(j-B,0),X=Array(Y+U),Z=!w;++x{s.exports=function copyArray(s,i){var u=-1,_=s.length;for(i||(i=Array(_));++u<_;)i[u]=s[u];return i}},21791:(s,i,u)=>{var _=u(16547),w=u(43360);s.exports=function copyObject(s,i,u,x){var j=!u;u||(u={});for(var P=-1,B=i.length;++P{var _=u(21791),w=u(4664);s.exports=function copySymbols(s,i){return _(s,w(s),i)}},48948:(s,i,u)=>{var _=u(21791),w=u(86375);s.exports=function copySymbolsIn(s,i){return _(s,w(s),i)}},55481:(s,i,u)=>{var _=u(9325)["__core-js_shared__"];s.exports=_},58523:s=>{s.exports=function countHolders(s,i){for(var u=s.length,_=0;u--;)s[u]===i&&++_;return _}},20999:(s,i,u)=>{var _=u(69302),w=u(36800);s.exports=function createAssigner(s){return _((function(i,u){var _=-1,x=u.length,j=x>1?u[x-1]:void 0,P=x>2?u[2]:void 0;for(j=s.length>3&&"function"==typeof j?(x--,j):void 0,P&&w(u[0],u[1],P)&&(j=x<3?void 0:j,x=1),i=Object(i);++_{var _=u(64894);s.exports=function createBaseEach(s,i){return function(u,w){if(null==u)return u;if(!_(u))return s(u,w);for(var x=u.length,j=i?x:-1,P=Object(u);(i?j--:++j{s.exports=function createBaseFor(s){return function(i,u,_){for(var w=-1,x=Object(i),j=_(i),P=j.length;P--;){var B=j[s?P:++w];if(!1===u(x[B],B,x))break}return i}}},11842:(s,i,u)=>{var _=u(82819),w=u(9325);s.exports=function createBind(s,i,u){var x=1&i,j=_(s);return function wrapper(){return(this&&this!==w&&this instanceof wrapper?j:s).apply(x?u:this,arguments)}}},12507:(s,i,u)=>{var _=u(28754),w=u(49698),x=u(63912),j=u(13222);s.exports=function createCaseFirst(s){return function(i){i=j(i);var u=w(i)?x(i):void 0,P=u?u[0]:i.charAt(0),B=u?_(u,1).join(""):i.slice(1);return P[s]()+B}}},45539:(s,i,u)=>{var _=u(40882),w=u(50828),x=u(66645),j=RegExp("['’]","g");s.exports=function createCompounder(s){return function(i){return _(x(w(i).replace(j,"")),s,"")}}},82819:(s,i,u)=>{var _=u(39344),w=u(23805);s.exports=function createCtor(s){return function(){var i=arguments;switch(i.length){case 0:return new s;case 1:return new s(i[0]);case 2:return new s(i[0],i[1]);case 3:return new s(i[0],i[1],i[2]);case 4:return new s(i[0],i[1],i[2],i[3]);case 5:return new s(i[0],i[1],i[2],i[3],i[4]);case 6:return new s(i[0],i[1],i[2],i[3],i[4],i[5]);case 7:return new s(i[0],i[1],i[2],i[3],i[4],i[5],i[6])}var u=_(s.prototype),x=s.apply(u,i);return w(x)?x:u}}},77078:(s,i,u)=>{var _=u(91033),w=u(82819),x=u(37471),j=u(18073),P=u(11287),B=u(36306),$=u(9325);s.exports=function createCurry(s,i,u){var U=w(s);return function wrapper(){for(var w=arguments.length,Y=Array(w),X=w,Z=P(wrapper);X--;)Y[X]=arguments[X];var ee=w<3&&Y[0]!==Z&&Y[w-1]!==Z?[]:B(Y,Z);return(w-=ee.length){var _=u(15389),w=u(64894),x=u(95950);s.exports=function createFind(s){return function(i,u,j){var P=Object(i);if(!w(i)){var B=_(u,3);i=x(i),u=function(s){return B(P[s],s,P)}}var $=s(i,u,j);return $>-1?P[B?i[$]:$]:void 0}}},37471:(s,i,u)=>{var _=u(91596),w=u(53320),x=u(58523),j=u(82819),P=u(18073),B=u(11287),$=u(68294),U=u(36306),Y=u(9325);s.exports=function createHybrid(s,i,u,X,Z,ee,ie,ae,le,ce){var pe=128&i,de=1&i,fe=2&i,ye=24&i,be=512&i,_e=fe?void 0:j(s);return function wrapper(){for(var we=arguments.length,Se=Array(we),xe=we;xe--;)Se[xe]=arguments[xe];if(ye)var Pe=B(wrapper),Te=x(Se,Pe);if(X&&(Se=_(Se,X,Z,ye)),ee&&(Se=w(Se,ee,ie,ye)),we-=Te,ye&&we1&&Se.reverse(),pe&&le{var _=u(91033),w=u(82819),x=u(9325);s.exports=function createPartial(s,i,u,j){var P=1&i,B=w(s);return function wrapper(){for(var i=-1,w=arguments.length,$=-1,U=j.length,Y=Array(U+w),X=this&&this!==x&&this instanceof wrapper?B:s;++${var _=u(85087),w=u(54641),x=u(70981);s.exports=function createRecurry(s,i,u,j,P,B,$,U,Y,X){var Z=8&i;i|=Z?32:64,4&(i&=~(Z?64:32))||(i&=-4);var ee=[s,i,P,Z?B:void 0,Z?$:void 0,Z?void 0:B,Z?void 0:$,U,Y,X],ie=u.apply(void 0,ee);return _(s)&&w(ie,ee),ie.placeholder=j,x(ie,s,i)}},66977:(s,i,u)=>{var _=u(68882),w=u(11842),x=u(77078),j=u(37471),P=u(24168),B=u(37381),$=u(3209),U=u(54641),Y=u(70981),X=u(61489),Z=Math.max;s.exports=function createWrap(s,i,u,ee,ie,ae,le,ce){var pe=2&i;if(!pe&&"function"!=typeof s)throw new TypeError("Expected a function");var de=ee?ee.length:0;if(de||(i&=-97,ee=ie=void 0),le=void 0===le?le:Z(X(le),0),ce=void 0===ce?ce:X(ce),de-=ie?ie.length:0,64&i){var fe=ee,ye=ie;ee=ie=void 0}var be=pe?void 0:B(s),_e=[s,i,u,ee,ie,fe,ye,ae,le,ce];if(be&&$(_e,be),s=_e[0],i=_e[1],u=_e[2],ee=_e[3],ie=_e[4],!(ce=_e[9]=void 0===_e[9]?pe?0:s.length:Z(_e[9]-de,0))&&24&i&&(i&=-25),i&&1!=i)we=8==i||16==i?x(s,i,ce):32!=i&&33!=i||ie.length?j.apply(void 0,_e):P(s,i,u,ee);else var we=w(s,i,u);return Y((be?_:U)(we,_e),s,i)}},53138:(s,i,u)=>{var _=u(11331);s.exports=function customOmitClone(s){return _(s)?void 0:s}},24647:(s,i,u)=>{var _=u(54552)({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"});s.exports=_},93243:(s,i,u)=>{var _=u(56110),w=function(){try{var s=_(Object,"defineProperty");return s({},"",{}),s}catch(s){}}();s.exports=w},25911:(s,i,u)=>{var _=u(38859),w=u(14248),x=u(19219);s.exports=function equalArrays(s,i,u,j,P,B){var $=1&u,U=s.length,Y=i.length;if(U!=Y&&!($&&Y>U))return!1;var X=B.get(s),Z=B.get(i);if(X&&Z)return X==i&&Z==s;var ee=-1,ie=!0,ae=2&u?new _:void 0;for(B.set(s,i),B.set(i,s);++ee{var _=u(51873),w=u(37828),x=u(75288),j=u(25911),P=u(20317),B=u(84247),$=_?_.prototype:void 0,U=$?$.valueOf:void 0;s.exports=function equalByTag(s,i,u,_,$,Y,X){switch(u){case"[object DataView]":if(s.byteLength!=i.byteLength||s.byteOffset!=i.byteOffset)return!1;s=s.buffer,i=i.buffer;case"[object ArrayBuffer]":return!(s.byteLength!=i.byteLength||!Y(new w(s),new w(i)));case"[object Boolean]":case"[object Date]":case"[object Number]":return x(+s,+i);case"[object Error]":return s.name==i.name&&s.message==i.message;case"[object RegExp]":case"[object String]":return s==i+"";case"[object Map]":var Z=P;case"[object Set]":var ee=1&_;if(Z||(Z=B),s.size!=i.size&&!ee)return!1;var ie=X.get(s);if(ie)return ie==i;_|=2,X.set(s,i);var ae=j(Z(s),Z(i),_,$,Y,X);return X.delete(s),ae;case"[object Symbol]":if(U)return U.call(s)==U.call(i)}return!1}},50689:(s,i,u)=>{var _=u(50002),w=Object.prototype.hasOwnProperty;s.exports=function equalObjects(s,i,u,x,j,P){var B=1&u,$=_(s),U=$.length;if(U!=_(i).length&&!B)return!1;for(var Y=U;Y--;){var X=$[Y];if(!(B?X in i:w.call(i,X)))return!1}var Z=P.get(s),ee=P.get(i);if(Z&&ee)return Z==i&&ee==s;var ie=!0;P.set(s,i),P.set(i,s);for(var ae=B;++Y{var _=u(35970),w=u(56757),x=u(32865);s.exports=function flatRest(s){return x(w(s,void 0,_),s+"")}},34840:(s,i,u)=>{var _="object"==typeof u.g&&u.g&&u.g.Object===Object&&u.g;s.exports=_},50002:(s,i,u)=>{var _=u(82199),w=u(4664),x=u(95950);s.exports=function getAllKeys(s){return _(s,x,w)}},83349:(s,i,u)=>{var _=u(82199),w=u(86375),x=u(37241);s.exports=function getAllKeysIn(s){return _(s,x,w)}},37381:(s,i,u)=>{var _=u(48152),w=u(63950),x=_?function(s){return _.get(s)}:w;s.exports=x},62284:(s,i,u)=>{var _=u(84629),w=Object.prototype.hasOwnProperty;s.exports=function getFuncName(s){for(var i=s.name+"",u=_[i],x=w.call(_,i)?u.length:0;x--;){var j=u[x],P=j.func;if(null==P||P==s)return j.name}return i}},11287:s=>{s.exports=function getHolder(s){return s.placeholder}},12651:(s,i,u)=>{var _=u(74218);s.exports=function getMapData(s,i){var u=s.__data__;return _(i)?u["string"==typeof i?"string":"hash"]:u.map}},10776:(s,i,u)=>{var _=u(30756),w=u(95950);s.exports=function getMatchData(s){for(var i=w(s),u=i.length;u--;){var x=i[u],j=s[x];i[u]=[x,j,_(j)]}return i}},56110:(s,i,u)=>{var _=u(45083),w=u(10392);s.exports=function getNative(s,i){var u=w(s,i);return _(u)?u:void 0}},28879:(s,i,u)=>{var _=u(74335)(Object.getPrototypeOf,Object);s.exports=_},659:(s,i,u)=>{var _=u(51873),w=Object.prototype,x=w.hasOwnProperty,j=w.toString,P=_?_.toStringTag:void 0;s.exports=function getRawTag(s){var i=x.call(s,P),u=s[P];try{s[P]=void 0;var _=!0}catch(s){}var w=j.call(s);return _&&(i?s[P]=u:delete s[P]),w}},4664:(s,i,u)=>{var _=u(79770),w=u(63345),x=Object.prototype.propertyIsEnumerable,j=Object.getOwnPropertySymbols,P=j?function(s){return null==s?[]:(s=Object(s),_(j(s),(function(i){return x.call(s,i)})))}:w;s.exports=P},86375:(s,i,u)=>{var _=u(14528),w=u(28879),x=u(4664),j=u(63345),P=Object.getOwnPropertySymbols?function(s){for(var i=[];s;)_(i,x(s)),s=w(s);return i}:j;s.exports=P},5861:(s,i,u)=>{var _=u(55580),w=u(68223),x=u(32804),j=u(76545),P=u(28303),B=u(72552),$=u(47473),U="[object Map]",Y="[object Promise]",X="[object Set]",Z="[object WeakMap]",ee="[object DataView]",ie=$(_),ae=$(w),le=$(x),ce=$(j),pe=$(P),de=B;(_&&de(new _(new ArrayBuffer(1)))!=ee||w&&de(new w)!=U||x&&de(x.resolve())!=Y||j&&de(new j)!=X||P&&de(new P)!=Z)&&(de=function(s){var i=B(s),u="[object Object]"==i?s.constructor:void 0,_=u?$(u):"";if(_)switch(_){case ie:return ee;case ae:return U;case le:return Y;case ce:return X;case pe:return Z}return i}),s.exports=de},10392:s=>{s.exports=function getValue(s,i){return null==s?void 0:s[i]}},75251:s=>{var i=/\{\n\/\* \[wrapped with (.+)\] \*/,u=/,? & /;s.exports=function getWrapDetails(s){var _=s.match(i);return _?_[1].split(u):[]}},49326:(s,i,u)=>{var _=u(31769),w=u(72428),x=u(56449),j=u(30361),P=u(30294),B=u(77797);s.exports=function hasPath(s,i,u){for(var $=-1,U=(i=_(i,s)).length,Y=!1;++${var i=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");s.exports=function hasUnicode(s){return i.test(s)}},45434:s=>{var i=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;s.exports=function hasUnicodeWord(s){return i.test(s)}},22032:(s,i,u)=>{var _=u(81042);s.exports=function hashClear(){this.__data__=_?_(null):{},this.size=0}},63862:s=>{s.exports=function hashDelete(s){var i=this.has(s)&&delete this.__data__[s];return this.size-=i?1:0,i}},66721:(s,i,u)=>{var _=u(81042),w=Object.prototype.hasOwnProperty;s.exports=function hashGet(s){var i=this.__data__;if(_){var u=i[s];return"__lodash_hash_undefined__"===u?void 0:u}return w.call(i,s)?i[s]:void 0}},12749:(s,i,u)=>{var _=u(81042),w=Object.prototype.hasOwnProperty;s.exports=function hashHas(s){var i=this.__data__;return _?void 0!==i[s]:w.call(i,s)}},35749:(s,i,u)=>{var _=u(81042);s.exports=function hashSet(s,i){var u=this.__data__;return this.size+=this.has(s)?0:1,u[s]=_&&void 0===i?"__lodash_hash_undefined__":i,this}},76189:s=>{var i=Object.prototype.hasOwnProperty;s.exports=function initCloneArray(s){var u=s.length,_=new s.constructor(u);return u&&"string"==typeof s[0]&&i.call(s,"index")&&(_.index=s.index,_.input=s.input),_}},77199:(s,i,u)=>{var _=u(49653),w=u(76169),x=u(73201),j=u(93736),P=u(71961);s.exports=function initCloneByTag(s,i,u){var B=s.constructor;switch(i){case"[object ArrayBuffer]":return _(s);case"[object Boolean]":case"[object Date]":return new B(+s);case"[object DataView]":return w(s,u);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return P(s,u);case"[object Map]":case"[object Set]":return new B;case"[object Number]":case"[object String]":return new B(s);case"[object RegExp]":return x(s);case"[object Symbol]":return j(s)}}},35529:(s,i,u)=>{var _=u(39344),w=u(28879),x=u(55527);s.exports=function initCloneObject(s){return"function"!=typeof s.constructor||x(s)?{}:_(w(s))}},62060:s=>{var i=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;s.exports=function insertWrapDetails(s,u){var _=u.length;if(!_)return s;var w=_-1;return u[w]=(_>1?"& ":"")+u[w],u=u.join(_>2?", ":" "),s.replace(i,"{\n/* [wrapped with "+u+"] */\n")}},45891:(s,i,u)=>{var _=u(51873),w=u(72428),x=u(56449),j=_?_.isConcatSpreadable:void 0;s.exports=function isFlattenable(s){return x(s)||w(s)||!!(j&&s&&s[j])}},30361:s=>{var i=/^(?:0|[1-9]\d*)$/;s.exports=function isIndex(s,u){var _=typeof s;return!!(u=null==u?9007199254740991:u)&&("number"==_||"symbol"!=_&&i.test(s))&&s>-1&&s%1==0&&s{var _=u(75288),w=u(64894),x=u(30361),j=u(23805);s.exports=function isIterateeCall(s,i,u){if(!j(u))return!1;var P=typeof i;return!!("number"==P?w(u)&&x(i,u.length):"string"==P&&i in u)&&_(u[i],s)}},28586:(s,i,u)=>{var _=u(56449),w=u(44394),x=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,j=/^\w*$/;s.exports=function isKey(s,i){if(_(s))return!1;var u=typeof s;return!("number"!=u&&"symbol"!=u&&"boolean"!=u&&null!=s&&!w(s))||(j.test(s)||!x.test(s)||null!=i&&s in Object(i))}},74218:s=>{s.exports=function isKeyable(s){var i=typeof s;return"string"==i||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==s:null===s}},85087:(s,i,u)=>{var _=u(30980),w=u(37381),x=u(62284),j=u(53758);s.exports=function isLaziable(s){var i=x(s),u=j[i];if("function"!=typeof u||!(i in _.prototype))return!1;if(s===u)return!0;var P=w(u);return!!P&&s===P[0]}},87296:(s,i,u)=>{var _,w=u(55481),x=(_=/[^.]+$/.exec(w&&w.keys&&w.keys.IE_PROTO||""))?"Symbol(src)_1."+_:"";s.exports=function isMasked(s){return!!x&&x in s}},55527:s=>{var i=Object.prototype;s.exports=function isPrototype(s){var u=s&&s.constructor;return s===("function"==typeof u&&u.prototype||i)}},30756:(s,i,u)=>{var _=u(23805);s.exports=function isStrictComparable(s){return s==s&&!_(s)}},63702:s=>{s.exports=function listCacheClear(){this.__data__=[],this.size=0}},70080:(s,i,u)=>{var _=u(26025),w=Array.prototype.splice;s.exports=function listCacheDelete(s){var i=this.__data__,u=_(i,s);return!(u<0)&&(u==i.length-1?i.pop():w.call(i,u,1),--this.size,!0)}},24739:(s,i,u)=>{var _=u(26025);s.exports=function listCacheGet(s){var i=this.__data__,u=_(i,s);return u<0?void 0:i[u][1]}},48655:(s,i,u)=>{var _=u(26025);s.exports=function listCacheHas(s){return _(this.__data__,s)>-1}},31175:(s,i,u)=>{var _=u(26025);s.exports=function listCacheSet(s,i){var u=this.__data__,w=_(u,s);return w<0?(++this.size,u.push([s,i])):u[w][1]=i,this}},63040:(s,i,u)=>{var _=u(21549),w=u(80079),x=u(68223);s.exports=function mapCacheClear(){this.size=0,this.__data__={hash:new _,map:new(x||w),string:new _}}},17670:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheDelete(s){var i=_(this,s).delete(s);return this.size-=i?1:0,i}},90289:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheGet(s){return _(this,s).get(s)}},4509:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheHas(s){return _(this,s).has(s)}},72949:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheSet(s,i){var u=_(this,s),w=u.size;return u.set(s,i),this.size+=u.size==w?0:1,this}},20317:s=>{s.exports=function mapToArray(s){var i=-1,u=Array(s.size);return s.forEach((function(s,_){u[++i]=[_,s]})),u}},67197:s=>{s.exports=function matchesStrictComparable(s,i){return function(u){return null!=u&&(u[s]===i&&(void 0!==i||s in Object(u)))}}},62224:(s,i,u)=>{var _=u(50104);s.exports=function memoizeCapped(s){var i=_(s,(function(s){return 500===u.size&&u.clear(),s})),u=i.cache;return i}},3209:(s,i,u)=>{var _=u(91596),w=u(53320),x=u(36306),j="__lodash_placeholder__",P=128,B=Math.min;s.exports=function mergeData(s,i){var u=s[1],$=i[1],U=u|$,Y=U<131,X=$==P&&8==u||$==P&&256==u&&s[7].length<=i[8]||384==$&&i[7].length<=i[8]&&8==u;if(!Y&&!X)return s;1&$&&(s[2]=i[2],U|=1&u?0:4);var Z=i[3];if(Z){var ee=s[3];s[3]=ee?_(ee,Z,i[4]):Z,s[4]=ee?x(s[3],j):i[4]}return(Z=i[5])&&(ee=s[5],s[5]=ee?w(ee,Z,i[6]):Z,s[6]=ee?x(s[5],j):i[6]),(Z=i[7])&&(s[7]=Z),$&P&&(s[8]=null==s[8]?i[8]:B(s[8],i[8])),null==s[9]&&(s[9]=i[9]),s[0]=i[0],s[1]=U,s}},48152:(s,i,u)=>{var _=u(28303),w=_&&new _;s.exports=w},81042:(s,i,u)=>{var _=u(56110)(Object,"create");s.exports=_},3650:(s,i,u)=>{var _=u(74335)(Object.keys,Object);s.exports=_},90181:s=>{s.exports=function nativeKeysIn(s){var i=[];if(null!=s)for(var u in Object(s))i.push(u);return i}},86009:(s,i,u)=>{s=u.nmd(s);var _=u(34840),w=i&&!i.nodeType&&i,x=w&&s&&!s.nodeType&&s,j=x&&x.exports===w&&_.process,P=function(){try{var s=x&&x.require&&x.require("util").types;return s||j&&j.binding&&j.binding("util")}catch(s){}}();s.exports=P},59350:s=>{var i=Object.prototype.toString;s.exports=function objectToString(s){return i.call(s)}},74335:s=>{s.exports=function overArg(s,i){return function(u){return s(i(u))}}},56757:(s,i,u)=>{var _=u(91033),w=Math.max;s.exports=function overRest(s,i,u){return i=w(void 0===i?s.length-1:i,0),function(){for(var x=arguments,j=-1,P=w(x.length-i,0),B=Array(P);++j{var _=u(47422),w=u(25160);s.exports=function parent(s,i){return i.length<2?s:_(s,w(i,0,-1))}},84629:s=>{s.exports={}},68294:(s,i,u)=>{var _=u(23007),w=u(30361),x=Math.min;s.exports=function reorder(s,i){for(var u=s.length,j=x(i.length,u),P=_(s);j--;){var B=i[j];s[j]=w(B,u)?P[B]:void 0}return s}},36306:s=>{var i="__lodash_placeholder__";s.exports=function replaceHolders(s,u){for(var _=-1,w=s.length,x=0,j=[];++_{var _=u(34840),w="object"==typeof self&&self&&self.Object===Object&&self,x=_||w||Function("return this")();s.exports=x},14974:s=>{s.exports=function safeGet(s,i){if(("constructor"!==i||"function"!=typeof s[i])&&"__proto__"!=i)return s[i]}},31380:s=>{s.exports=function setCacheAdd(s){return this.__data__.set(s,"__lodash_hash_undefined__"),this}},51459:s=>{s.exports=function setCacheHas(s){return this.__data__.has(s)}},54641:(s,i,u)=>{var _=u(68882),w=u(51811)(_);s.exports=w},84247:s=>{s.exports=function setToArray(s){var i=-1,u=Array(s.size);return s.forEach((function(s){u[++i]=s})),u}},32865:(s,i,u)=>{var _=u(19570),w=u(51811)(_);s.exports=w},70981:(s,i,u)=>{var _=u(75251),w=u(62060),x=u(32865),j=u(75948);s.exports=function setWrapToString(s,i,u){var P=i+"";return x(s,w(P,j(_(P),u)))}},51811:s=>{var i=Date.now;s.exports=function shortOut(s){var u=0,_=0;return function(){var w=i(),x=16-(w-_);if(_=w,x>0){if(++u>=800)return arguments[0]}else u=0;return s.apply(void 0,arguments)}}},51420:(s,i,u)=>{var _=u(80079);s.exports=function stackClear(){this.__data__=new _,this.size=0}},90938:s=>{s.exports=function stackDelete(s){var i=this.__data__,u=i.delete(s);return this.size=i.size,u}},63605:s=>{s.exports=function stackGet(s){return this.__data__.get(s)}},29817:s=>{s.exports=function stackHas(s){return this.__data__.has(s)}},80945:(s,i,u)=>{var _=u(80079),w=u(68223),x=u(53661);s.exports=function stackSet(s,i){var u=this.__data__;if(u instanceof _){var j=u.__data__;if(!w||j.length<199)return j.push([s,i]),this.size=++u.size,this;u=this.__data__=new x(j)}return u.set(s,i),this.size=u.size,this}},76959:s=>{s.exports=function strictIndexOf(s,i,u){for(var _=u-1,w=s.length;++_{var _=u(61074),w=u(49698),x=u(42054);s.exports=function stringToArray(s){return w(s)?x(s):_(s)}},61802:(s,i,u)=>{var _=u(62224),w=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,x=/\\(\\)?/g,j=_((function(s){var i=[];return 46===s.charCodeAt(0)&&i.push(""),s.replace(w,(function(s,u,_,w){i.push(_?w.replace(x,"$1"):u||s)})),i}));s.exports=j},77797:(s,i,u)=>{var _=u(44394);s.exports=function toKey(s){if("string"==typeof s||_(s))return s;var i=s+"";return"0"==i&&1/s==-Infinity?"-0":i}},47473:s=>{var i=Function.prototype.toString;s.exports=function toSource(s){if(null!=s){try{return i.call(s)}catch(s){}try{return s+""}catch(s){}}return""}},31800:s=>{var i=/\s/;s.exports=function trimmedEndIndex(s){for(var u=s.length;u--&&i.test(s.charAt(u)););return u}},42054:s=>{var i="\\ud800-\\udfff",u="["+i+"]",_="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",w="\\ud83c[\\udffb-\\udfff]",x="[^"+i+"]",j="(?:\\ud83c[\\udde6-\\uddff]){2}",P="[\\ud800-\\udbff][\\udc00-\\udfff]",B="(?:"+_+"|"+w+")"+"?",$="[\\ufe0e\\ufe0f]?",U=$+B+("(?:\\u200d(?:"+[x,j,P].join("|")+")"+$+B+")*"),Y="(?:"+[x+_+"?",_,j,P,u].join("|")+")",X=RegExp(w+"(?="+w+")|"+Y+U,"g");s.exports=function unicodeToArray(s){return s.match(X)||[]}},22225:s=>{var i="\\ud800-\\udfff",u="\\u2700-\\u27bf",_="a-z\\xdf-\\xf6\\xf8-\\xff",w="A-Z\\xc0-\\xd6\\xd8-\\xde",x="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",j="["+x+"]",P="\\d+",B="["+u+"]",$="["+_+"]",U="[^"+i+x+P+u+_+w+"]",Y="(?:\\ud83c[\\udde6-\\uddff]){2}",X="[\\ud800-\\udbff][\\udc00-\\udfff]",Z="["+w+"]",ee="(?:"+$+"|"+U+")",ie="(?:"+Z+"|"+U+")",ae="(?:['’](?:d|ll|m|re|s|t|ve))?",le="(?:['’](?:D|LL|M|RE|S|T|VE))?",ce="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",pe="[\\ufe0e\\ufe0f]?",de=pe+ce+("(?:\\u200d(?:"+["[^"+i+"]",Y,X].join("|")+")"+pe+ce+")*"),fe="(?:"+[B,Y,X].join("|")+")"+de,ye=RegExp([Z+"?"+$+"+"+ae+"(?="+[j,Z,"$"].join("|")+")",ie+"+"+le+"(?="+[j,Z+ee,"$"].join("|")+")",Z+"?"+ee+"+"+ae,Z+"+"+le,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",P,fe].join("|"),"g");s.exports=function unicodeWords(s){return s.match(ye)||[]}},75948:(s,i,u)=>{var _=u(83729),w=u(15325),x=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]];s.exports=function updateWrapDetails(s,i){return _(x,(function(u){var _="_."+u[0];i&u[1]&&!w(s,_)&&s.push(_)})),s.sort()}},80257:(s,i,u)=>{var _=u(30980),w=u(56017),x=u(23007);s.exports=function wrapperClone(s){if(s instanceof _)return s.clone();var i=new w(s.__wrapped__,s.__chain__);return i.__actions__=x(s.__actions__),i.__index__=s.__index__,i.__values__=s.__values__,i}},64626:(s,i,u)=>{var _=u(66977);s.exports=function ary(s,i,u){return i=u?void 0:i,i=s&&null==i?s.length:i,_(s,128,void 0,void 0,void 0,void 0,i)}},84058:(s,i,u)=>{var _=u(14792),w=u(45539)((function(s,i,u){return i=i.toLowerCase(),s+(u?_(i):i)}));s.exports=w},14792:(s,i,u)=>{var _=u(13222),w=u(55808);s.exports=function capitalize(s){return w(_(s).toLowerCase())}},32629:(s,i,u)=>{var _=u(9999);s.exports=function clone(s){return _(s,4)}},37334:s=>{s.exports=function constant(s){return function(){return s}}},49747:(s,i,u)=>{var _=u(66977);function curry(s,i,u){var w=_(s,8,void 0,void 0,void 0,void 0,void 0,i=u?void 0:i);return w.placeholder=curry.placeholder,w}curry.placeholder={},s.exports=curry},38221:(s,i,u)=>{var _=u(23805),w=u(10124),x=u(99374),j=Math.max,P=Math.min;s.exports=function debounce(s,i,u){var B,$,U,Y,X,Z,ee=0,ie=!1,ae=!1,le=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function invokeFunc(i){var u=B,_=$;return B=$=void 0,ee=i,Y=s.apply(_,u)}function shouldInvoke(s){var u=s-Z;return void 0===Z||u>=i||u<0||ae&&s-ee>=U}function timerExpired(){var s=w();if(shouldInvoke(s))return trailingEdge(s);X=setTimeout(timerExpired,function remainingWait(s){var u=i-(s-Z);return ae?P(u,U-(s-ee)):u}(s))}function trailingEdge(s){return X=void 0,le&&B?invokeFunc(s):(B=$=void 0,Y)}function debounced(){var s=w(),u=shouldInvoke(s);if(B=arguments,$=this,Z=s,u){if(void 0===X)return function leadingEdge(s){return ee=s,X=setTimeout(timerExpired,i),ie?invokeFunc(s):Y}(Z);if(ae)return clearTimeout(X),X=setTimeout(timerExpired,i),invokeFunc(Z)}return void 0===X&&(X=setTimeout(timerExpired,i)),Y}return i=x(i)||0,_(u)&&(ie=!!u.leading,U=(ae="maxWait"in u)?j(x(u.maxWait)||0,i):U,le="trailing"in u?!!u.trailing:le),debounced.cancel=function cancel(){void 0!==X&&clearTimeout(X),ee=0,B=Z=$=X=void 0},debounced.flush=function flush(){return void 0===X?Y:trailingEdge(w())},debounced}},50828:(s,i,u)=>{var _=u(24647),w=u(13222),x=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,j=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");s.exports=function deburr(s){return(s=w(s))&&s.replace(x,_).replace(j,"")}},75288:s=>{s.exports=function eq(s,i){return s===i||s!=s&&i!=i}},60680:(s,i,u)=>{var _=u(13222),w=/[\\^$.*+?()[\]{}|]/g,x=RegExp(w.source);s.exports=function escapeRegExp(s){return(s=_(s))&&x.test(s)?s.replace(w,"\\$&"):s}},7309:(s,i,u)=>{var _=u(62006)(u(24713));s.exports=_},24713:(s,i,u)=>{var _=u(2523),w=u(15389),x=u(61489),j=Math.max;s.exports=function findIndex(s,i,u){var P=null==s?0:s.length;if(!P)return-1;var B=null==u?0:x(u);return B<0&&(B=j(P+B,0)),_(s,w(i,3),B)}},35970:(s,i,u)=>{var _=u(83120);s.exports=function flatten(s){return(null==s?0:s.length)?_(s,1):[]}},73424:(s,i,u)=>{var _=u(16962),w=u(2874),x=Array.prototype.push;function baseAry(s,i){return 2==i?function(i,u){return s(i,u)}:function(i){return s(i)}}function cloneArray(s){for(var i=s?s.length:0,u=Array(i);i--;)u[i]=s[i];return u}function wrapImmutable(s,i){return function(){var u=arguments.length;if(u){for(var _=Array(u);u--;)_[u]=arguments[u];var w=_[0]=i.apply(void 0,_);return s.apply(void 0,_),w}}}s.exports=function baseConvert(s,i,u,j){var P="function"==typeof i,B=i===Object(i);if(B&&(j=u,u=i,i=void 0),null==u)throw new TypeError;j||(j={});var $={cap:!("cap"in j)||j.cap,curry:!("curry"in j)||j.curry,fixed:!("fixed"in j)||j.fixed,immutable:!("immutable"in j)||j.immutable,rearg:!("rearg"in j)||j.rearg},U=P?u:w,Y="curry"in j&&j.curry,X="fixed"in j&&j.fixed,Z="rearg"in j&&j.rearg,ee=P?u.runInContext():void 0,ie=P?u:{ary:s.ary,assign:s.assign,clone:s.clone,curry:s.curry,forEach:s.forEach,isArray:s.isArray,isError:s.isError,isFunction:s.isFunction,isWeakMap:s.isWeakMap,iteratee:s.iteratee,keys:s.keys,rearg:s.rearg,toInteger:s.toInteger,toPath:s.toPath},ae=ie.ary,le=ie.assign,ce=ie.clone,pe=ie.curry,de=ie.forEach,fe=ie.isArray,ye=ie.isError,be=ie.isFunction,_e=ie.isWeakMap,we=ie.keys,Se=ie.rearg,xe=ie.toInteger,Pe=ie.toPath,Te=we(_.aryMethod),Re={castArray:function(s){return function(){var i=arguments[0];return fe(i)?s(cloneArray(i)):s.apply(void 0,arguments)}},iteratee:function(s){return function(){var i=arguments[1],u=s(arguments[0],i),_=u.length;return $.cap&&"number"==typeof i?(i=i>2?i-2:1,_&&_<=i?u:baseAry(u,i)):u}},mixin:function(s){return function(i){var u=this;if(!be(u))return s(u,Object(i));var _=[];return de(we(i),(function(s){be(i[s])&&_.push([s,u.prototype[s]])})),s(u,Object(i)),de(_,(function(s){var i=s[1];be(i)?u.prototype[s[0]]=i:delete u.prototype[s[0]]})),u}},nthArg:function(s){return function(i){var u=i<0?1:xe(i)+1;return pe(s(i),u)}},rearg:function(s){return function(i,u){var _=u?u.length:0;return pe(s(i,u),_)}},runInContext:function(i){return function(u){return baseConvert(s,i(u),j)}}};function castCap(s,i){if($.cap){var u=_.iterateeRearg[s];if(u)return function iterateeRearg(s,i){return overArg(s,(function(s){var u=i.length;return function baseArity(s,i){return 2==i?function(i,u){return s.apply(void 0,arguments)}:function(i){return s.apply(void 0,arguments)}}(Se(baseAry(s,u),i),u)}))}(i,u);var w=!P&&_.iterateeAry[s];if(w)return function iterateeAry(s,i){return overArg(s,(function(s){return"function"==typeof s?baseAry(s,i):s}))}(i,w)}return i}function castFixed(s,i,u){if($.fixed&&(X||!_.skipFixed[s])){var w=_.methodSpread[s],j=w&&w.start;return void 0===j?ae(i,u):function flatSpread(s,i){return function(){for(var u=arguments.length,_=u-1,w=Array(u);u--;)w[u]=arguments[u];var j=w[i],P=w.slice(0,i);return j&&x.apply(P,j),i!=_&&x.apply(P,w.slice(i+1)),s.apply(this,P)}}(i,j)}return i}function castRearg(s,i,u){return $.rearg&&u>1&&(Z||!_.skipRearg[s])?Se(i,_.methodRearg[s]||_.aryRearg[u]):i}function cloneByPath(s,i){for(var u=-1,_=(i=Pe(i)).length,w=_-1,x=ce(Object(s)),j=x;null!=j&&++u<_;){var P=i[u],B=j[P];null==B||be(B)||ye(B)||_e(B)||(j[P]=ce(u==w?B:Object(B))),j=j[P]}return x}function createConverter(s,i){var u=_.aliasToReal[s]||s,w=_.remap[u]||u,x=j;return function(s){var _=P?ee:ie,j=P?ee[w]:i,B=le(le({},x),s);return baseConvert(_,u,j,B)}}function overArg(s,i){return function(){var u=arguments.length;if(!u)return s();for(var _=Array(u);u--;)_[u]=arguments[u];var w=$.rearg?0:u-1;return _[w]=i(_[w]),s.apply(void 0,_)}}function wrap(s,i,u){var w,x=_.aliasToReal[s]||s,j=i,P=Re[x];return P?j=P(i):$.immutable&&(_.mutate.array[x]?j=wrapImmutable(i,cloneArray):_.mutate.object[x]?j=wrapImmutable(i,function createCloner(s){return function(i){return s({},i)}}(i)):_.mutate.set[x]&&(j=wrapImmutable(i,cloneByPath))),de(Te,(function(s){return de(_.aryMethod[s],(function(i){if(x==i){var u=_.methodSpread[x],P=u&&u.afterRearg;return w=P?castFixed(x,castRearg(x,j,s),s):castRearg(x,castFixed(x,j,s),s),w=function castCurry(s,i,u){return Y||$.curry&&u>1?pe(i,u):i}(0,w=castCap(x,w),s),!1}})),!w})),w||(w=j),w==i&&(w=Y?pe(w,1):function(){return i.apply(this,arguments)}),w.convert=createConverter(x,i),w.placeholder=i.placeholder=u,w}if(!B)return wrap(i,u,U);var qe=u,$e=[];return de(Te,(function(s){de(_.aryMethod[s],(function(s){var i=qe[_.remap[s]||s];i&&$e.push([s,wrap(s,i,qe)])}))})),de(we(qe),(function(s){var i=qe[s];if("function"==typeof i){for(var u=$e.length;u--;)if($e[u][0]==s)return;i.convert=createConverter(s,i),$e.push([s,i])}})),de($e,(function(s){qe[s[0]]=s[1]})),qe.convert=function convertLib(s){return qe.runInContext.convert(s)(void 0)},qe.placeholder=qe,de(we(qe),(function(s){de(_.realToAlias[s]||[],(function(i){qe[i]=qe[s]}))})),qe}},16962:(s,i)=>{i.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},i.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},i.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},i.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},i.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},i.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},i.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},i.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},i.realToAlias=function(){var s=Object.prototype.hasOwnProperty,u=i.aliasToReal,_={};for(var w in u){var x=u[w];s.call(_,x)?_[x].push(w):_[x]=[w]}return _}(),i.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},i.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},i.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},47934:(s,i,u)=>{s.exports={ary:u(64626),assign:u(74733),clone:u(32629),curry:u(49747),forEach:u(83729),isArray:u(56449),isError:u(23546),isFunction:u(1882),isWeakMap:u(47886),iteratee:u(33855),keys:u(88984),rearg:u(84195),toInteger:u(61489),toPath:u(42072)}},56367:(s,i,u)=>{s.exports=u(77731)},79920:(s,i,u)=>{var _=u(73424),w=u(47934);s.exports=function convert(s,i,u){return _(w,s,i,u)}},2874:s=>{s.exports={}},77731:(s,i,u)=>{var _=u(79920)("set",u(63560));_.placeholder=u(2874),s.exports=_},58156:(s,i,u)=>{var _=u(47422);s.exports=function get(s,i,u){var w=null==s?void 0:_(s,i);return void 0===w?u:w}},80631:(s,i,u)=>{var _=u(28077),w=u(49326);s.exports=function hasIn(s,i){return null!=s&&w(s,i,_)}},83488:s=>{s.exports=function identity(s){return s}},72428:(s,i,u)=>{var _=u(27534),w=u(40346),x=Object.prototype,j=x.hasOwnProperty,P=x.propertyIsEnumerable,B=_(function(){return arguments}())?_:function(s){return w(s)&&j.call(s,"callee")&&!P.call(s,"callee")};s.exports=B},56449:s=>{var i=Array.isArray;s.exports=i},64894:(s,i,u)=>{var _=u(1882),w=u(30294);s.exports=function isArrayLike(s){return null!=s&&w(s.length)&&!_(s)}},83693:(s,i,u)=>{var _=u(64894),w=u(40346);s.exports=function isArrayLikeObject(s){return w(s)&&_(s)}},53812:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function isBoolean(s){return!0===s||!1===s||w(s)&&"[object Boolean]"==_(s)}},3656:(s,i,u)=>{s=u.nmd(s);var _=u(9325),w=u(89935),x=i&&!i.nodeType&&i,j=x&&s&&!s.nodeType&&s,P=j&&j.exports===x?_.Buffer:void 0,B=(P?P.isBuffer:void 0)||w;s.exports=B},62193:(s,i,u)=>{var _=u(88984),w=u(5861),x=u(72428),j=u(56449),P=u(64894),B=u(3656),$=u(55527),U=u(37167),Y=Object.prototype.hasOwnProperty;s.exports=function isEmpty(s){if(null==s)return!0;if(P(s)&&(j(s)||"string"==typeof s||"function"==typeof s.splice||B(s)||U(s)||x(s)))return!s.length;var i=w(s);if("[object Map]"==i||"[object Set]"==i)return!s.size;if($(s))return!_(s).length;for(var u in s)if(Y.call(s,u))return!1;return!0}},2404:(s,i,u)=>{var _=u(60270);s.exports=function isEqual(s,i){return _(s,i)}},23546:(s,i,u)=>{var _=u(72552),w=u(40346),x=u(11331);s.exports=function isError(s){if(!w(s))return!1;var i=_(s);return"[object Error]"==i||"[object DOMException]"==i||"string"==typeof s.message&&"string"==typeof s.name&&!x(s)}},1882:(s,i,u)=>{var _=u(72552),w=u(23805);s.exports=function isFunction(s){if(!w(s))return!1;var i=_(s);return"[object Function]"==i||"[object GeneratorFunction]"==i||"[object AsyncFunction]"==i||"[object Proxy]"==i}},30294:s=>{s.exports=function isLength(s){return"number"==typeof s&&s>-1&&s%1==0&&s<=9007199254740991}},87730:(s,i,u)=>{var _=u(29172),w=u(27301),x=u(86009),j=x&&x.isMap,P=j?w(j):_;s.exports=P},5187:s=>{s.exports=function isNull(s){return null===s}},98023:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function isNumber(s){return"number"==typeof s||w(s)&&"[object Number]"==_(s)}},23805:s=>{s.exports=function isObject(s){var i=typeof s;return null!=s&&("object"==i||"function"==i)}},40346:s=>{s.exports=function isObjectLike(s){return null!=s&&"object"==typeof s}},11331:(s,i,u)=>{var _=u(72552),w=u(28879),x=u(40346),j=Function.prototype,P=Object.prototype,B=j.toString,$=P.hasOwnProperty,U=B.call(Object);s.exports=function isPlainObject(s){if(!x(s)||"[object Object]"!=_(s))return!1;var i=w(s);if(null===i)return!0;var u=$.call(i,"constructor")&&i.constructor;return"function"==typeof u&&u instanceof u&&B.call(u)==U}},38440:(s,i,u)=>{var _=u(16038),w=u(27301),x=u(86009),j=x&&x.isSet,P=j?w(j):_;s.exports=P},85015:(s,i,u)=>{var _=u(72552),w=u(56449),x=u(40346);s.exports=function isString(s){return"string"==typeof s||!w(s)&&x(s)&&"[object String]"==_(s)}},44394:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function isSymbol(s){return"symbol"==typeof s||w(s)&&"[object Symbol]"==_(s)}},37167:(s,i,u)=>{var _=u(4901),w=u(27301),x=u(86009),j=x&&x.isTypedArray,P=j?w(j):_;s.exports=P},47886:(s,i,u)=>{var _=u(5861),w=u(40346);s.exports=function isWeakMap(s){return w(s)&&"[object WeakMap]"==_(s)}},33855:(s,i,u)=>{var _=u(9999),w=u(15389);s.exports=function iteratee(s){return w("function"==typeof s?s:_(s,1))}},95950:(s,i,u)=>{var _=u(70695),w=u(88984),x=u(64894);s.exports=function keys(s){return x(s)?_(s):w(s)}},37241:(s,i,u)=>{var _=u(70695),w=u(72903),x=u(64894);s.exports=function keysIn(s){return x(s)?_(s,!0):w(s)}},68090:s=>{s.exports=function last(s){var i=null==s?0:s.length;return i?s[i-1]:void 0}},50104:(s,i,u)=>{var _=u(53661);function memoize(s,i){if("function"!=typeof s||null!=i&&"function"!=typeof i)throw new TypeError("Expected a function");var memoized=function(){var u=arguments,_=i?i.apply(this,u):u[0],w=memoized.cache;if(w.has(_))return w.get(_);var x=s.apply(this,u);return memoized.cache=w.set(_,x)||w,x};return memoized.cache=new(memoize.Cache||_),memoized}memoize.Cache=_,s.exports=memoize},55364:(s,i,u)=>{var _=u(85250),w=u(20999)((function(s,i,u){_(s,i,u)}));s.exports=w},6048:s=>{s.exports=function negate(s){if("function"!=typeof s)throw new TypeError("Expected a function");return function(){var i=arguments;switch(i.length){case 0:return!s.call(this);case 1:return!s.call(this,i[0]);case 2:return!s.call(this,i[0],i[1]);case 3:return!s.call(this,i[0],i[1],i[2])}return!s.apply(this,i)}}},63950:s=>{s.exports=function noop(){}},10124:(s,i,u)=>{var _=u(9325);s.exports=function(){return _.Date.now()}},90179:(s,i,u)=>{var _=u(34932),w=u(9999),x=u(19931),j=u(31769),P=u(21791),B=u(53138),$=u(38816),U=u(83349),Y=$((function(s,i){var u={};if(null==s)return u;var $=!1;i=_(i,(function(i){return i=j(i,s),$||($=i.length>1),i})),P(s,U(s),u),$&&(u=w(u,7,B));for(var Y=i.length;Y--;)x(u,i[Y]);return u}));s.exports=Y},50583:(s,i,u)=>{var _=u(47237),w=u(17255),x=u(28586),j=u(77797);s.exports=function property(s){return x(s)?_(j(s)):w(s)}},84195:(s,i,u)=>{var _=u(66977),w=u(38816),x=w((function(s,i){return _(s,256,void 0,void 0,void 0,i)}));s.exports=x},40860:(s,i,u)=>{var _=u(40882),w=u(80909),x=u(15389),j=u(85558),P=u(56449);s.exports=function reduce(s,i,u){var B=P(s)?_:j,$=arguments.length<3;return B(s,x(i,4),u,$,w)}},63560:(s,i,u)=>{var _=u(73170);s.exports=function set(s,i,u){return null==s?s:_(s,i,u)}},42426:(s,i,u)=>{var _=u(14248),w=u(15389),x=u(90916),j=u(56449),P=u(36800);s.exports=function some(s,i,u){var B=j(s)?_:x;return u&&P(s,i,u)&&(i=void 0),B(s,w(i,3))}},63345:s=>{s.exports=function stubArray(){return[]}},89935:s=>{s.exports=function stubFalse(){return!1}},17400:(s,i,u)=>{var _=u(99374),w=1/0;s.exports=function toFinite(s){return s?(s=_(s))===w||s===-1/0?17976931348623157e292*(s<0?-1:1):s==s?s:0:0===s?s:0}},61489:(s,i,u)=>{var _=u(17400);s.exports=function toInteger(s){var i=_(s),u=i%1;return i==i?u?i-u:i:0}},80218:(s,i,u)=>{var _=u(13222);s.exports=function toLower(s){return _(s).toLowerCase()}},99374:(s,i,u)=>{var _=u(54128),w=u(23805),x=u(44394),j=/^[-+]0x[0-9a-f]+$/i,P=/^0b[01]+$/i,B=/^0o[0-7]+$/i,$=parseInt;s.exports=function toNumber(s){if("number"==typeof s)return s;if(x(s))return NaN;if(w(s)){var i="function"==typeof s.valueOf?s.valueOf():s;s=w(i)?i+"":i}if("string"!=typeof s)return 0===s?s:+s;s=_(s);var u=P.test(s);return u||B.test(s)?$(s.slice(2),u?2:8):j.test(s)?NaN:+s}},42072:(s,i,u)=>{var _=u(34932),w=u(23007),x=u(56449),j=u(44394),P=u(61802),B=u(77797),$=u(13222);s.exports=function toPath(s){return x(s)?_(s,B):j(s)?[s]:w(P($(s)))}},69884:(s,i,u)=>{var _=u(21791),w=u(37241);s.exports=function toPlainObject(s){return _(s,w(s))}},13222:(s,i,u)=>{var _=u(77556);s.exports=function toString(s){return null==s?"":_(s)}},55808:(s,i,u)=>{var _=u(12507)("toUpperCase");s.exports=_},66645:(s,i,u)=>{var _=u(1733),w=u(45434),x=u(13222),j=u(22225);s.exports=function words(s,i,u){return s=x(s),void 0===(i=u?void 0:i)?w(s)?j(s):_(s):s.match(i)||[]}},53758:(s,i,u)=>{var _=u(30980),w=u(56017),x=u(94033),j=u(56449),P=u(40346),B=u(80257),$=Object.prototype.hasOwnProperty;function lodash(s){if(P(s)&&!j(s)&&!(s instanceof _)){if(s instanceof w)return s;if($.call(s,"__wrapped__"))return B(s)}return new w(s)}lodash.prototype=x.prototype,lodash.prototype.constructor=lodash,s.exports=lodash},47248:(s,i,u)=>{var _=u(16547),w=u(51234);s.exports=function zipObject(s,i){return w(s||[],i||[],_)}},43768:(s,i,u)=>{"use strict";var _=u(45981),w=u(85587);i.highlight=highlight,i.highlightAuto=function highlightAuto(s,i){var u,j,P,B,$=i||{},U=$.subset||_.listLanguages(),Y=$.prefix,X=U.length,Z=-1;null==Y&&(Y=x);if("string"!=typeof s)throw w("Expected `string` for value, got `%s`",s);j={relevance:0,language:null,value:[]},u={relevance:0,language:null,value:[]};for(;++Zj.relevance&&(j=P),P.relevance>u.relevance&&(j=u,u=P));j.language&&(u.secondBest=j);return u},i.registerLanguage=function registerLanguage(s,i){_.registerLanguage(s,i)},i.listLanguages=function listLanguages(){return _.listLanguages()},i.registerAlias=function registerAlias(s,i){var u,w=s;i&&((w={})[s]=i);for(u in w)_.registerAliases(w[u],{languageName:u})},Emitter.prototype.addText=function text(s){var i,u,_=this.stack;if(""===s)return;i=_[_.length-1],(u=i.children[i.children.length-1])&&"text"===u.type?u.value+=s:i.children.push({type:"text",value:s})},Emitter.prototype.addKeyword=function addKeyword(s,i){this.openNode(i),this.addText(s),this.closeNode()},Emitter.prototype.addSublanguage=function addSublanguage(s,i){var u=this.stack,_=u[u.length-1],w=s.rootNode.children,x=i?{type:"element",tagName:"span",properties:{className:[i]},children:w}:w;_.children=_.children.concat(x)},Emitter.prototype.openNode=function open(s){var i=this.stack,u=this.options.classPrefix+s,_=i[i.length-1],w={type:"element",tagName:"span",properties:{className:[u]},children:[]};_.children.push(w),i.push(w)},Emitter.prototype.closeNode=function close(){this.stack.pop()},Emitter.prototype.closeAllNodes=noop,Emitter.prototype.finalize=noop,Emitter.prototype.toHTML=function toHtmlNoop(){return""};var x="hljs-";function highlight(s,i,u){var j,P=_.configure({}),B=(u||{}).prefix;if("string"!=typeof s)throw w("Expected `string` for name, got `%s`",s);if(!_.getLanguage(s))throw w("Unknown language: `%s` is not registered",s);if("string"!=typeof i)throw w("Expected `string` for value, got `%s`",i);if(null==B&&(B=x),_.configure({__emitter:Emitter,classPrefix:B}),j=_.highlight(i,{language:s,ignoreIllegals:!0}),_.configure(P||{}),j.errorRaised)throw j.errorRaised;return{relevance:j.relevance,language:j.language,value:j.emitter.rootNode.children}}function Emitter(s){this.options=s,this.rootNode={children:[]},this.stack=[this.rootNode]}function noop(){}},92340:(s,i,u)=>{const _=u(6048);function coerceElementMatchingCallback(s){return"string"==typeof s?i=>i.element===s:s.constructor&&s.extend?i=>i instanceof s:s}class ArraySlice{constructor(s){this.elements=s||[]}toValue(){return this.elements.map((s=>s.toValue()))}map(s,i){return this.elements.map(s,i)}flatMap(s,i){return this.map(s,i).reduce(((s,i)=>s.concat(i)),[])}compactMap(s,i){const u=[];return this.forEach((_=>{const w=s.bind(i)(_);w&&u.push(w)})),u}filter(s,i){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(s,i))}reject(s,i){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(_(s),i))}find(s,i){return s=coerceElementMatchingCallback(s),this.elements.find(s,i)}forEach(s,i){this.elements.forEach(s,i)}reduce(s,i){return this.elements.reduce(s,i)}includes(s){return this.elements.some((i=>i.equals(s)))}shift(){return this.elements.shift()}unshift(s){this.elements.unshift(this.refract(s))}push(s){return this.elements.push(this.refract(s)),this}add(s){this.push(s)}get(s){return this.elements[s]}getValue(s){const i=this.elements[s];if(i)return i.toValue()}get length(){return this.elements.length}get isEmpty(){return 0===this.elements.length}get first(){return this.elements[0]}}"undefined"!=typeof Symbol&&(ArraySlice.prototype[Symbol.iterator]=function symbol(){return this.elements[Symbol.iterator]()}),s.exports=ArraySlice},55973:s=>{class KeyValuePair{constructor(s,i){this.key=s,this.value=i}clone(){const s=new KeyValuePair;return this.key&&(s.key=this.key.clone()),this.value&&(s.value=this.value.clone()),s}}s.exports=KeyValuePair},3110:(s,i,u)=>{const _=u(5187),w=u(85015),x=u(98023),j=u(53812),P=u(23805),B=u(85105),$=u(86804);class Namespace{constructor(s){this.elementMap={},this.elementDetection=[],this.Element=$.Element,this.KeyValuePair=$.KeyValuePair,s&&s.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(s){return s.namespace&&s.namespace({base:this}),s.load&&s.load({base:this}),this}useDefault(){return this.register("null",$.NullElement).register("string",$.StringElement).register("number",$.NumberElement).register("boolean",$.BooleanElement).register("array",$.ArrayElement).register("object",$.ObjectElement).register("member",$.MemberElement).register("ref",$.RefElement).register("link",$.LinkElement),this.detect(_,$.NullElement,!1).detect(w,$.StringElement,!1).detect(x,$.NumberElement,!1).detect(j,$.BooleanElement,!1).detect(Array.isArray,$.ArrayElement,!1).detect(P,$.ObjectElement,!1),this}register(s,i){return this._elements=void 0,this.elementMap[s]=i,this}unregister(s){return this._elements=void 0,delete this.elementMap[s],this}detect(s,i,u){return void 0===u||u?this.elementDetection.unshift([s,i]):this.elementDetection.push([s,i]),this}toElement(s){if(s instanceof this.Element)return s;let i;for(let u=0;u{const i=s[0].toUpperCase()+s.substr(1);this._elements[i]=this.elementMap[s]}))),this._elements}get serialiser(){return new B(this)}}B.prototype.Namespace=Namespace,s.exports=Namespace},10866:(s,i,u)=>{const _=u(6048),w=u(92340);class ObjectSlice extends w{map(s,i){return this.elements.map((u=>s.bind(i)(u.value,u.key,u)))}filter(s,i){return new ObjectSlice(this.elements.filter((u=>s.bind(i)(u.value,u.key,u))))}reject(s,i){return this.filter(_(s.bind(i)))}forEach(s,i){return this.elements.forEach(((u,_)=>{s.bind(i)(u.value,u.key,u,_)}))}keys(){return this.map(((s,i)=>i.toValue()))}values(){return this.map((s=>s.toValue()))}}s.exports=ObjectSlice},86804:(s,i,u)=>{const _=u(10316),w=u(41067),x=u(71167),j=u(40239),P=u(12242),B=u(6233),$=u(87726),U=u(61045),Y=u(86303),X=u(14540),Z=u(92340),ee=u(10866),ie=u(55973);function refract(s){if(s instanceof _)return s;if("string"==typeof s)return new x(s);if("number"==typeof s)return new j(s);if("boolean"==typeof s)return new P(s);if(null===s)return new w;if(Array.isArray(s))return new B(s.map(refract));if("object"==typeof s){return new U(s)}return s}_.prototype.ObjectElement=U,_.prototype.RefElement=X,_.prototype.MemberElement=$,_.prototype.refract=refract,Z.prototype.refract=refract,s.exports={Element:_,NullElement:w,StringElement:x,NumberElement:j,BooleanElement:P,ArrayElement:B,MemberElement:$,ObjectElement:U,LinkElement:Y,RefElement:X,refract,ArraySlice:Z,ObjectSlice:ee,KeyValuePair:ie}},86303:(s,i,u)=>{const _=u(10316);s.exports=class LinkElement extends _{constructor(s,i,u){super(s||[],i,u),this.element="link"}get relation(){return this.attributes.get("relation")}set relation(s){this.attributes.set("relation",s)}get href(){return this.attributes.get("href")}set href(s){this.attributes.set("href",s)}}},14540:(s,i,u)=>{const _=u(10316);s.exports=class RefElement extends _{constructor(s,i,u){super(s||[],i,u),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(s){this.attributes.set("path",s)}}},34035:(s,i,u)=>{const _=u(3110),w=u(86804);i.g$=_,i.KeyValuePair=u(55973),i.G6=w.ArraySlice,i.ot=w.ObjectSlice,i.Hg=w.Element,i.Om=w.StringElement,i.kT=w.NumberElement,i.bd=w.BooleanElement,i.Os=w.NullElement,i.wE=w.ArrayElement,i.Sh=w.ObjectElement,i.Pr=w.MemberElement,i.sI=w.RefElement,i.Ft=w.LinkElement,i.e=w.refract,u(85105),u(75147)},6233:(s,i,u)=>{const _=u(6048),w=u(10316),x=u(92340);class ArrayElement extends w{constructor(s,i,u){super(s||[],i,u),this.element="array"}primitive(){return"array"}get(s){return this.content[s]}getValue(s){const i=this.get(s);if(i)return i.toValue()}getIndex(s){return this.content[s]}set(s,i){return this.content[s]=this.refract(i),this}remove(s){const i=this.content.splice(s,1);return i.length?i[0]:null}map(s,i){return this.content.map(s,i)}flatMap(s,i){return this.map(s,i).reduce(((s,i)=>s.concat(i)),[])}compactMap(s,i){const u=[];return this.forEach((_=>{const w=s.bind(i)(_);w&&u.push(w)})),u}filter(s,i){return new x(this.content.filter(s,i))}reject(s,i){return this.filter(_(s),i)}reduce(s,i){let u,_;void 0!==i?(u=0,_=this.refract(i)):(u=1,_="object"===this.primitive()?this.first.value:this.first);for(let i=u;i{s.bind(i)(u,this.refract(_))}))}shift(){return this.content.shift()}unshift(s){this.content.unshift(this.refract(s))}push(s){return this.content.push(this.refract(s)),this}add(s){this.push(s)}findElements(s,i){const u=i||{},_=!!u.recursive,w=void 0===u.results?[]:u.results;return this.forEach(((i,u,x)=>{_&&void 0!==i.findElements&&i.findElements(s,{results:w,recursive:_}),s(i,u,x)&&w.push(i)})),w}find(s){return new x(this.findElements(s,{recursive:!0}))}findByElement(s){return this.find((i=>i.element===s))}findByClass(s){return this.find((i=>i.classes.includes(s)))}getById(s){return this.find((i=>i.id.toValue()===s)).first}includes(s){return this.content.some((i=>i.equals(s)))}contains(s){return this.includes(s)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(s){return new this.constructor(this.content.concat(s.content))}"fantasy-land/concat"(s){return this.concat(s)}"fantasy-land/map"(s){return new this.constructor(this.map(s))}"fantasy-land/chain"(s){return this.map((i=>s(i)),this).reduce(((s,i)=>s.concat(i)),this.empty())}"fantasy-land/filter"(s){return new this.constructor(this.content.filter(s))}"fantasy-land/reduce"(s,i){return this.content.reduce(s,i)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}ArrayElement.empty=function empty(){return new this},ArrayElement["fantasy-land/empty"]=ArrayElement.empty,"undefined"!=typeof Symbol&&(ArrayElement.prototype[Symbol.iterator]=function symbol(){return this.content[Symbol.iterator]()}),s.exports=ArrayElement},12242:(s,i,u)=>{const _=u(10316);s.exports=class BooleanElement extends _{constructor(s,i,u){super(s,i,u),this.element="boolean"}primitive(){return"boolean"}}},10316:(s,i,u)=>{const _=u(2404),w=u(55973),x=u(92340);class Element{constructor(s,i,u){i&&(this.meta=i),u&&(this.attributes=u),this.content=s}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this,this.meta.freeze()),this._attributes&&(this.attributes.parent=this,this.attributes.freeze()),this.children.forEach((s=>{s.parent=this,s.freeze()}),this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const s=new this.constructor;return s.element=this.element,this.meta.length&&(s._meta=this.meta.clone()),this.attributes.length&&(s._attributes=this.attributes.clone()),this.content?this.content.clone?s.content=this.content.clone():Array.isArray(this.content)?s.content=this.content.map((s=>s.clone())):s.content=this.content:s.content=this.content,s}toValue(){return this.content instanceof Element?this.content.toValue():this.content instanceof w?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map((s=>s.toValue()),this):this.content}toRef(s){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const i=new this.RefElement(this.id.toValue());return s&&(i.path=s),i}findRecursive(...s){if(arguments.length>1&&!this.isFrozen)throw new Error("Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`");const i=s.pop();let u=new x;const append=(s,i)=>(s.push(i),s),checkElement=(s,u)=>{u.element===i&&s.push(u);const _=u.findRecursive(i);return _&&_.reduce(append,s),u.content instanceof w&&(u.content.key&&checkElement(s,u.content.key),u.content.value&&checkElement(s,u.content.value)),s};return this.content&&(this.content.element&&checkElement(u,this.content),Array.isArray(this.content)&&this.content.reduce(checkElement,u)),s.isEmpty||(u=u.filter((i=>{let u=i.parents.map((s=>s.element));for(const i in s){const _=s[i],w=u.indexOf(_);if(-1===w)return!1;u=u.splice(0,w)}return!0}))),u}set(s){return this.content=s,this}equals(s){return _(this.toValue(),s)}getMetaProperty(s,i){if(!this.meta.hasKey(s)){if(this.isFrozen){const s=this.refract(i);return s.freeze(),s}this.meta.set(s,i)}return this.meta.get(s)}setMetaProperty(s,i){this.meta.set(s,i)}get element(){return this._storedElement||"element"}set element(s){this._storedElement=s}get content(){return this._content}set content(s){if(s instanceof Element)this._content=s;else if(s instanceof x)this.content=s.elements;else if("string"==typeof s||"number"==typeof s||"boolean"==typeof s||"null"===s||null==s)this._content=s;else if(s instanceof w)this._content=s;else if(Array.isArray(s))this._content=s.map(this.refract);else{if("object"!=typeof s)throw new Error("Cannot set content to given value");this._content=Object.keys(s).map((i=>new this.MemberElement(i,s[i])))}}get meta(){if(!this._meta){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._meta=new this.ObjectElement}return this._meta}set meta(s){s instanceof this.ObjectElement?this._meta=s:this.meta.set(s||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._attributes=new this.ObjectElement}return this._attributes}set attributes(s){s instanceof this.ObjectElement?this._attributes=s:this.attributes.set(s||{})}get id(){return this.getMetaProperty("id","")}set id(s){this.setMetaProperty("id",s)}get classes(){return this.getMetaProperty("classes",[])}set classes(s){this.setMetaProperty("classes",s)}get title(){return this.getMetaProperty("title","")}set title(s){this.setMetaProperty("title",s)}get description(){return this.getMetaProperty("description","")}set description(s){this.setMetaProperty("description",s)}get links(){return this.getMetaProperty("links",[])}set links(s){this.setMetaProperty("links",s)}get isFrozen(){return Object.isFrozen(this)}get parents(){let{parent:s}=this;const i=new x;for(;s;)i.push(s),s=s.parent;return i}get children(){if(Array.isArray(this.content))return new x(this.content);if(this.content instanceof w){const s=new x([this.content.key]);return this.content.value&&s.push(this.content.value),s}return this.content instanceof Element?new x([this.content]):new x}get recursiveChildren(){const s=new x;return this.children.forEach((i=>{s.push(i),i.recursiveChildren.forEach((i=>{s.push(i)}))})),s}}s.exports=Element},87726:(s,i,u)=>{const _=u(55973),w=u(10316);s.exports=class MemberElement extends w{constructor(s,i,u,w){super(new _,u,w),this.element="member",this.key=s,this.value=i}get key(){return this.content.key}set key(s){this.content.key=this.refract(s)}get value(){return this.content.value}set value(s){this.content.value=this.refract(s)}}},41067:(s,i,u)=>{const _=u(10316);s.exports=class NullElement extends _{constructor(s,i,u){super(s||null,i,u),this.element="null"}primitive(){return"null"}set(){return new Error("Cannot set the value of null")}}},40239:(s,i,u)=>{const _=u(10316);s.exports=class NumberElement extends _{constructor(s,i,u){super(s,i,u),this.element="number"}primitive(){return"number"}}},61045:(s,i,u)=>{const _=u(6048),w=u(23805),x=u(6233),j=u(87726),P=u(10866);s.exports=class ObjectElement extends x{constructor(s,i,u){super(s||[],i,u),this.element="object"}primitive(){return"object"}toValue(){return this.content.reduce(((s,i)=>(s[i.key.toValue()]=i.value?i.value.toValue():void 0,s)),{})}get(s){const i=this.getMember(s);if(i)return i.value}getMember(s){if(void 0!==s)return this.content.find((i=>i.key.toValue()===s))}remove(s){let i=null;return this.content=this.content.filter((u=>u.key.toValue()!==s||(i=u,!1))),i}getKey(s){const i=this.getMember(s);if(i)return i.key}set(s,i){if(w(s))return Object.keys(s).forEach((i=>{this.set(i,s[i])})),this;const u=s,_=this.getMember(u);return _?_.value=i:this.content.push(new j(u,i)),this}keys(){return this.content.map((s=>s.key.toValue()))}values(){return this.content.map((s=>s.value.toValue()))}hasKey(s){return this.content.some((i=>i.key.equals(s)))}items(){return this.content.map((s=>[s.key.toValue(),s.value.toValue()]))}map(s,i){return this.content.map((u=>s.bind(i)(u.value,u.key,u)))}compactMap(s,i){const u=[];return this.forEach(((_,w,x)=>{const j=s.bind(i)(_,w,x);j&&u.push(j)})),u}filter(s,i){return new P(this.content).filter(s,i)}reject(s,i){return this.filter(_(s),i)}forEach(s,i){return this.content.forEach((u=>s.bind(i)(u.value,u.key,u)))}}},71167:(s,i,u)=>{const _=u(10316);s.exports=class StringElement extends _{constructor(s,i,u){super(s,i,u),this.element="string"}primitive(){return"string"}get length(){return this.content.length}}},75147:(s,i,u)=>{const _=u(85105);s.exports=class JSON06Serialiser extends _{serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);let i;s._attributes&&s.attributes.get("variable")&&(i=s.attributes.get("variable"));const u={element:s.element};s._meta&&s._meta.length>0&&(u.meta=this.serialiseObject(s.meta));const _="enum"===s.element||-1!==s.attributes.keys().indexOf("enumerations");if(_){const i=this.enumSerialiseAttributes(s);i&&(u.attributes=i)}else if(s._attributes&&s._attributes.length>0){let{attributes:_}=s;_.get("metadata")&&(_=_.clone(),_.set("meta",_.get("metadata")),_.remove("metadata")),"member"===s.element&&i&&(_=_.clone(),_.remove("variable")),_.length>0&&(u.attributes=this.serialiseObject(_))}if(_)u.content=this.enumSerialiseContent(s,u);else if(this[`${s.element}SerialiseContent`])u.content=this[`${s.element}SerialiseContent`](s,u);else if(void 0!==s.content){let _;i&&s.content.key?(_=s.content.clone(),_.key.attributes.set("variable",i),_=this.serialiseContent(_)):_=this.serialiseContent(s.content),this.shouldSerialiseContent(s,_)&&(u.content=_)}else this.shouldSerialiseContent(s,s.content)&&s instanceof this.namespace.elements.Array&&(u.content=[]);return u}shouldSerialiseContent(s,i){return"parseResult"===s.element||"httpRequest"===s.element||"httpResponse"===s.element||"category"===s.element||"link"===s.element||void 0!==i&&(!Array.isArray(i)||0!==i.length)}refSerialiseContent(s,i){return delete i.attributes,{href:s.toValue(),path:s.path.toValue()}}sourceMapSerialiseContent(s){return s.toValue()}dataStructureSerialiseContent(s){return[this.serialiseContent(s.content)]}enumSerialiseAttributes(s){const i=s.attributes.clone(),u=i.remove("enumerations")||new this.namespace.elements.Array([]),_=i.get("default");let w=i.get("samples")||new this.namespace.elements.Array([]);if(_&&_.content&&(_.content.attributes&&_.content.attributes.remove("typeAttributes"),i.set("default",new this.namespace.elements.Array([_.content]))),w.forEach((s=>{s.content&&s.content.element&&s.content.attributes.remove("typeAttributes")})),s.content&&0!==u.length&&w.unshift(s.content),w=w.map((s=>s instanceof this.namespace.elements.Array?[s]:new this.namespace.elements.Array([s.content]))),w.length&&i.set("samples",w),i.length>0)return this.serialiseObject(i)}enumSerialiseContent(s){if(s._attributes){const i=s.attributes.get("enumerations");if(i&&i.length>0)return i.content.map((s=>{const i=s.clone();return i.attributes.remove("typeAttributes"),this.serialise(i)}))}if(s.content){const i=s.content.clone();return i.attributes.remove("typeAttributes"),[this.serialise(i)]}return[]}deserialise(s){if("string"==typeof s)return new this.namespace.elements.String(s);if("number"==typeof s)return new this.namespace.elements.Number(s);if("boolean"==typeof s)return new this.namespace.elements.Boolean(s);if(null===s)return new this.namespace.elements.Null;if(Array.isArray(s))return new this.namespace.elements.Array(s.map(this.deserialise,this));const i=this.namespace.getElementClass(s.element),u=new i;u.element!==s.element&&(u.element=s.element),s.meta&&this.deserialiseObject(s.meta,u.meta),s.attributes&&this.deserialiseObject(s.attributes,u.attributes);const _=this.deserialiseContent(s.content);if(void 0===_&&null!==u.content||(u.content=_),"enum"===u.element){u.content&&u.attributes.set("enumerations",u.content);let s=u.attributes.get("samples");if(u.attributes.remove("samples"),s){const _=s;s=new this.namespace.elements.Array,_.forEach((_=>{_.forEach((_=>{const w=new i(_);w.element=u.element,s.push(w)}))}));const w=s.shift();u.content=w?w.content:void 0,u.attributes.set("samples",s)}else u.content=void 0;let _=u.attributes.get("default");if(_&&_.length>0){_=_.get(0);const s=new i(_);s.element=u.element,u.attributes.set("default",s)}}else if("dataStructure"===u.element&&Array.isArray(u.content))[u.content]=u.content;else if("category"===u.element){const s=u.attributes.get("meta");s&&(u.attributes.set("metadata",s),u.attributes.remove("meta"))}else"member"===u.element&&u.key&&u.key._attributes&&u.key._attributes.getValue("variable")&&(u.attributes.set("variable",u.key.attributes.get("variable")),u.key.attributes.remove("variable"));return u}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const i={key:this.serialise(s.key)};return s.value&&(i.value=this.serialise(s.value)),i}return s&&s.map?s.map(this.serialise,this):s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const i=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(i.value=this.deserialise(s.value)),i}if(s.map)return s.map(this.deserialise,this)}return s}shouldRefract(s){return!!(s._attributes&&s.attributes.keys().length||s._meta&&s.meta.keys().length)||"enum"!==s.element&&(s.element!==s.primitive()||"member"===s.element)}convertKeyToRefract(s,i){return this.shouldRefract(i)?this.serialise(i):"enum"===i.element?this.serialiseEnum(i):"array"===i.element?i.map((i=>this.shouldRefract(i)||"default"===s?this.serialise(i):"array"===i.element||"object"===i.element||"enum"===i.element?i.children.map((s=>this.serialise(s))):i.toValue())):"object"===i.element?(i.content||[]).map(this.serialise,this):i.toValue()}serialiseEnum(s){return s.children.map((s=>this.serialise(s)))}serialiseObject(s){const i={};return s.forEach(((s,u)=>{if(s){const _=u.toValue();i[_]=this.convertKeyToRefract(_,s)}})),i}deserialiseObject(s,i){Object.keys(s).forEach((u=>{i.set(u,this.deserialise(s[u]))}))}}},85105:s=>{s.exports=class JSONSerialiser{constructor(s){this.namespace=s||new this.Namespace}serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);const i={element:s.element};s._meta&&s._meta.length>0&&(i.meta=this.serialiseObject(s.meta)),s._attributes&&s._attributes.length>0&&(i.attributes=this.serialiseObject(s.attributes));const u=this.serialiseContent(s.content);return void 0!==u&&(i.content=u),i}deserialise(s){if(!s.element)throw new Error("Given value is not an object containing an element name");const i=new(this.namespace.getElementClass(s.element));i.element!==s.element&&(i.element=s.element),s.meta&&this.deserialiseObject(s.meta,i.meta),s.attributes&&this.deserialiseObject(s.attributes,i.attributes);const u=this.deserialiseContent(s.content);return void 0===u&&null!==i.content||(i.content=u),i}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const i={key:this.serialise(s.key)};return s.value&&(i.value=this.serialise(s.value)),i}if(s&&s.map){if(0===s.length)return;return s.map(this.serialise,this)}return s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const i=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(i.value=this.deserialise(s.value)),i}if(s.map)return s.map(this.deserialise,this)}return s}serialiseObject(s){const i={};if(s.forEach(((s,u)=>{s&&(i[u.toValue()]=this.serialise(s))})),0!==Object.keys(i).length)return i}deserialiseObject(s,i){Object.keys(s).forEach((u=>{i.set(u,this.deserialise(s[u]))}))}}},58859:(s,i,u)=>{var _="function"==typeof Map&&Map.prototype,w=Object.getOwnPropertyDescriptor&&_?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,x=_&&w&&"function"==typeof w.get?w.get:null,j=_&&Map.prototype.forEach,P="function"==typeof Set&&Set.prototype,B=Object.getOwnPropertyDescriptor&&P?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,$=P&&B&&"function"==typeof B.get?B.get:null,U=P&&Set.prototype.forEach,Y="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,X="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Z="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ee=Boolean.prototype.valueOf,ie=Object.prototype.toString,ae=Function.prototype.toString,le=String.prototype.match,ce=String.prototype.slice,pe=String.prototype.replace,de=String.prototype.toUpperCase,fe=String.prototype.toLowerCase,ye=RegExp.prototype.test,be=Array.prototype.concat,_e=Array.prototype.join,we=Array.prototype.slice,Se=Math.floor,xe="function"==typeof BigInt?BigInt.prototype.valueOf:null,Pe=Object.getOwnPropertySymbols,Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Re="function"==typeof Symbol&&"object"==typeof Symbol.iterator,qe="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Re||"symbol")?Symbol.toStringTag:null,$e=Object.prototype.propertyIsEnumerable,ze=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(s){return s.__proto__}:null);function addNumericSeparator(s,i){if(s===1/0||s===-1/0||s!=s||s&&s>-1e3&&s<1e3||ye.call(/e/,i))return i;var u=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof s){var _=s<0?-Se(-s):Se(s);if(_!==s){var w=String(_),x=ce.call(i,w.length+1);return pe.call(w,u,"$&_")+"."+pe.call(pe.call(x,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pe.call(i,u,"$&_")}var We=u(42634),He=We.custom,Ye=isSymbol(He)?He:null;function wrapQuotes(s,i,u){var _="double"===(u.quoteStyle||i)?'"':"'";return _+s+_}function quote(s){return pe.call(String(s),/"/g,""")}function isArray(s){return!("[object Array]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}function isRegExp(s){return!("[object RegExp]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}function isSymbol(s){if(Re)return s&&"object"==typeof s&&s instanceof Symbol;if("symbol"==typeof s)return!0;if(!s||"object"!=typeof s||!Te)return!1;try{return Te.call(s),!0}catch(s){}return!1}s.exports=function inspect_(s,i,_,w){var P=i||{};if(has(P,"quoteStyle")&&"single"!==P.quoteStyle&&"double"!==P.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(P,"maxStringLength")&&("number"==typeof P.maxStringLength?P.maxStringLength<0&&P.maxStringLength!==1/0:null!==P.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var B=!has(P,"customInspect")||P.customInspect;if("boolean"!=typeof B&&"symbol"!==B)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(P,"indent")&&null!==P.indent&&"\t"!==P.indent&&!(parseInt(P.indent,10)===P.indent&&P.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(P,"numericSeparator")&&"boolean"!=typeof P.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ie=P.numericSeparator;if(void 0===s)return"undefined";if(null===s)return"null";if("boolean"==typeof s)return s?"true":"false";if("string"==typeof s)return inspectString(s,P);if("number"==typeof s){if(0===s)return 1/0/s>0?"0":"-0";var de=String(s);return ie?addNumericSeparator(s,de):de}if("bigint"==typeof s){var ye=String(s)+"n";return ie?addNumericSeparator(s,ye):ye}var Se=void 0===P.depth?5:P.depth;if(void 0===_&&(_=0),_>=Se&&Se>0&&"object"==typeof s)return isArray(s)?"[Array]":"[Object]";var Pe=function getIndent(s,i){var u;if("\t"===s.indent)u="\t";else{if(!("number"==typeof s.indent&&s.indent>0))return null;u=_e.call(Array(s.indent+1)," ")}return{base:u,prev:_e.call(Array(i+1),u)}}(P,_);if(void 0===w)w=[];else if(indexOf(w,s)>=0)return"[Circular]";function inspect(s,i,u){if(i&&(w=we.call(w)).push(i),u){var x={depth:P.depth};return has(P,"quoteStyle")&&(x.quoteStyle=P.quoteStyle),inspect_(s,x,_+1,w)}return inspect_(s,P,_+1,w)}if("function"==typeof s&&!isRegExp(s)){var He=function nameOf(s){if(s.name)return s.name;var i=le.call(ae.call(s),/^function\s*([\w$]+)/);if(i)return i[1];return null}(s),Xe=arrObjKeys(s,inspect);return"[Function"+(He?": "+He:" (anonymous)")+"]"+(Xe.length>0?" { "+_e.call(Xe,", ")+" }":"")}if(isSymbol(s)){var Qe=Re?pe.call(String(s),/^(Symbol\(.*\))_[^)]*$/,"$1"):Te.call(s);return"object"!=typeof s||Re?Qe:markBoxed(Qe)}if(function isElement(s){if(!s||"object"!=typeof s)return!1;if("undefined"!=typeof HTMLElement&&s instanceof HTMLElement)return!0;return"string"==typeof s.nodeName&&"function"==typeof s.getAttribute}(s)){for(var et="<"+fe.call(String(s.nodeName)),tt=s.attributes||[],rt=0;rt"}if(isArray(s)){if(0===s.length)return"[]";var nt=arrObjKeys(s,inspect);return Pe&&!function singleLineValues(s){for(var i=0;i=0)return!1;return!0}(nt)?"["+indentedJoin(nt,Pe)+"]":"[ "+_e.call(nt,", ")+" ]"}if(function isError(s){return!("[object Error]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s)){var ot=arrObjKeys(s,inspect);return"cause"in Error.prototype||!("cause"in s)||$e.call(s,"cause")?0===ot.length?"["+String(s)+"]":"{ ["+String(s)+"] "+_e.call(ot,", ")+" }":"{ ["+String(s)+"] "+_e.call(be.call("[cause]: "+inspect(s.cause),ot),", ")+" }"}if("object"==typeof s&&B){if(Ye&&"function"==typeof s[Ye]&&We)return We(s,{depth:Se-_});if("symbol"!==B&&"function"==typeof s.inspect)return s.inspect()}if(function isMap(s){if(!x||!s||"object"!=typeof s)return!1;try{x.call(s);try{$.call(s)}catch(s){return!0}return s instanceof Map}catch(s){}return!1}(s)){var st=[];return j&&j.call(s,(function(i,u){st.push(inspect(u,s,!0)+" => "+inspect(i,s))})),collectionOf("Map",x.call(s),st,Pe)}if(function isSet(s){if(!$||!s||"object"!=typeof s)return!1;try{$.call(s);try{x.call(s)}catch(s){return!0}return s instanceof Set}catch(s){}return!1}(s)){var it=[];return U&&U.call(s,(function(i){it.push(inspect(i,s))})),collectionOf("Set",$.call(s),it,Pe)}if(function isWeakMap(s){if(!Y||!s||"object"!=typeof s)return!1;try{Y.call(s,Y);try{X.call(s,X)}catch(s){return!0}return s instanceof WeakMap}catch(s){}return!1}(s))return weakCollectionOf("WeakMap");if(function isWeakSet(s){if(!X||!s||"object"!=typeof s)return!1;try{X.call(s,X);try{Y.call(s,Y)}catch(s){return!0}return s instanceof WeakSet}catch(s){}return!1}(s))return weakCollectionOf("WeakSet");if(function isWeakRef(s){if(!Z||!s||"object"!=typeof s)return!1;try{return Z.call(s),!0}catch(s){}return!1}(s))return weakCollectionOf("WeakRef");if(function isNumber(s){return!("[object Number]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s))return markBoxed(inspect(Number(s)));if(function isBigInt(s){if(!s||"object"!=typeof s||!xe)return!1;try{return xe.call(s),!0}catch(s){}return!1}(s))return markBoxed(inspect(xe.call(s)));if(function isBoolean(s){return!("[object Boolean]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s))return markBoxed(ee.call(s));if(function isString(s){return!("[object String]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s))return markBoxed(inspect(String(s)));if("undefined"!=typeof window&&s===window)return"{ [object Window] }";if(s===u.g)return"{ [object globalThis] }";if(!function isDate(s){return!("[object Date]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s)&&!isRegExp(s)){var at=arrObjKeys(s,inspect),lt=ze?ze(s)===Object.prototype:s instanceof Object||s.constructor===Object,ct=s instanceof Object?"":"null prototype",ut=!lt&&qe&&Object(s)===s&&qe in s?ce.call(toStr(s),8,-1):ct?"Object":"",pt=(lt||"function"!=typeof s.constructor?"":s.constructor.name?s.constructor.name+" ":"")+(ut||ct?"["+_e.call(be.call([],ut||[],ct||[]),": ")+"] ":"");return 0===at.length?pt+"{}":Pe?pt+"{"+indentedJoin(at,Pe)+"}":pt+"{ "+_e.call(at,", ")+" }"}return String(s)};var Xe=Object.prototype.hasOwnProperty||function(s){return s in this};function has(s,i){return Xe.call(s,i)}function toStr(s){return ie.call(s)}function indexOf(s,i){if(s.indexOf)return s.indexOf(i);for(var u=0,_=s.length;u<_;u++)if(s[u]===i)return u;return-1}function inspectString(s,i){if(s.length>i.maxStringLength){var u=s.length-i.maxStringLength,_="... "+u+" more character"+(u>1?"s":"");return inspectString(ce.call(s,0,i.maxStringLength),i)+_}return wrapQuotes(pe.call(pe.call(s,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",i)}function lowbyte(s){var i=s.charCodeAt(0),u={8:"b",9:"t",10:"n",12:"f",13:"r"}[i];return u?"\\"+u:"\\x"+(i<16?"0":"")+de.call(i.toString(16))}function markBoxed(s){return"Object("+s+")"}function weakCollectionOf(s){return s+" { ? }"}function collectionOf(s,i,u,_){return s+" ("+i+") {"+(_?indentedJoin(u,_):_e.call(u,", "))+"}"}function indentedJoin(s,i){if(0===s.length)return"";var u="\n"+i.prev+i.base;return u+_e.call(s,","+u)+"\n"+i.prev}function arrObjKeys(s,i){var u=isArray(s),_=[];if(u){_.length=s.length;for(var w=0;w{var i,u,_=s.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(s){if(i===setTimeout)return setTimeout(s,0);if((i===defaultSetTimout||!i)&&setTimeout)return i=setTimeout,setTimeout(s,0);try{return i(s,0)}catch(u){try{return i.call(null,s,0)}catch(u){return i.call(this,s,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(s){i=defaultSetTimout}try{u="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(s){u=defaultClearTimeout}}();var w,x=[],j=!1,P=-1;function cleanUpNextTick(){j&&w&&(j=!1,w.length?x=w.concat(x):P=-1,x.length&&drainQueue())}function drainQueue(){if(!j){var s=runTimeout(cleanUpNextTick);j=!0;for(var i=x.length;i;){for(w=x,x=[];++P1)for(var u=1;u{"use strict";var _=u(6925);function emptyFunction(){}function emptyFunctionWithReset(){}emptyFunctionWithReset.resetWarningCache=emptyFunction,s.exports=function(){function shim(s,i,u,w,x,j){if(j!==_){var P=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw P.name="Invariant Violation",P}}function getShim(){return shim}shim.isRequired=shim;var s={array:shim,bigint:shim,bool:shim,func:shim,number:shim,object:shim,string:shim,symbol:shim,any:shim,arrayOf:getShim,element:shim,elementType:shim,instanceOf:getShim,node:shim,objectOf:getShim,oneOf:getShim,oneOfType:getShim,shape:getShim,exact:getShim,checkPropTypes:emptyFunctionWithReset,resetWarningCache:emptyFunction};return s.PropTypes=s,s}},5556:(s,i,u)=>{s.exports=u(2694)()},6925:s=>{"use strict";s.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},74765:s=>{"use strict";var i=String.prototype.replace,u=/%20/g,_="RFC1738",w="RFC3986";s.exports={default:w,formatters:{RFC1738:function(s){return i.call(s,u,"+")},RFC3986:function(s){return String(s)}},RFC1738:_,RFC3986:w}},55373:(s,i,u)=>{"use strict";var _=u(98636),w=u(62642),x=u(74765);s.exports={formats:x,parse:w,stringify:_}},62642:(s,i,u)=>{"use strict";var _=u(37720),w=Object.prototype.hasOwnProperty,x=Array.isArray,j={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},interpretNumericEntities=function(s){return s.replace(/&#(\d+);/g,(function(s,i){return String.fromCharCode(parseInt(i,10))}))},parseArrayValue=function(s,i){return s&&"string"==typeof s&&i.comma&&s.indexOf(",")>-1?s.split(","):s},P=function parseQueryStringKeys(s,i,u,_){if(s){var x=u.allowDots?s.replace(/\.([^.[]+)/g,"[$1]"):s,j=/(\[[^[\]]*])/g,P=u.depth>0&&/(\[[^[\]]*])/.exec(x),B=P?x.slice(0,P.index):x,$=[];if(B){if(!u.plainObjects&&w.call(Object.prototype,B)&&!u.allowPrototypes)return;$.push(B)}for(var U=0;u.depth>0&&null!==(P=j.exec(x))&&U=0;--x){var j,P=s[x];if("[]"===P&&u.parseArrays)j=[].concat(w);else{j=u.plainObjects?Object.create(null):{};var B="["===P.charAt(0)&&"]"===P.charAt(P.length-1)?P.slice(1,-1):P,$=parseInt(B,10);u.parseArrays||""!==B?!isNaN($)&&P!==B&&String($)===B&&$>=0&&u.parseArrays&&$<=u.arrayLimit?(j=[])[$]=w:"__proto__"!==B&&(j[B]=w):j={0:w}}w=j}return w}($,i,u,_)}};s.exports=function(s,i){var u=function normalizeParseOptions(s){if(!s)return j;if(null!==s.decoder&&void 0!==s.decoder&&"function"!=typeof s.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==s.charset&&"utf-8"!==s.charset&&"iso-8859-1"!==s.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var i=void 0===s.charset?j.charset:s.charset;return{allowDots:void 0===s.allowDots?j.allowDots:!!s.allowDots,allowPrototypes:"boolean"==typeof s.allowPrototypes?s.allowPrototypes:j.allowPrototypes,allowSparse:"boolean"==typeof s.allowSparse?s.allowSparse:j.allowSparse,arrayLimit:"number"==typeof s.arrayLimit?s.arrayLimit:j.arrayLimit,charset:i,charsetSentinel:"boolean"==typeof s.charsetSentinel?s.charsetSentinel:j.charsetSentinel,comma:"boolean"==typeof s.comma?s.comma:j.comma,decoder:"function"==typeof s.decoder?s.decoder:j.decoder,delimiter:"string"==typeof s.delimiter||_.isRegExp(s.delimiter)?s.delimiter:j.delimiter,depth:"number"==typeof s.depth||!1===s.depth?+s.depth:j.depth,ignoreQueryPrefix:!0===s.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof s.interpretNumericEntities?s.interpretNumericEntities:j.interpretNumericEntities,parameterLimit:"number"==typeof s.parameterLimit?s.parameterLimit:j.parameterLimit,parseArrays:!1!==s.parseArrays,plainObjects:"boolean"==typeof s.plainObjects?s.plainObjects:j.plainObjects,strictNullHandling:"boolean"==typeof s.strictNullHandling?s.strictNullHandling:j.strictNullHandling}}(i);if(""===s||null==s)return u.plainObjects?Object.create(null):{};for(var B="string"==typeof s?function parseQueryStringValues(s,i){var u,P={},B=i.ignoreQueryPrefix?s.replace(/^\?/,""):s,$=i.parameterLimit===1/0?void 0:i.parameterLimit,U=B.split(i.delimiter,$),Y=-1,X=i.charset;if(i.charsetSentinel)for(u=0;u-1&&(ee=x(ee)?[ee]:ee),w.call(P,Z)?P[Z]=_.combine(P[Z],ee):P[Z]=ee}return P}(s,u):s,$=u.plainObjects?Object.create(null):{},U=Object.keys(B),Y=0;Y{"use strict";var _=u(920),w=u(37720),x=u(74765),j=Object.prototype.hasOwnProperty,P={brackets:function brackets(s){return s+"[]"},comma:"comma",indices:function indices(s,i){return s+"["+i+"]"},repeat:function repeat(s){return s}},B=Array.isArray,$=String.prototype.split,U=Array.prototype.push,pushToArray=function(s,i){U.apply(s,B(i)?i:[i])},Y=Date.prototype.toISOString,X=x.default,Z={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:w.encode,encodeValuesOnly:!1,format:X,formatter:x.formatters[X],indices:!1,serializeDate:function serializeDate(s){return Y.call(s)},skipNulls:!1,strictNullHandling:!1},ee={},ie=function stringify(s,i,u,x,j,P,U,Y,X,ie,ae,le,ce,pe,de,fe){for(var ye=s,be=fe,_e=0,we=!1;void 0!==(be=be.get(ee))&&!we;){var Se=be.get(s);if(_e+=1,void 0!==Se){if(Se===_e)throw new RangeError("Cyclic object value");we=!0}void 0===be.get(ee)&&(_e=0)}if("function"==typeof Y?ye=Y(i,ye):ye instanceof Date?ye=ae(ye):"comma"===u&&B(ye)&&(ye=w.maybeMap(ye,(function(s){return s instanceof Date?ae(s):s}))),null===ye){if(j)return U&&!pe?U(i,Z.encoder,de,"key",le):i;ye=""}if(function isNonNullishPrimitive(s){return"string"==typeof s||"number"==typeof s||"boolean"==typeof s||"symbol"==typeof s||"bigint"==typeof s}(ye)||w.isBuffer(ye)){if(U){var xe=pe?i:U(i,Z.encoder,de,"key",le);if("comma"===u&&pe){for(var Pe=$.call(String(ye),","),Te="",Re=0;Re0?ye.join(",")||null:void 0}];else if(B(Y))qe=Y;else{var ze=Object.keys(ye);qe=X?ze.sort(X):ze}for(var We=x&&B(ye)&&1===ye.length?i+"[]":i,He=0;He0?de+pe:""}},37720:(s,i,u)=>{"use strict";var _=u(74765),w=Object.prototype.hasOwnProperty,x=Array.isArray,j=function(){for(var s=[],i=0;i<256;++i)s.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase());return s}(),P=function arrayToObject(s,i){for(var u=i&&i.plainObjects?Object.create(null):{},_=0;_1;){var i=s.pop(),u=i.obj[i.prop];if(x(u)){for(var _=[],w=0;w=48&&U<=57||U>=65&&U<=90||U>=97&&U<=122||x===_.RFC1738&&(40===U||41===U)?B+=P.charAt($):U<128?B+=j[U]:U<2048?B+=j[192|U>>6]+j[128|63&U]:U<55296||U>=57344?B+=j[224|U>>12]+j[128|U>>6&63]+j[128|63&U]:($+=1,U=65536+((1023&U)<<10|1023&P.charCodeAt($)),B+=j[240|U>>18]+j[128|U>>12&63]+j[128|U>>6&63]+j[128|63&U])}return B},isBuffer:function isBuffer(s){return!(!s||"object"!=typeof s)&&!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))},isRegExp:function isRegExp(s){return"[object RegExp]"===Object.prototype.toString.call(s)},maybeMap:function maybeMap(s,i){if(x(s)){for(var u=[],_=0;_{"use strict";var u=Object.prototype.hasOwnProperty;function decode(s){try{return decodeURIComponent(s.replace(/\+/g," "))}catch(s){return null}}function encode(s){try{return encodeURIComponent(s)}catch(s){return null}}i.stringify=function querystringify(s,i){i=i||"";var _,w,x=[];for(w in"string"!=typeof i&&(i="?"),s)if(u.call(s,w)){if((_=s[w])||null!=_&&!isNaN(_)||(_=""),w=encode(w),_=encode(_),null===w||null===_)continue;x.push(w+"="+_)}return x.length?i+x.join("&"):""},i.parse=function querystring(s){for(var i,u=/([^=?#&]+)=?([^&]*)/g,_={};i=u.exec(s);){var w=decode(i[1]),x=decode(i[2]);null===w||null===x||w in _||(_[w]=x)}return _}},41859:(s,i,u)=>{const _=u(27096),w=u(78004),x=_.types;s.exports=class RandExp{constructor(s,i){if(this._setDefaults(s),s instanceof RegExp)this.ignoreCase=s.ignoreCase,this.multiline=s.multiline,s=s.source;else{if("string"!=typeof s)throw new Error("Expected a regexp or string");this.ignoreCase=i&&-1!==i.indexOf("i"),this.multiline=i&&-1!==i.indexOf("m")}this.tokens=_(s)}_setDefaults(s){this.max=null!=s.max?s.max:null!=RandExp.prototype.max?RandExp.prototype.max:100,this.defaultRange=s.defaultRange?s.defaultRange:this.defaultRange.clone(),s.randInt&&(this.randInt=s.randInt)}gen(){return this._gen(this.tokens,[])}_gen(s,i){var u,_,w,j,P;switch(s.type){case x.ROOT:case x.GROUP:if(s.followedBy||s.notFollowedBy)return"";for(s.remember&&void 0===s.groupNumber&&(s.groupNumber=i.push(null)-1),_="",j=0,P=(u=s.options?this._randSelect(s.options):s.stack).length;j{"use strict";var _=u(65606),w=65536,x=4294967295;var j=u(92861).Buffer,P=u.g.crypto||u.g.msCrypto;P&&P.getRandomValues?s.exports=function randomBytes(s,i){if(s>x)throw new RangeError("requested too many random bytes");var u=j.allocUnsafe(s);if(s>0)if(s>w)for(var B=0;B{"use strict";function _typeof(s){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(s){return typeof s}:function(s){return s&&"function"==typeof Symbol&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},_typeof(s)}Object.defineProperty(i,"__esModule",{value:!0}),i.CopyToClipboard=void 0;var _=_interopRequireDefault(u(96540)),w=_interopRequireDefault(u(17965)),x=["text","onCopy","options","children"];function _interopRequireDefault(s){return s&&s.__esModule?s:{default:s}}function ownKeys(s,i){var u=Object.keys(s);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);i&&(_=_.filter((function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable}))),u.push.apply(u,_)}return u}function _objectSpread(s){for(var i=1;i=0||(w[u]=s[u]);return w}(s,i);if(Object.getOwnPropertySymbols){var x=Object.getOwnPropertySymbols(s);for(_=0;_=0||Object.prototype.propertyIsEnumerable.call(s,u)&&(w[u]=s[u])}return w}function _defineProperties(s,i){for(var u=0;u{"use strict";var _=u(25264).CopyToClipboard;_.CopyToClipboard=_,s.exports=_},81214:(s,i,u)=>{"use strict";function _typeof(s){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(s){return typeof s}:function(s){return s&&"function"==typeof Symbol&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},_typeof(s)}Object.defineProperty(i,"__esModule",{value:!0}),i.DebounceInput=void 0;var _=_interopRequireDefault(u(96540)),w=_interopRequireDefault(u(20181)),x=["element","onChange","value","minLength","debounceTimeout","forceNotifyByEnter","forceNotifyOnBlur","onKeyDown","onBlur","inputRef"];function _interopRequireDefault(s){return s&&s.__esModule?s:{default:s}}function _objectWithoutProperties(s,i){if(null==s)return{};var u,_,w=function _objectWithoutPropertiesLoose(s,i){if(null==s)return{};var u,_,w={},x=Object.keys(s);for(_=0;_=0||(w[u]=s[u]);return w}(s,i);if(Object.getOwnPropertySymbols){var x=Object.getOwnPropertySymbols(s);for(_=0;_=0||Object.prototype.propertyIsEnumerable.call(s,u)&&(w[u]=s[u])}return w}function ownKeys(s,i){var u=Object.keys(s);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);i&&(_=_.filter((function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable}))),u.push.apply(u,_)}return u}function _objectSpread(s){for(var i=1;i=_?u.notify(s):i.length>w.length&&u.notify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:""})}))}))})),_defineProperty(_assertThisInitialized(u),"onKeyDown",(function(s){"Enter"===s.key&&u.forceNotify(s);var i=u.props.onKeyDown;i&&(s.persist(),i(s))})),_defineProperty(_assertThisInitialized(u),"onBlur",(function(s){u.forceNotify(s);var i=u.props.onBlur;i&&(s.persist(),i(s))})),_defineProperty(_assertThisInitialized(u),"createNotifier",(function(s){if(s<0)u.notify=function(){return null};else if(0===s)u.notify=u.doNotify;else{var i=(0,w.default)((function(s){u.isDebouncing=!1,u.doNotify(s)}),s);u.notify=function(s){u.isDebouncing=!0,i(s)},u.flush=function(){return i.flush()},u.cancel=function(){u.isDebouncing=!1,i.cancel()}}})),_defineProperty(_assertThisInitialized(u),"doNotify",(function(){u.props.onChange.apply(void 0,arguments)})),_defineProperty(_assertThisInitialized(u),"forceNotify",(function(s){var i=u.props.debounceTimeout;if(u.isDebouncing||!(i>0)){u.cancel&&u.cancel();var _=u.state.value,w=u.props.minLength;_.length>=w?u.doNotify(s):u.doNotify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:_})}))}})),u.isDebouncing=!1,u.state={value:void 0===s.value||null===s.value?"":s.value};var _=u.props.debounceTimeout;return u.createNotifier(_),u}return function _createClass(s,i,u){return i&&_defineProperties(s.prototype,i),u&&_defineProperties(s,u),Object.defineProperty(s,"prototype",{writable:!1}),s}(DebounceInput,[{key:"componentDidUpdate",value:function componentDidUpdate(s){if(!this.isDebouncing){var i=this.props,u=i.value,_=i.debounceTimeout,w=s.debounceTimeout,x=s.value,j=this.state.value;void 0!==u&&x!==u&&j!==u&&this.setState({value:u}),_!==w&&this.createNotifier(_)}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.flush&&this.flush()}},{key:"render",value:function render(){var s,i,u=this.props,w=u.element,j=(u.onChange,u.value,u.minLength,u.debounceTimeout,u.forceNotifyByEnter),P=u.forceNotifyOnBlur,B=u.onKeyDown,$=u.onBlur,U=u.inputRef,Y=_objectWithoutProperties(u,x),X=this.state.value;s=j?{onKeyDown:this.onKeyDown}:B?{onKeyDown:B}:{},i=P?{onBlur:this.onBlur}:$?{onBlur:$}:{};var Z=U?{ref:U}:{};return _.default.createElement(w,_objectSpread(_objectSpread(_objectSpread(_objectSpread({},Y),{},{onChange:this.onChange,value:X},s),i),Z))}}]),DebounceInput}(_.default.PureComponent);i.DebounceInput=j,_defineProperty(j,"defaultProps",{element:"input",type:"text",onKeyDown:void 0,onBlur:void 0,value:void 0,minLength:0,debounceTimeout:100,forceNotifyByEnter:!0,forceNotifyOnBlur:!0,inputRef:void 0})},24677:(s,i,u)=>{"use strict";var _=u(81214).DebounceInput;_.DebounceInput=_,s.exports=_},22551:(s,i,u)=>{"use strict";var _=u(96540),w=u(69982);function p(s){for(var i="https://reactjs.org/docs/error-decoder.html?invariant="+s,u=1;u
")}value(){return this.buffer}span(s){this.buffer+=``}}class TokenTree{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(s){this.top.children.push(s)}openNode(s){const i={kind:s,children:[]};this.add(i),this.stack.push(i)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(s){return this.constructor._walk(s,this.rootNode)}static _walk(s,i){return"string"==typeof i?s.addText(i):i.children&&(s.openNode(i),i.children.forEach((i=>this._walk(s,i))),s.closeNode(i)),s}static _collapse(s){"string"!=typeof s&&s.children&&(s.children.every((s=>"string"==typeof s))?s.children=[s.children.join("")]:s.children.forEach((s=>{TokenTree._collapse(s)})))}}class TokenTreeEmitter extends TokenTree{constructor(s){super(),this.options=s}addKeyword(s,i){""!==s&&(this.openNode(i),this.addText(s),this.closeNode())}addText(s){""!==s&&this.add(s)}addSublanguage(s,i){const u=s.root;u.kind=i,u.sublanguage=!0,this.add(u)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return!0}}function source(s){return s?"string"==typeof s?s:s.source:null}const _=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;const w="[a-zA-Z]\\w*",x="[a-zA-Z_]\\w*",j="\\b\\d+(\\.\\d+)?",P="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",B="\\b(0b[01]+)",$={begin:"\\\\[\\s\\S]",relevance:0},U={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[$]},Y={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[$]},X={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},COMMENT=function(s,i,u={}){const _=inherit({className:"comment",begin:s,end:i,contains:[]},u);return _.contains.push(X),_.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),_},Z=COMMENT("//","$"),ee=COMMENT("/\\*","\\*/"),ie=COMMENT("#","$"),ae={className:"number",begin:j,relevance:0},le={className:"number",begin:P,relevance:0},ce={className:"number",begin:B,relevance:0},pe={className:"number",begin:j+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},de={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[$,{begin:/\[/,end:/\]/,relevance:0,contains:[$]}]}]},fe={className:"title",begin:w,relevance:0},ye={className:"title",begin:x,relevance:0},be={begin:"\\.\\s*"+x,relevance:0};var _e=Object.freeze({__proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:w,UNDERSCORE_IDENT_RE:x,NUMBER_RE:j,C_NUMBER_RE:P,BINARY_NUMBER_RE:B,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(s={})=>{const i=/^#![ ]*\//;return s.binary&&(s.begin=function concat(...s){return s.map((s=>source(s))).join("")}(i,/.*\b/,s.binary,/\b.*/)),inherit({className:"meta",begin:i,end:/$/,relevance:0,"on:begin":(s,i)=>{0!==s.index&&i.ignoreMatch()}},s)},BACKSLASH_ESCAPE:$,APOS_STRING_MODE:U,QUOTE_STRING_MODE:Y,PHRASAL_WORDS_MODE:X,COMMENT,C_LINE_COMMENT_MODE:Z,C_BLOCK_COMMENT_MODE:ee,HASH_COMMENT_MODE:ie,NUMBER_MODE:ae,C_NUMBER_MODE:le,BINARY_NUMBER_MODE:ce,CSS_NUMBER_MODE:pe,REGEXP_MODE:de,TITLE_MODE:fe,UNDERSCORE_TITLE_MODE:ye,METHOD_GUARD:be,END_SAME_AS_BEGIN:function(s){return Object.assign(s,{"on:begin":(s,i)=>{i.data._beginMatch=s[1]},"on:end":(s,i)=>{i.data._beginMatch!==s[1]&&i.ignoreMatch()}})}});function skipIfhasPrecedingDot(s,i){"."===s.input[s.index-1]&&i.ignoreMatch()}function beginKeywords(s,i){i&&s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",s.__beforeBegin=skipIfhasPrecedingDot,s.keywords=s.keywords||s.beginKeywords,delete s.beginKeywords,void 0===s.relevance&&(s.relevance=0))}function compileIllegal(s,i){Array.isArray(s.illegal)&&(s.illegal=function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}(...s.illegal))}function compileMatch(s,i){if(s.match){if(s.begin||s.end)throw new Error("begin & end are not supported with match");s.begin=s.match,delete s.match}}function compileRelevance(s,i){void 0===s.relevance&&(s.relevance=1)}const we=["of","and","for","in","not","or","if","then","parent","list","value"],Se="keyword";function compileKeywords(s,i,u=Se){const _={};return"string"==typeof s?compileList(u,s.split(" ")):Array.isArray(s)?compileList(u,s):Object.keys(s).forEach((function(u){Object.assign(_,compileKeywords(s[u],i,u))})),_;function compileList(s,u){i&&(u=u.map((s=>s.toLowerCase()))),u.forEach((function(i){const u=i.split("|");_[u[0]]=[s,scoreForKeyword(u[0],u[1])]}))}}function scoreForKeyword(s,i){return i?Number(i):function commonKeyword(s){return we.includes(s.toLowerCase())}(s)?0:1}function compileLanguage(s,{plugins:i}){function langRe(i,u){return new RegExp(source(i),"m"+(s.case_insensitive?"i":"")+(u?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(s,i){i.position=this.position++,this.matchIndexes[this.matchAt]=i,this.regexes.push([i,s]),this.matchAt+=function countMatchGroups(s){return new RegExp(s.toString()+"|").exec("").length-1}(s)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const s=this.regexes.map((s=>s[1]));this.matcherRe=langRe(function join(s,i="|"){let u=0;return s.map((s=>{u+=1;const i=u;let w=source(s),x="";for(;w.length>0;){const s=_.exec(w);if(!s){x+=w;break}x+=w.substring(0,s.index),w=w.substring(s.index+s[0].length),"\\"===s[0][0]&&s[1]?x+="\\"+String(Number(s[1])+i):(x+=s[0],"("===s[0]&&u++)}return x})).map((s=>`(${s})`)).join(i)}(s),!0),this.lastIndex=0}exec(s){this.matcherRe.lastIndex=this.lastIndex;const i=this.matcherRe.exec(s);if(!i)return null;const u=i.findIndex(((s,i)=>i>0&&void 0!==s)),_=this.matchIndexes[u];return i.splice(0,u),Object.assign(i,_)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(s){if(this.multiRegexes[s])return this.multiRegexes[s];const i=new MultiRegex;return this.rules.slice(s).forEach((([s,u])=>i.addRule(s,u))),i.compile(),this.multiRegexes[s]=i,i}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(s,i){this.rules.push([s,i]),"begin"===i.type&&this.count++}exec(s){const i=this.getMatcher(this.regexIndex);i.lastIndex=this.lastIndex;let u=i.exec(s);if(this.resumingScanAtSamePosition())if(u&&u.index===this.lastIndex);else{const i=this.getMatcher(0);i.lastIndex=this.lastIndex+1,u=i.exec(s)}return u&&(this.regexIndex+=u.position+1,this.regexIndex===this.count&&this.considerAll()),u}}if(s.compilerExtensions||(s.compilerExtensions=[]),s.contains&&s.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return s.classNameAliases=inherit(s.classNameAliases||{}),function compileMode(i,u){const _=i;if(i.isCompiled)return _;[compileMatch].forEach((s=>s(i,u))),s.compilerExtensions.forEach((s=>s(i,u))),i.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach((s=>s(i,u))),i.isCompiled=!0;let w=null;if("object"==typeof i.keywords&&(w=i.keywords.$pattern,delete i.keywords.$pattern),i.keywords&&(i.keywords=compileKeywords(i.keywords,s.case_insensitive)),i.lexemes&&w)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return w=w||i.lexemes||/\w+/,_.keywordPatternRe=langRe(w,!0),u&&(i.begin||(i.begin=/\B|\b/),_.beginRe=langRe(i.begin),i.endSameAsBegin&&(i.end=i.begin),i.end||i.endsWithParent||(i.end=/\B|\b/),i.end&&(_.endRe=langRe(i.end)),_.terminatorEnd=source(i.end)||"",i.endsWithParent&&u.terminatorEnd&&(_.terminatorEnd+=(i.end?"|":"")+u.terminatorEnd)),i.illegal&&(_.illegalRe=langRe(i.illegal)),i.contains||(i.contains=[]),i.contains=[].concat(...i.contains.map((function(s){return function expandOrCloneMode(s){s.variants&&!s.cachedVariants&&(s.cachedVariants=s.variants.map((function(i){return inherit(s,{variants:null},i)})));if(s.cachedVariants)return s.cachedVariants;if(dependencyOnParent(s))return inherit(s,{starts:s.starts?inherit(s.starts):null});if(Object.isFrozen(s))return inherit(s);return s}("self"===s?i:s)}))),i.contains.forEach((function(s){compileMode(s,_)})),i.starts&&compileMode(i.starts,u),_.matcher=function buildModeRegex(s){const i=new ResumableMultiRegex;return s.contains.forEach((s=>i.addRule(s.begin,{rule:s,type:"begin"}))),s.terminatorEnd&&i.addRule(s.terminatorEnd,{type:"end"}),s.illegal&&i.addRule(s.illegal,{type:"illegal"}),i}(_),_}(s)}function dependencyOnParent(s){return!!s&&(s.endsWithParent||dependencyOnParent(s.starts))}function BuildVuePlugin(s){const i={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!s.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,escapeHTML(this.code);let i={};return this.autoDetect?(i=s.highlightAuto(this.code),this.detectedLanguage=i.language):(i=s.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),i.value},autoDetect(){return!this.language||function hasValueOrEmptyAttribute(s){return Boolean(s||""===s)}(this.autodetect)},ignoreIllegals:()=>!0},render(s){return s("pre",{},[s("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:i,VuePlugin:{install(s){s.component("highlightjs",i)}}}}const xe={"after:highlightElement":({el:s,result:i,text:u})=>{const _=nodeStream(s);if(!_.length)return;const w=document.createElement("div");w.innerHTML=i.value,i.value=function mergeStreams(s,i,u){let _=0,w="";const x=[];function selectStream(){return s.length&&i.length?s[0].offset!==i[0].offset?s[0].offset"}function close(s){w+=""}function render(s){("start"===s.event?open:close)(s.node)}for(;s.length||i.length;){let i=selectStream();if(w+=escapeHTML(u.substring(_,i[0].offset)),_=i[0].offset,i===s){x.reverse().forEach(close);do{render(i.splice(0,1)[0]),i=selectStream()}while(i===s&&i.length&&i[0].offset===_);x.reverse().forEach(open)}else"start"===i[0].event?x.push(i[0].node):x.pop(),render(i.splice(0,1)[0])}return w+escapeHTML(u.substr(_))}(_,nodeStream(w),u)}};function tag(s){return s.nodeName.toLowerCase()}function nodeStream(s){const i=[];return function _nodeStream(s,u){for(let _=s.firstChild;_;_=_.nextSibling)3===_.nodeType?u+=_.nodeValue.length:1===_.nodeType&&(i.push({event:"start",offset:u,node:_}),u=_nodeStream(_,u),tag(_).match(/br|hr|img|input/)||i.push({event:"stop",offset:u,node:_}));return u}(s,0),i}const Pe={},error=s=>{console.error(s)},warn=(s,...i)=>{console.log(`WARN: ${s}`,...i)},deprecated=(s,i)=>{Pe[`${s}/${i}`]||(console.log(`Deprecated as of ${s}. ${i}`),Pe[`${s}/${i}`]=!0)},Te=escapeHTML,Re=inherit,qe=Symbol("nomatch");var $e=function(s){const u=Object.create(null),_=Object.create(null),w=[];let x=!0;const j=/(^(<[^>]+>|\t|)+|\n)/gm,P="Could not find the language '{}', did you forget to load/include a language module?",B={disableAutodetect:!0,name:"Plain text",contains:[]};let $={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(s){return $.noHighlightRe.test(s)}function highlight(s,i,u,_){let w="",x="";"object"==typeof i?(w=s,u=i.ignoreIllegals,x=i.language,_=void 0):(deprecated("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),x=s,w=i);const j={code:w,language:x};fire("before:highlight",j);const P=j.result?j.result:_highlight(j.language,j.code,u,_);return P.code=j.code,fire("after:highlight",P),P}function _highlight(s,i,_,j){function keywordData(s,i){const u=U.case_insensitive?i[0].toLowerCase():i[0];return Object.prototype.hasOwnProperty.call(s.keywords,u)&&s.keywords[u]}function processBuffer(){null!=Z.subLanguage?function processSubLanguage(){if(""===ae)return;let s=null;if("string"==typeof Z.subLanguage){if(!u[Z.subLanguage])return void ie.addText(ae);s=_highlight(Z.subLanguage,ae,!0,ee[Z.subLanguage]),ee[Z.subLanguage]=s.top}else s=highlightAuto(ae,Z.subLanguage.length?Z.subLanguage:null);Z.relevance>0&&(le+=s.relevance),ie.addSublanguage(s.emitter,s.language)}():function processKeywords(){if(!Z.keywords)return void ie.addText(ae);let s=0;Z.keywordPatternRe.lastIndex=0;let i=Z.keywordPatternRe.exec(ae),u="";for(;i;){u+=ae.substring(s,i.index);const _=keywordData(Z,i);if(_){const[s,w]=_;if(ie.addText(u),u="",le+=w,s.startsWith("_"))u+=i[0];else{const u=U.classNameAliases[s]||s;ie.addKeyword(i[0],u)}}else u+=i[0];s=Z.keywordPatternRe.lastIndex,i=Z.keywordPatternRe.exec(ae)}u+=ae.substr(s),ie.addText(u)}(),ae=""}function startNewMode(s){return s.className&&ie.openNode(U.classNameAliases[s.className]||s.className),Z=Object.create(s,{parent:{value:Z}}),Z}function endOfMode(s,i,u){let _=function startsWith(s,i){const u=s&&s.exec(i);return u&&0===u.index}(s.endRe,u);if(_){if(s["on:end"]){const u=new Response(s);s["on:end"](i,u),u.isMatchIgnored&&(_=!1)}if(_){for(;s.endsParent&&s.parent;)s=s.parent;return s}}if(s.endsWithParent)return endOfMode(s.parent,i,u)}function doIgnore(s){return 0===Z.matcher.regexIndex?(ae+=s[0],1):(de=!0,0)}function doBeginMatch(s){const i=s[0],u=s.rule,_=new Response(u),w=[u.__beforeBegin,u["on:begin"]];for(const u of w)if(u&&(u(s,_),_.isMatchIgnored))return doIgnore(i);return u&&u.endSameAsBegin&&(u.endRe=function escape(s){return new RegExp(s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(i)),u.skip?ae+=i:(u.excludeBegin&&(ae+=i),processBuffer(),u.returnBegin||u.excludeBegin||(ae=i)),startNewMode(u),u.returnBegin?0:i.length}function doEndMatch(s){const u=s[0],_=i.substr(s.index),w=endOfMode(Z,s,_);if(!w)return qe;const x=Z;x.skip?ae+=u:(x.returnEnd||x.excludeEnd||(ae+=u),processBuffer(),x.excludeEnd&&(ae=u));do{Z.className&&ie.closeNode(),Z.skip||Z.subLanguage||(le+=Z.relevance),Z=Z.parent}while(Z!==w.parent);return w.starts&&(w.endSameAsBegin&&(w.starts.endRe=w.endRe),startNewMode(w.starts)),x.returnEnd?0:u.length}let B={};function processLexeme(u,w){const j=w&&w[0];if(ae+=u,null==j)return processBuffer(),0;if("begin"===B.type&&"end"===w.type&&B.index===w.index&&""===j){if(ae+=i.slice(w.index,w.index+1),!x){const i=new Error("0 width match regex");throw i.languageName=s,i.badRule=B.rule,i}return 1}if(B=w,"begin"===w.type)return doBeginMatch(w);if("illegal"===w.type&&!_){const s=new Error('Illegal lexeme "'+j+'" for mode "'+(Z.className||"")+'"');throw s.mode=Z,s}if("end"===w.type){const s=doEndMatch(w);if(s!==qe)return s}if("illegal"===w.type&&""===j)return 1;if(pe>1e5&&pe>3*w.index){throw new Error("potential infinite loop, way more iterations than matches")}return ae+=j,j.length}const U=getLanguage(s);if(!U)throw error(P.replace("{}",s)),new Error('Unknown language: "'+s+'"');const Y=compileLanguage(U,{plugins:w});let X="",Z=j||Y;const ee={},ie=new $.__emitter($);!function processContinuations(){const s=[];for(let i=Z;i!==U;i=i.parent)i.className&&s.unshift(i.className);s.forEach((s=>ie.openNode(s)))}();let ae="",le=0,ce=0,pe=0,de=!1;try{for(Z.matcher.considerAll();;){pe++,de?de=!1:Z.matcher.considerAll(),Z.matcher.lastIndex=ce;const s=Z.matcher.exec(i);if(!s)break;const u=processLexeme(i.substring(ce,s.index),s);ce=s.index+u}return processLexeme(i.substr(ce)),ie.closeAllNodes(),ie.finalize(),X=ie.toHTML(),{relevance:Math.floor(le),value:X,language:s,illegal:!1,emitter:ie,top:Z}}catch(u){if(u.message&&u.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:u.message,context:i.slice(ce-100,ce+100),mode:u.mode},sofar:X,relevance:0,value:Te(i),emitter:ie};if(x)return{illegal:!1,relevance:0,value:Te(i),emitter:ie,language:s,top:Z,errorRaised:u};throw u}}function highlightAuto(s,i){i=i||$.languages||Object.keys(u);const _=function justTextHighlightResult(s){const i={relevance:0,emitter:new $.__emitter($),value:Te(s),illegal:!1,top:B};return i.emitter.addText(s),i}(s),w=i.filter(getLanguage).filter(autoDetection).map((i=>_highlight(i,s,!1)));w.unshift(_);const x=w.sort(((s,i)=>{if(s.relevance!==i.relevance)return i.relevance-s.relevance;if(s.language&&i.language){if(getLanguage(s.language).supersetOf===i.language)return 1;if(getLanguage(i.language).supersetOf===s.language)return-1}return 0})),[j,P]=x,U=j;return U.second_best=P,U}const U={"before:highlightElement":({el:s})=>{$.useBR&&(s.innerHTML=s.innerHTML.replace(/\n/g,"").replace(//g,"\n"))},"after:highlightElement":({result:s})=>{$.useBR&&(s.value=s.value.replace(/\n/g,"
"))}},Y=/^(<[^>]+>|\t)+/gm,X={"after:highlightElement":({result:s})=>{$.tabReplace&&(s.value=s.value.replace(Y,(s=>s.replace(/\t/g,$.tabReplace))))}};function highlightElement(s){let i=null;const u=function blockLanguage(s){let i=s.className+" ";i+=s.parentNode?s.parentNode.className:"";const u=$.languageDetectRe.exec(i);if(u){const i=getLanguage(u[1]);return i||(warn(P.replace("{}",u[1])),warn("Falling back to no-highlight mode for this block.",s)),i?u[1]:"no-highlight"}return i.split(/\s+/).find((s=>shouldNotHighlight(s)||getLanguage(s)))}(s);if(shouldNotHighlight(u))return;fire("before:highlightElement",{el:s,language:u}),i=s;const w=i.textContent,x=u?highlight(w,{language:u,ignoreIllegals:!0}):highlightAuto(w);fire("after:highlightElement",{el:s,result:x,text:w}),s.innerHTML=x.value,function updateClassName(s,i,u){const w=i?_[i]:u;s.classList.add("hljs"),w&&s.classList.add(w)}(s,u,x.language),s.result={language:x.language,re:x.relevance,relavance:x.relevance},x.second_best&&(s.second_best={language:x.second_best.language,re:x.second_best.relevance,relavance:x.second_best.relevance})}const initHighlighting=()=>{if(initHighlighting.called)return;initHighlighting.called=!0,deprecated("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead.");document.querySelectorAll("pre code").forEach(highlightElement)};let Z=!1;function highlightAll(){if("loading"===document.readyState)return void(Z=!0);document.querySelectorAll("pre code").forEach(highlightElement)}function getLanguage(s){return s=(s||"").toLowerCase(),u[s]||u[_[s]]}function registerAliases(s,{languageName:i}){"string"==typeof s&&(s=[s]),s.forEach((s=>{_[s.toLowerCase()]=i}))}function autoDetection(s){const i=getLanguage(s);return i&&!i.disableAutodetect}function fire(s,i){const u=s;w.forEach((function(s){s[u]&&s[u](i)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function boot(){Z&&highlightAll()}),!1),Object.assign(s,{highlight,highlightAuto,highlightAll,fixMarkup:function deprecateFixMarkup(s){return deprecated("10.2.0","fixMarkup will be removed entirely in v11.0"),deprecated("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),function fixMarkup(s){return $.tabReplace||$.useBR?s.replace(j,(s=>"\n"===s?$.useBR?"
":s:$.tabReplace?s.replace(/\t/g,$.tabReplace):s)):s}(s)},highlightElement,highlightBlock:function deprecateHighlightBlock(s){return deprecated("10.7.0","highlightBlock will be removed entirely in v12.0"),deprecated("10.7.0","Please use highlightElement now."),highlightElement(s)},configure:function configure(s){s.useBR&&(deprecated("10.3.0","'useBR' will be removed entirely in v11.0"),deprecated("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),$=Re($,s)},initHighlighting,initHighlightingOnLoad:function initHighlightingOnLoad(){deprecated("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),Z=!0},registerLanguage:function registerLanguage(i,_){let w=null;try{w=_(s)}catch(s){if(error("Language definition for '{}' could not be registered.".replace("{}",i)),!x)throw s;error(s),w=B}w.name||(w.name=i),u[i]=w,w.rawDefinition=_.bind(null,s),w.aliases&®isterAliases(w.aliases,{languageName:i})},unregisterLanguage:function unregisterLanguage(s){delete u[s];for(const i of Object.keys(_))_[i]===s&&delete _[i]},listLanguages:function listLanguages(){return Object.keys(u)},getLanguage,registerAliases,requireLanguage:function requireLanguage(s){deprecated("10.4.0","requireLanguage will be removed entirely in v11."),deprecated("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");const i=getLanguage(s);if(i)return i;throw new Error("The '{}' language is required, but not loaded.".replace("{}",s))},autoDetection,inherit:Re,addPlugin:function addPlugin(s){!function upgradePluginAPI(s){s["before:highlightBlock"]&&!s["before:highlightElement"]&&(s["before:highlightElement"]=i=>{s["before:highlightBlock"](Object.assign({block:i.el},i))}),s["after:highlightBlock"]&&!s["after:highlightElement"]&&(s["after:highlightElement"]=i=>{s["after:highlightBlock"](Object.assign({block:i.el},i))})}(s),w.push(s)},vuePlugin:BuildVuePlugin(s).VuePlugin}),s.debugMode=function(){x=!1},s.safeMode=function(){x=!0},s.versionString="10.7.3";for(const s in _e)"object"==typeof _e[s]&&i(_e[s]);return Object.assign(s,_e),s.addPlugin(U),s.addPlugin(xe),s.addPlugin(X),s}({});s.exports=$e},35344:s=>{function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function bash(s){const i={},u={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[i]}]};Object.assign(i,{className:"variable",variants:[{begin:concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},u]});const _={className:"subst",begin:/\$\(/,end:/\)/,contains:[s.BACKSLASH_ESCAPE]},w={begin:/<<-?\s*(?=\w+)/,starts:{contains:[s.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},x={className:"string",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE,i,_]};_.contains.push(x);const j={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},s.NUMBER_MODE,i]},P=s.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),B={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[s.inherit(s.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[P,s.SHEBANG(),B,j,s.HASH_COMMENT_MODE,w,x,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},i]}}},73402:s=>{function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function http(s){const i="HTTP/(2|1\\.[01])",u={className:"attribute",begin:concat("^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},_=[u,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+i+" \\d{3})",end:/$/,contains:[{className:"meta",begin:i},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:_}},{begin:"(?=^[A-Z]+ (.*?) "+i+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:i},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:_}},s.inherit(u,{relevance:0})]}}},95089:s=>{const i="[A-Za-z$_][0-9A-Za-z$_]*",u=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],_=["true","false","null","undefined","NaN","Infinity"],w=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer","BigInt64Array","BigUint64Array","BigInt"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function javascript(s){const x=i,j="<>",P="",B={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(s,i)=>{const u=s[0].length+s.index,_=s.input[u];"<"!==_?">"===_&&(((s,{after:i})=>{const u="",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:s.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:$,contains:fe}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:j,end:P},{begin:B.begin,"on:begin":B.isTrulyOpeningTag,end:B.end}],subLanguage:"xml",contains:[{begin:B.begin,end:B.end,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:$,contains:["self",s.inherit(s.TITLE_MODE,{begin:x}),ye],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:s.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[ye,s.inherit(s.TITLE_MODE,{begin:x})]},{variants:[{begin:"\\."+x},{begin:"\\$"+x}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},s.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[s.inherit(s.TITLE_MODE,{begin:x}),"self",ye]},{begin:"(get|set)\\s+(?="+x+"\\()",end:/\{/,keywords:"get set",contains:[s.inherit(s.TITLE_MODE,{begin:x}),{begin:/\(\)/},ye]},{begin:/\$[(.]/}]}}},65772:s=>{s.exports=function json(s){const i={literal:"true false null"},u=[s.C_LINE_COMMENT_MODE,s.C_BLOCK_COMMENT_MODE],_=[s.QUOTE_STRING_MODE,s.C_NUMBER_MODE],w={end:",",endsWithParent:!0,excludeEnd:!0,contains:_,keywords:i},x={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE],illegal:"\\n"},s.inherit(w,{begin:/:/})].concat(u),illegal:"\\S"},j={begin:"\\[",end:"\\]",contains:[s.inherit(w)],illegal:"\\S"};return _.push(x,j),u.forEach((function(s){_.push(s)})),{name:"JSON",contains:_,keywords:i,illegal:"\\S"}}},26571:s=>{s.exports=function powershell(s){const i={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},u={begin:"`[\\s\\S]",relevance:0},_={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},w={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[u,_,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},x={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},j=s.inherit(s.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),P={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},B={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[s.TITLE_MODE]},$={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[_]}]},U={begin:/using\s/,end:/$/,returnBegin:!0,contains:[w,x,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},Y={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-)[\w\d]+/,relevance:0}]},X={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(i.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},s.inherit(s.TITLE_MODE,{endsParent:!0})]},Z=[X,j,u,s.NUMBER_MODE,w,x,P,_,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],ee={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",Z,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return X.contains.unshift(ee),{name:"PowerShell",aliases:["ps","ps1"],case_insensitive:!0,keywords:i,contains:Z.concat(B,$,U,Y,ee)}}},17285:s=>{function source(s){return s?"string"==typeof s?s:s.source:null}function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>source(s))).join("")}function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}s.exports=function xml(s){const i=concat(/[A-Z_]/,function optional(s){return concat("(",s,")?")}(/[A-Z0-9_.-]*:/),/[A-Z0-9_.-]*/),u={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},_={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},w=s.inherit(_,{begin:/\(/,end:/\)/}),x=s.inherit(s.APOS_STRING_MODE,{className:"meta-string"}),j=s.inherit(s.QUOTE_STRING_MODE,{className:"meta-string"}),P={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[_,j,x,w,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[_,w,j,x]}]}]},s.COMMENT(//,{relevance:10}),{begin://,relevance:10},u,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[P],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[P],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:i,relevance:0,starts:P}]},{className:"tag",begin:concat(/<\//,lookahead(concat(i,/>/))),contains:[{className:"name",begin:i,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17533:s=>{s.exports=function yaml(s){var i="true false yes no null",u="[\\w#;/?:@&=+$,.~*'()[\\]]+",_={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[s.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},w=s.inherit(_,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),x={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},j={end:",",endsWithParent:!0,excludeEnd:!0,keywords:i,relevance:0},P={begin:/\{/,end:/\}/,contains:[j],illegal:"\\n",relevance:0},B={begin:"\\[",end:"\\]",contains:[j],illegal:"\\n",relevance:0},$=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+u},{className:"type",begin:"!<"+u+">"},{className:"type",begin:"!"+u},{className:"type",begin:"!!"+u},{className:"meta",begin:"&"+s.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+s.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},s.HASH_COMMENT_MODE,{beginKeywords:i,keywords:{literal:i}},x,{className:"number",begin:s.C_NUMBER_RE+"\\b",relevance:0},P,B,_],U=[...$];return U.pop(),U.push(w),j.contains=U,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:$}}},251:(s,i)=>{i.read=function(s,i,u,_,w){var x,j,P=8*w-_-1,B=(1<>1,U=-7,Y=u?w-1:0,X=u?-1:1,Z=s[i+Y];for(Y+=X,x=Z&(1<<-U)-1,Z>>=-U,U+=P;U>0;x=256*x+s[i+Y],Y+=X,U-=8);for(j=x&(1<<-U)-1,x>>=-U,U+=_;U>0;j=256*j+s[i+Y],Y+=X,U-=8);if(0===x)x=1-$;else{if(x===B)return j?NaN:1/0*(Z?-1:1);j+=Math.pow(2,_),x-=$}return(Z?-1:1)*j*Math.pow(2,x-_)},i.write=function(s,i,u,_,w,x){var j,P,B,$=8*x-w-1,U=(1<<$)-1,Y=U>>1,X=23===w?Math.pow(2,-24)-Math.pow(2,-77):0,Z=_?0:x-1,ee=_?1:-1,ie=i<0||0===i&&1/i<0?1:0;for(i=Math.abs(i),isNaN(i)||i===1/0?(P=isNaN(i)?1:0,j=U):(j=Math.floor(Math.log(i)/Math.LN2),i*(B=Math.pow(2,-j))<1&&(j--,B*=2),(i+=j+Y>=1?X/B:X*Math.pow(2,1-Y))*B>=2&&(j++,B/=2),j+Y>=U?(P=0,j=U):j+Y>=1?(P=(i*B-1)*Math.pow(2,w),j+=Y):(P=i*Math.pow(2,Y-1)*Math.pow(2,w),j=0));w>=8;s[u+Z]=255&P,Z+=ee,P/=256,w-=8);for(j=j<0;s[u+Z]=255&j,Z+=ee,j/=256,$-=8);s[u+Z-ee]|=128*ie}},9404:function(s){s.exports=function(){"use strict";var s=Array.prototype.slice;function createClass(s,i){i&&(s.prototype=Object.create(i.prototype)),s.prototype.constructor=s}function Iterable(s){return isIterable(s)?s:Seq(s)}function KeyedIterable(s){return isKeyed(s)?s:KeyedSeq(s)}function IndexedIterable(s){return isIndexed(s)?s:IndexedSeq(s)}function SetIterable(s){return isIterable(s)&&!isAssociative(s)?s:SetSeq(s)}function isIterable(s){return!(!s||!s[i])}function isKeyed(s){return!(!s||!s[u])}function isIndexed(s){return!(!s||!s[_])}function isAssociative(s){return isKeyed(s)||isIndexed(s)}function isOrdered(s){return!(!s||!s[w])}createClass(KeyedIterable,Iterable),createClass(IndexedIterable,Iterable),createClass(SetIterable,Iterable),Iterable.isIterable=isIterable,Iterable.isKeyed=isKeyed,Iterable.isIndexed=isIndexed,Iterable.isAssociative=isAssociative,Iterable.isOrdered=isOrdered,Iterable.Keyed=KeyedIterable,Iterable.Indexed=IndexedIterable,Iterable.Set=SetIterable;var i="@@__IMMUTABLE_ITERABLE__@@",u="@@__IMMUTABLE_KEYED__@@",_="@@__IMMUTABLE_INDEXED__@@",w="@@__IMMUTABLE_ORDERED__@@",x="delete",j=5,P=1<>>0;if(""+u!==i||4294967295===u)return NaN;i=u}return i<0?ensureSize(s)+i:i}function returnTrue(){return!0}function wholeSlice(s,i,u){return(0===s||void 0!==u&&s<=-u)&&(void 0===i||void 0!==u&&i>=u)}function resolveBegin(s,i){return resolveIndex(s,i,0)}function resolveEnd(s,i){return resolveIndex(s,i,i)}function resolveIndex(s,i,u){return void 0===s?u:s<0?Math.max(0,i+s):void 0===i?s:Math.min(i,s)}var X=0,Z=1,ee=2,ie="function"==typeof Symbol&&Symbol.iterator,ae="@@iterator",le=ie||ae;function Iterator(s){this.next=s}function iteratorValue(s,i,u,_){var w=0===s?i:1===s?u:[i,u];return _?_.value=w:_={value:w,done:!1},_}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(s){return!!getIteratorFn(s)}function isIterator(s){return s&&"function"==typeof s.next}function getIterator(s){var i=getIteratorFn(s);return i&&i.call(s)}function getIteratorFn(s){var i=s&&(ie&&s[ie]||s[ae]);if("function"==typeof i)return i}function isArrayLike(s){return s&&"number"==typeof s.length}function Seq(s){return null==s?emptySequence():isIterable(s)?s.toSeq():seqFromValue(s)}function KeyedSeq(s){return null==s?emptySequence().toKeyedSeq():isIterable(s)?isKeyed(s)?s.toSeq():s.fromEntrySeq():keyedSeqFromValue(s)}function IndexedSeq(s){return null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s.toIndexedSeq():indexedSeqFromValue(s)}function SetSeq(s){return(null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s:indexedSeqFromValue(s)).toSetSeq()}Iterator.prototype.toString=function(){return"[Iterator]"},Iterator.KEYS=X,Iterator.VALUES=Z,Iterator.ENTRIES=ee,Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()},Iterator.prototype[le]=function(){return this},createClass(Seq,Iterable),Seq.of=function(){return Seq(arguments)},Seq.prototype.toSeq=function(){return this},Seq.prototype.toString=function(){return this.__toString("Seq {","}")},Seq.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},Seq.prototype.__iterate=function(s,i){return seqIterate(this,s,i,!0)},Seq.prototype.__iterator=function(s,i){return seqIterator(this,s,i,!0)},createClass(KeyedSeq,Seq),KeyedSeq.prototype.toKeyedSeq=function(){return this},createClass(IndexedSeq,Seq),IndexedSeq.of=function(){return IndexedSeq(arguments)},IndexedSeq.prototype.toIndexedSeq=function(){return this},IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")},IndexedSeq.prototype.__iterate=function(s,i){return seqIterate(this,s,i,!1)},IndexedSeq.prototype.__iterator=function(s,i){return seqIterator(this,s,i,!1)},createClass(SetSeq,Seq),SetSeq.of=function(){return SetSeq(arguments)},SetSeq.prototype.toSetSeq=function(){return this},Seq.isSeq=isSeq,Seq.Keyed=KeyedSeq,Seq.Set=SetSeq,Seq.Indexed=IndexedSeq;var ce,pe,de,fe="@@__IMMUTABLE_SEQ__@@";function ArraySeq(s){this._array=s,this.size=s.length}function ObjectSeq(s){var i=Object.keys(s);this._object=s,this._keys=i,this.size=i.length}function IterableSeq(s){this._iterable=s,this.size=s.length||s.size}function IteratorSeq(s){this._iterator=s,this._iteratorCache=[]}function isSeq(s){return!(!s||!s[fe])}function emptySequence(){return ce||(ce=new ArraySeq([]))}function keyedSeqFromValue(s){var i=Array.isArray(s)?new ArraySeq(s).fromEntrySeq():isIterator(s)?new IteratorSeq(s).fromEntrySeq():hasIterator(s)?new IterableSeq(s).fromEntrySeq():"object"==typeof s?new ObjectSeq(s):void 0;if(!i)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+s);return i}function indexedSeqFromValue(s){var i=maybeIndexedSeqFromValue(s);if(!i)throw new TypeError("Expected Array or iterable object of values: "+s);return i}function seqFromValue(s){var i=maybeIndexedSeqFromValue(s)||"object"==typeof s&&new ObjectSeq(s);if(!i)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+s);return i}function maybeIndexedSeqFromValue(s){return isArrayLike(s)?new ArraySeq(s):isIterator(s)?new IteratorSeq(s):hasIterator(s)?new IterableSeq(s):void 0}function seqIterate(s,i,u,_){var w=s._cache;if(w){for(var x=w.length-1,j=0;j<=x;j++){var P=w[u?x-j:j];if(!1===i(P[1],_?P[0]:j,s))return j+1}return j}return s.__iterateUncached(i,u)}function seqIterator(s,i,u,_){var w=s._cache;if(w){var x=w.length-1,j=0;return new Iterator((function(){var s=w[u?x-j:j];return j++>x?iteratorDone():iteratorValue(i,_?s[0]:j-1,s[1])}))}return s.__iteratorUncached(i,u)}function fromJS(s,i){return i?fromJSWith(i,s,"",{"":s}):fromJSDefault(s)}function fromJSWith(s,i,u,_){return Array.isArray(i)?s.call(_,u,IndexedSeq(i).map((function(u,_){return fromJSWith(s,u,_,i)}))):isPlainObj(i)?s.call(_,u,KeyedSeq(i).map((function(u,_){return fromJSWith(s,u,_,i)}))):i}function fromJSDefault(s){return Array.isArray(s)?IndexedSeq(s).map(fromJSDefault).toList():isPlainObj(s)?KeyedSeq(s).map(fromJSDefault).toMap():s}function isPlainObj(s){return s&&(s.constructor===Object||void 0===s.constructor)}function is(s,i){if(s===i||s!=s&&i!=i)return!0;if(!s||!i)return!1;if("function"==typeof s.valueOf&&"function"==typeof i.valueOf){if((s=s.valueOf())===(i=i.valueOf())||s!=s&&i!=i)return!0;if(!s||!i)return!1}return!("function"!=typeof s.equals||"function"!=typeof i.equals||!s.equals(i))}function deepEqual(s,i){if(s===i)return!0;if(!isIterable(i)||void 0!==s.size&&void 0!==i.size&&s.size!==i.size||void 0!==s.__hash&&void 0!==i.__hash&&s.__hash!==i.__hash||isKeyed(s)!==isKeyed(i)||isIndexed(s)!==isIndexed(i)||isOrdered(s)!==isOrdered(i))return!1;if(0===s.size&&0===i.size)return!0;var u=!isAssociative(s);if(isOrdered(s)){var _=s.entries();return i.every((function(s,i){var w=_.next().value;return w&&is(w[1],s)&&(u||is(w[0],i))}))&&_.next().done}var w=!1;if(void 0===s.size)if(void 0===i.size)"function"==typeof s.cacheResult&&s.cacheResult();else{w=!0;var x=s;s=i,i=x}var j=!0,P=i.__iterate((function(i,_){if(u?!s.has(i):w?!is(i,s.get(_,$)):!is(s.get(_,$),i))return j=!1,!1}));return j&&s.size===P}function Repeat(s,i){if(!(this instanceof Repeat))return new Repeat(s,i);if(this._value=s,this.size=void 0===i?1/0:Math.max(0,i),0===this.size){if(pe)return pe;pe=this}}function invariant(s,i){if(!s)throw new Error(i)}function Range(s,i,u){if(!(this instanceof Range))return new Range(s,i,u);if(invariant(0!==u,"Cannot step a Range by 0"),s=s||0,void 0===i&&(i=1/0),u=void 0===u?1:Math.abs(u),i_?iteratorDone():iteratorValue(s,w,u[i?_-w++:w++])}))},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(s,i){return void 0===i||this.has(s)?this._object[s]:i},ObjectSeq.prototype.has=function(s){return this._object.hasOwnProperty(s)},ObjectSeq.prototype.__iterate=function(s,i){for(var u=this._object,_=this._keys,w=_.length-1,x=0;x<=w;x++){var j=_[i?w-x:x];if(!1===s(u[j],j,this))return x+1}return x},ObjectSeq.prototype.__iterator=function(s,i){var u=this._object,_=this._keys,w=_.length-1,x=0;return new Iterator((function(){var j=_[i?w-x:x];return x++>w?iteratorDone():iteratorValue(s,j,u[j])}))},ObjectSeq.prototype[w]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(s,i){if(i)return this.cacheResult().__iterate(s,i);var u=getIterator(this._iterable),_=0;if(isIterator(u))for(var w;!(w=u.next()).done&&!1!==s(w.value,_++,this););return _},IterableSeq.prototype.__iteratorUncached=function(s,i){if(i)return this.cacheResult().__iterator(s,i);var u=getIterator(this._iterable);if(!isIterator(u))return new Iterator(iteratorDone);var _=0;return new Iterator((function(){var i=u.next();return i.done?i:iteratorValue(s,_++,i.value)}))},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(s,i){if(i)return this.cacheResult().__iterate(s,i);for(var u,_=this._iterator,w=this._iteratorCache,x=0;x=_.length){var i=u.next();if(i.done)return i;_[w]=i.value}return iteratorValue(s,w,_[w++])}))},createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(s,i){return this.has(s)?this._value:i},Repeat.prototype.includes=function(s){return is(this._value,s)},Repeat.prototype.slice=function(s,i){var u=this.size;return wholeSlice(s,i,u)?this:new Repeat(this._value,resolveEnd(i,u)-resolveBegin(s,u))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(s){return is(this._value,s)?0:-1},Repeat.prototype.lastIndexOf=function(s){return is(this._value,s)?this.size:-1},Repeat.prototype.__iterate=function(s,i){for(var u=0;u=0&&i=0&&uu?iteratorDone():iteratorValue(s,x++,j)}))},Range.prototype.equals=function(s){return s instanceof Range?this._start===s._start&&this._end===s._end&&this._step===s._step:deepEqual(this,s)},createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var ye="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function imul(s,i){var u=65535&(s|=0),_=65535&(i|=0);return u*_+((s>>>16)*_+u*(i>>>16)<<16>>>0)|0};function smi(s){return s>>>1&1073741824|3221225471&s}function hash(s){if(!1===s||null==s)return 0;if("function"==typeof s.valueOf&&(!1===(s=s.valueOf())||null==s))return 0;if(!0===s)return 1;var i=typeof s;if("number"===i){if(s!=s||s===1/0)return 0;var u=0|s;for(u!==s&&(u^=4294967295*s);s>4294967295;)u^=s/=4294967295;return smi(u)}if("string"===i)return s.length>Te?cachedHashString(s):hashString(s);if("function"==typeof s.hashCode)return s.hashCode();if("object"===i)return hashJSObj(s);if("function"==typeof s.toString)return hashString(s.toString());throw new Error("Value type "+i+" cannot be hashed.")}function cachedHashString(s){var i=$e[s];return void 0===i&&(i=hashString(s),qe===Re&&(qe=0,$e={}),qe++,$e[s]=i),i}function hashString(s){for(var i=0,u=0;u0)switch(s.nodeType){case 1:return s.uniqueID;case 9:return s.documentElement&&s.documentElement.uniqueID}}var we,Se="function"==typeof WeakMap;Se&&(we=new WeakMap);var xe=0,Pe="__immutablehash__";"function"==typeof Symbol&&(Pe=Symbol(Pe));var Te=16,Re=255,qe=0,$e={};function assertNotInfinite(s){invariant(s!==1/0,"Cannot perform this action with an infinite size.")}function Map(s){return null==s?emptyMap():isMap(s)&&!isOrdered(s)?s:emptyMap().withMutations((function(i){var u=KeyedIterable(s);assertNotInfinite(u.size),u.forEach((function(s,u){return i.set(u,s)}))}))}function isMap(s){return!(!s||!s[We])}createClass(Map,KeyedCollection),Map.of=function(){var i=s.call(arguments,0);return emptyMap().withMutations((function(s){for(var u=0;u=i.length)throw new Error("Missing value for key: "+i[u]);s.set(i[u],i[u+1])}}))},Map.prototype.toString=function(){return this.__toString("Map {","}")},Map.prototype.get=function(s,i){return this._root?this._root.get(0,void 0,s,i):i},Map.prototype.set=function(s,i){return updateMap(this,s,i)},Map.prototype.setIn=function(s,i){return this.updateIn(s,$,(function(){return i}))},Map.prototype.remove=function(s){return updateMap(this,s,$)},Map.prototype.deleteIn=function(s){return this.updateIn(s,(function(){return $}))},Map.prototype.update=function(s,i,u){return 1===arguments.length?s(this):this.updateIn([s],i,u)},Map.prototype.updateIn=function(s,i,u){u||(u=i,i=void 0);var _=updateInDeepMap(this,forceIterator(s),i,u);return _===$?void 0:_},Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},Map.prototype.mergeWith=function(i){return mergeIntoMapWith(this,i,s.call(arguments,1))},Map.prototype.mergeIn=function(i){var u=s.call(arguments,1);return this.updateIn(i,emptyMap(),(function(s){return"function"==typeof s.merge?s.merge.apply(s,u):u[u.length-1]}))},Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)},Map.prototype.mergeDeepWith=function(i){var u=s.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(i),u)},Map.prototype.mergeDeepIn=function(i){var u=s.call(arguments,1);return this.updateIn(i,emptyMap(),(function(s){return"function"==typeof s.mergeDeep?s.mergeDeep.apply(s,u):u[u.length-1]}))},Map.prototype.sort=function(s){return OrderedMap(sortFactory(this,s))},Map.prototype.sortBy=function(s,i){return OrderedMap(sortFactory(this,i,s))},Map.prototype.withMutations=function(s){var i=this.asMutable();return s(i),i.wasAltered()?i.__ensureOwner(this.__ownerID):this},Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},Map.prototype.asImmutable=function(){return this.__ensureOwner()},Map.prototype.wasAltered=function(){return this.__altered},Map.prototype.__iterator=function(s,i){return new MapIterator(this,s,i)},Map.prototype.__iterate=function(s,i){var u=this,_=0;return this._root&&this._root.iterate((function(i){return _++,s(i[1],i[0],u)}),i),_},Map.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeMap(this.size,this._root,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Map.isMap=isMap;var ze,We="@@__IMMUTABLE_MAP__@@",He=Map.prototype;function ArrayMapNode(s,i){this.ownerID=s,this.entries=i}function BitmapIndexedNode(s,i,u){this.ownerID=s,this.bitmap=i,this.nodes=u}function HashArrayMapNode(s,i,u){this.ownerID=s,this.count=i,this.nodes=u}function HashCollisionNode(s,i,u){this.ownerID=s,this.keyHash=i,this.entries=u}function ValueNode(s,i,u){this.ownerID=s,this.keyHash=i,this.entry=u}function MapIterator(s,i,u){this._type=i,this._reverse=u,this._stack=s._root&&mapIteratorFrame(s._root)}function mapIteratorValue(s,i){return iteratorValue(s,i[0],i[1])}function mapIteratorFrame(s,i){return{node:s,index:0,__prev:i}}function makeMap(s,i,u,_){var w=Object.create(He);return w.size=s,w._root=i,w.__ownerID=u,w.__hash=_,w.__altered=!1,w}function emptyMap(){return ze||(ze=makeMap(0))}function updateMap(s,i,u){var _,w;if(s._root){var x=MakeRef(U),j=MakeRef(Y);if(_=updateNode(s._root,s.__ownerID,0,void 0,i,u,x,j),!j.value)return s;w=s.size+(x.value?u===$?-1:1:0)}else{if(u===$)return s;w=1,_=new ArrayMapNode(s.__ownerID,[[i,u]])}return s.__ownerID?(s.size=w,s._root=_,s.__hash=void 0,s.__altered=!0,s):_?makeMap(w,_):emptyMap()}function updateNode(s,i,u,_,w,x,j,P){return s?s.update(i,u,_,w,x,j,P):x===$?s:(SetRef(P),SetRef(j),new ValueNode(i,_,[w,x]))}function isLeafNode(s){return s.constructor===ValueNode||s.constructor===HashCollisionNode}function mergeIntoNode(s,i,u,_,w){if(s.keyHash===_)return new HashCollisionNode(i,_,[s.entry,w]);var x,P=(0===u?s.keyHash:s.keyHash>>>u)&B,$=(0===u?_:_>>>u)&B;return new BitmapIndexedNode(i,1<>>=1)j[B]=1&u?i[x++]:void 0;return j[_]=w,new HashArrayMapNode(s,x+1,j)}function mergeIntoMapWith(s,i,u){for(var _=[],w=0;w>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135,s+=s>>8,127&(s+=s>>16)}function setIn(s,i,u,_){var w=_?s:arrCopy(s);return w[i]=u,w}function spliceIn(s,i,u,_){var w=s.length+1;if(_&&i+1===w)return s[i]=u,s;for(var x=new Array(w),j=0,P=0;P=Ye)return createNodes(s,B,_,w);var Z=s&&s===this.ownerID,ee=Z?B:arrCopy(B);return X?P?U===Y-1?ee.pop():ee[U]=ee.pop():ee[U]=[_,w]:ee.push([_,w]),Z?(this.entries=ee,this):new ArrayMapNode(s,ee)}},BitmapIndexedNode.prototype.get=function(s,i,u,_){void 0===i&&(i=hash(u));var w=1<<((0===s?i:i>>>s)&B),x=this.bitmap;return 0==(x&w)?_:this.nodes[popCount(x&w-1)].get(s+j,i,u,_)},BitmapIndexedNode.prototype.update=function(s,i,u,_,w,x,P){void 0===u&&(u=hash(_));var U=(0===i?u:u>>>i)&B,Y=1<=Xe)return expandNodes(s,ie,X,U,le);if(Z&&!le&&2===ie.length&&isLeafNode(ie[1^ee]))return ie[1^ee];if(Z&&le&&1===ie.length&&isLeafNode(le))return le;var ce=s&&s===this.ownerID,pe=Z?le?X:X^Y:X|Y,de=Z?le?setIn(ie,ee,le,ce):spliceOut(ie,ee,ce):spliceIn(ie,ee,le,ce);return ce?(this.bitmap=pe,this.nodes=de,this):new BitmapIndexedNode(s,pe,de)},HashArrayMapNode.prototype.get=function(s,i,u,_){void 0===i&&(i=hash(u));var w=(0===s?i:i>>>s)&B,x=this.nodes[w];return x?x.get(s+j,i,u,_):_},HashArrayMapNode.prototype.update=function(s,i,u,_,w,x,P){void 0===u&&(u=hash(_));var U=(0===i?u:u>>>i)&B,Y=w===$,X=this.nodes,Z=X[U];if(Y&&!Z)return this;var ee=updateNode(Z,s,i+j,u,_,w,x,P);if(ee===Z)return this;var ie=this.count;if(Z){if(!ee&&--ie0&&_=0&&s>>i&B;if(_>=this.array.length)return new VNode([],s);var w,x=0===_;if(i>0){var P=this.array[_];if((w=P&&P.removeBefore(s,i-j,u))===P&&x)return this}if(x&&!w)return this;var $=editableVNode(this,s);if(!x)for(var U=0;U<_;U++)$.array[U]=void 0;return w&&($.array[_]=w),$},VNode.prototype.removeAfter=function(s,i,u){if(u===(i?1<>>i&B;if(w>=this.array.length)return this;if(i>0){var x=this.array[w];if((_=x&&x.removeAfter(s,i-j,u))===x&&w===this.array.length-1)return this}var P=editableVNode(this,s);return P.array.splice(w+1),_&&(P.array[w]=_),P};var rt,nt,ot={};function iterateList(s,i){var u=s._origin,_=s._capacity,w=getTailOffset(_),x=s._tail;return iterateNodeOrLeaf(s._root,s._level,0);function iterateNodeOrLeaf(s,i,u){return 0===i?iterateLeaf(s,u):iterateNode(s,i,u)}function iterateLeaf(s,j){var B=j===w?x&&x.array:s&&s.array,$=j>u?0:u-j,U=_-j;return U>P&&(U=P),function(){if($===U)return ot;var s=i?--U:$++;return B&&B[s]}}function iterateNode(s,w,x){var B,$=s&&s.array,U=x>u?0:u-x>>w,Y=1+(_-x>>w);return Y>P&&(Y=P),function(){for(;;){if(B){var s=B();if(s!==ot)return s;B=null}if(U===Y)return ot;var u=i?--Y:U++;B=iterateNodeOrLeaf($&&$[u],w-j,x+(u<=s.size||i<0)return s.withMutations((function(s){i<0?setListBounds(s,i).set(0,u):setListBounds(s,0,i+1).set(i,u)}));i+=s._origin;var _=s._tail,w=s._root,x=MakeRef(Y);return i>=getTailOffset(s._capacity)?_=updateVNode(_,s.__ownerID,0,i,u,x):w=updateVNode(w,s.__ownerID,s._level,i,u,x),x.value?s.__ownerID?(s._root=w,s._tail=_,s.__hash=void 0,s.__altered=!0,s):makeList(s._origin,s._capacity,s._level,w,_):s}function updateVNode(s,i,u,_,w,x){var P,$=_>>>u&B,U=s&&$0){var Y=s&&s.array[$],X=updateVNode(Y,i,u-j,_,w,x);return X===Y?s:((P=editableVNode(s,i)).array[$]=X,P)}return U&&s.array[$]===w?s:(SetRef(x),P=editableVNode(s,i),void 0===w&&$===P.array.length-1?P.array.pop():P.array[$]=w,P)}function editableVNode(s,i){return i&&s&&i===s.ownerID?s:new VNode(s?s.array.slice():[],i)}function listNodeFor(s,i){if(i>=getTailOffset(s._capacity))return s._tail;if(i<1<0;)u=u.array[i>>>_&B],_-=j;return u}}function setListBounds(s,i,u){void 0!==i&&(i|=0),void 0!==u&&(u|=0);var _=s.__ownerID||new OwnerID,w=s._origin,x=s._capacity,P=w+i,$=void 0===u?x:u<0?x+u:w+u;if(P===w&&$===x)return s;if(P>=$)return s.clear();for(var U=s._level,Y=s._root,X=0;P+X<0;)Y=new VNode(Y&&Y.array.length?[void 0,Y]:[],_),X+=1<<(U+=j);X&&(P+=X,w+=X,$+=X,x+=X);for(var Z=getTailOffset(x),ee=getTailOffset($);ee>=1<Z?new VNode([],_):ie;if(ie&&ee>Z&&Pj;ce-=j){var pe=Z>>>ce&B;le=le.array[pe]=editableVNode(le.array[pe],_)}le.array[Z>>>j&B]=ie}if($=ee)P-=ee,$-=ee,U=j,Y=null,ae=ae&&ae.removeBefore(_,0,P);else if(P>w||ee>>U&B;if(de!==ee>>>U&B)break;de&&(X+=(1<w&&(Y=Y.removeBefore(_,U,P-X)),Y&&eew&&(w=P.size),isIterable(j)||(P=P.map((function(s){return fromJS(s)}))),_.push(P)}return w>s.size&&(s=s.setSize(w)),mergeIntoCollectionWith(s,i,_)}function getTailOffset(s){return s>>j<=P&&j.size>=2*x.size?(_=(w=j.filter((function(s,i){return void 0!==s&&B!==i}))).toKeyedSeq().map((function(s){return s[0]})).flip().toMap(),s.__ownerID&&(_.__ownerID=w.__ownerID=s.__ownerID)):(_=x.remove(i),w=B===j.size-1?j.pop():j.set(B,void 0))}else if(U){if(u===j.get(B)[1])return s;_=x,w=j.set(B,[i,u])}else _=x.set(i,j.size),w=j.set(j.size,[i,u]);return s.__ownerID?(s.size=_.size,s._map=_,s._list=w,s.__hash=void 0,s):makeOrderedMap(_,w)}function ToKeyedSequence(s,i){this._iter=s,this._useKeys=i,this.size=s.size}function ToIndexedSequence(s){this._iter=s,this.size=s.size}function ToSetSequence(s){this._iter=s,this.size=s.size}function FromEntriesSequence(s){this._iter=s,this.size=s.size}function flipFactory(s){var i=makeSequence(s);return i._iter=s,i.size=s.size,i.flip=function(){return s},i.reverse=function(){var i=s.reverse.apply(this);return i.flip=function(){return s.reverse()},i},i.has=function(i){return s.includes(i)},i.includes=function(i){return s.has(i)},i.cacheResult=cacheResultThrough,i.__iterateUncached=function(i,u){var _=this;return s.__iterate((function(s,u){return!1!==i(u,s,_)}),u)},i.__iteratorUncached=function(i,u){if(i===ee){var _=s.__iterator(i,u);return new Iterator((function(){var s=_.next();if(!s.done){var i=s.value[0];s.value[0]=s.value[1],s.value[1]=i}return s}))}return s.__iterator(i===Z?X:Z,u)},i}function mapFactory(s,i,u){var _=makeSequence(s);return _.size=s.size,_.has=function(i){return s.has(i)},_.get=function(_,w){var x=s.get(_,$);return x===$?w:i.call(u,x,_,s)},_.__iterateUncached=function(_,w){var x=this;return s.__iterate((function(s,w,j){return!1!==_(i.call(u,s,w,j),w,x)}),w)},_.__iteratorUncached=function(_,w){var x=s.__iterator(ee,w);return new Iterator((function(){var w=x.next();if(w.done)return w;var j=w.value,P=j[0];return iteratorValue(_,P,i.call(u,j[1],P,s),w)}))},_}function reverseFactory(s,i){var u=makeSequence(s);return u._iter=s,u.size=s.size,u.reverse=function(){return s},s.flip&&(u.flip=function(){var i=flipFactory(s);return i.reverse=function(){return s.flip()},i}),u.get=function(u,_){return s.get(i?u:-1-u,_)},u.has=function(u){return s.has(i?u:-1-u)},u.includes=function(i){return s.includes(i)},u.cacheResult=cacheResultThrough,u.__iterate=function(i,u){var _=this;return s.__iterate((function(s,u){return i(s,u,_)}),!u)},u.__iterator=function(i,u){return s.__iterator(i,!u)},u}function filterFactory(s,i,u,_){var w=makeSequence(s);return _&&(w.has=function(_){var w=s.get(_,$);return w!==$&&!!i.call(u,w,_,s)},w.get=function(_,w){var x=s.get(_,$);return x!==$&&i.call(u,x,_,s)?x:w}),w.__iterateUncached=function(w,x){var j=this,P=0;return s.__iterate((function(s,x,B){if(i.call(u,s,x,B))return P++,w(s,_?x:P-1,j)}),x),P},w.__iteratorUncached=function(w,x){var j=s.__iterator(ee,x),P=0;return new Iterator((function(){for(;;){var x=j.next();if(x.done)return x;var B=x.value,$=B[0],U=B[1];if(i.call(u,U,$,s))return iteratorValue(w,_?$:P++,U,x)}}))},w}function countByFactory(s,i,u){var _=Map().asMutable();return s.__iterate((function(w,x){_.update(i.call(u,w,x,s),0,(function(s){return s+1}))})),_.asImmutable()}function groupByFactory(s,i,u){var _=isKeyed(s),w=(isOrdered(s)?OrderedMap():Map()).asMutable();s.__iterate((function(x,j){w.update(i.call(u,x,j,s),(function(s){return(s=s||[]).push(_?[j,x]:x),s}))}));var x=iterableClass(s);return w.map((function(i){return reify(s,x(i))}))}function sliceFactory(s,i,u,_){var w=s.size;if(void 0!==i&&(i|=0),void 0!==u&&(u===1/0?u=w:u|=0),wholeSlice(i,u,w))return s;var x=resolveBegin(i,w),j=resolveEnd(u,w);if(x!=x||j!=j)return sliceFactory(s.toSeq().cacheResult(),i,u,_);var P,B=j-x;B==B&&(P=B<0?0:B);var $=makeSequence(s);return $.size=0===P?P:s.size&&P||void 0,!_&&isSeq(s)&&P>=0&&($.get=function(i,u){return(i=wrapIndex(this,i))>=0&&iP)return iteratorDone();var s=w.next();return _||i===Z?s:iteratorValue(i,B-1,i===X?void 0:s.value[1],s)}))},$}function takeWhileFactory(s,i,u){var _=makeSequence(s);return _.__iterateUncached=function(_,w){var x=this;if(w)return this.cacheResult().__iterate(_,w);var j=0;return s.__iterate((function(s,w,P){return i.call(u,s,w,P)&&++j&&_(s,w,x)})),j},_.__iteratorUncached=function(_,w){var x=this;if(w)return this.cacheResult().__iterator(_,w);var j=s.__iterator(ee,w),P=!0;return new Iterator((function(){if(!P)return iteratorDone();var s=j.next();if(s.done)return s;var w=s.value,B=w[0],$=w[1];return i.call(u,$,B,x)?_===ee?s:iteratorValue(_,B,$,s):(P=!1,iteratorDone())}))},_}function skipWhileFactory(s,i,u,_){var w=makeSequence(s);return w.__iterateUncached=function(w,x){var j=this;if(x)return this.cacheResult().__iterate(w,x);var P=!0,B=0;return s.__iterate((function(s,x,$){if(!P||!(P=i.call(u,s,x,$)))return B++,w(s,_?x:B-1,j)})),B},w.__iteratorUncached=function(w,x){var j=this;if(x)return this.cacheResult().__iterator(w,x);var P=s.__iterator(ee,x),B=!0,$=0;return new Iterator((function(){var s,x,U;do{if((s=P.next()).done)return _||w===Z?s:iteratorValue(w,$++,w===X?void 0:s.value[1],s);var Y=s.value;x=Y[0],U=Y[1],B&&(B=i.call(u,U,x,j))}while(B);return w===ee?s:iteratorValue(w,x,U,s)}))},w}function concatFactory(s,i){var u=isKeyed(s),_=[s].concat(i).map((function(s){return isIterable(s)?u&&(s=KeyedIterable(s)):s=u?keyedSeqFromValue(s):indexedSeqFromValue(Array.isArray(s)?s:[s]),s})).filter((function(s){return 0!==s.size}));if(0===_.length)return s;if(1===_.length){var w=_[0];if(w===s||u&&isKeyed(w)||isIndexed(s)&&isIndexed(w))return w}var x=new ArraySeq(_);return u?x=x.toKeyedSeq():isIndexed(s)||(x=x.toSetSeq()),(x=x.flatten(!0)).size=_.reduce((function(s,i){if(void 0!==s){var u=i.size;if(void 0!==u)return s+u}}),0),x}function flattenFactory(s,i,u){var _=makeSequence(s);return _.__iterateUncached=function(_,w){var x=0,j=!1;function flatDeep(s,P){var B=this;s.__iterate((function(s,w){return(!i||P0}function zipWithFactory(s,i,u){var _=makeSequence(s);return _.size=new ArraySeq(u).map((function(s){return s.size})).min(),_.__iterate=function(s,i){for(var u,_=this.__iterator(Z,i),w=0;!(u=_.next()).done&&!1!==s(u.value,w++,this););return w},_.__iteratorUncached=function(s,_){var w=u.map((function(s){return s=Iterable(s),getIterator(_?s.reverse():s)})),x=0,j=!1;return new Iterator((function(){var u;return j||(u=w.map((function(s){return s.next()})),j=u.some((function(s){return s.done}))),j?iteratorDone():iteratorValue(s,x++,i.apply(null,u.map((function(s){return s.value}))))}))},_}function reify(s,i){return isSeq(s)?i:s.constructor(i)}function validateEntry(s){if(s!==Object(s))throw new TypeError("Expected [K, V] tuple: "+s)}function resolveSize(s){return assertNotInfinite(s.size),ensureSize(s)}function iterableClass(s){return isKeyed(s)?KeyedIterable:isIndexed(s)?IndexedIterable:SetIterable}function makeSequence(s){return Object.create((isKeyed(s)?KeyedSeq:isIndexed(s)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(s,i){return s>i?1:s=0;u--)i={value:arguments[u],next:i};return this.__ownerID?(this.size=s,this._head=i,this.__hash=void 0,this.__altered=!0,this):makeStack(s,i)},Stack.prototype.pushAll=function(s){if(0===(s=IndexedIterable(s)).size)return this;assertNotInfinite(s.size);var i=this.size,u=this._head;return s.reverse().forEach((function(s){i++,u={value:s,next:u}})),this.__ownerID?(this.size=i,this._head=u,this.__hash=void 0,this.__altered=!0,this):makeStack(i,u)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(s){return this.pushAll(s)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(s,i){if(wholeSlice(s,i,this.size))return this;var u=resolveBegin(s,this.size);if(resolveEnd(i,this.size)!==this.size)return IndexedCollection.prototype.slice.call(this,s,i);for(var _=this.size-u,w=this._head;u--;)w=w.next;return this.__ownerID?(this.size=_,this._head=w,this.__hash=void 0,this.__altered=!0,this):makeStack(_,w)},Stack.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeStack(this.size,this._head,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Stack.prototype.__iterate=function(s,i){if(i)return this.reverse().__iterate(s);for(var u=0,_=this._head;_&&!1!==s(_.value,u++,this);)_=_.next;return u},Stack.prototype.__iterator=function(s,i){if(i)return this.reverse().__iterator(s);var u=0,_=this._head;return new Iterator((function(){if(_){var i=_.value;return _=_.next,iteratorValue(s,u++,i)}return iteratorDone()}))},Stack.isStack=isStack;var pt,ht="@@__IMMUTABLE_STACK__@@",dt=Stack.prototype;function makeStack(s,i,u,_){var w=Object.create(dt);return w.size=s,w._head=i,w.__ownerID=u,w.__hash=_,w.__altered=!1,w}function emptyStack(){return pt||(pt=makeStack(0))}function mixin(s,i){var keyCopier=function(u){s.prototype[u]=i[u]};return Object.keys(i).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(i).forEach(keyCopier),s}dt[ht]=!0,dt.withMutations=He.withMutations,dt.asMutable=He.asMutable,dt.asImmutable=He.asImmutable,dt.wasAltered=He.wasAltered,Iterable.Iterator=Iterator,mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var s=new Array(this.size||0);return this.valueSeq().__iterate((function(i,u){s[u]=i})),s},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJS?s.toJS():s})).__toJS()},toJSON:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJSON?s.toJSON():s})).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,!0)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var s={};return this.__iterate((function(i,u){s[u]=i})),s},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(s,i){return 0===this.size?s+i:s+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+i},concat:function(){return reify(this,concatFactory(this,s.call(arguments,0)))},includes:function(s){return this.some((function(i){return is(i,s)}))},entries:function(){return this.__iterator(ee)},every:function(s,i){assertNotInfinite(this.size);var u=!0;return this.__iterate((function(_,w,x){if(!s.call(i,_,w,x))return u=!1,!1})),u},filter:function(s,i){return reify(this,filterFactory(this,s,i,!0))},find:function(s,i,u){var _=this.findEntry(s,i);return _?_[1]:u},forEach:function(s,i){return assertNotInfinite(this.size),this.__iterate(i?s.bind(i):s)},join:function(s){assertNotInfinite(this.size),s=void 0!==s?""+s:",";var i="",u=!0;return this.__iterate((function(_){u?u=!1:i+=s,i+=null!=_?_.toString():""})),i},keys:function(){return this.__iterator(X)},map:function(s,i){return reify(this,mapFactory(this,s,i))},reduce:function(s,i,u){var _,w;return assertNotInfinite(this.size),arguments.length<2?w=!0:_=i,this.__iterate((function(i,x,j){w?(w=!1,_=i):_=s.call(u,_,i,x,j)})),_},reduceRight:function(s,i,u){var _=this.toKeyedSeq().reverse();return _.reduce.apply(_,arguments)},reverse:function(){return reify(this,reverseFactory(this,!0))},slice:function(s,i){return reify(this,sliceFactory(this,s,i,!0))},some:function(s,i){return!this.every(not(s),i)},sort:function(s){return reify(this,sortFactory(this,s))},values:function(){return this.__iterator(Z)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(s,i){return ensureSize(s?this.toSeq().filter(s,i):this)},countBy:function(s,i){return countByFactory(this,s,i)},equals:function(s){return deepEqual(this,s)},entrySeq:function(){var s=this;if(s._cache)return new ArraySeq(s._cache);var i=s.toSeq().map(entryMapper).toIndexedSeq();return i.fromEntrySeq=function(){return s.toSeq()},i},filterNot:function(s,i){return this.filter(not(s),i)},findEntry:function(s,i,u){var _=u;return this.__iterate((function(u,w,x){if(s.call(i,u,w,x))return _=[w,u],!1})),_},findKey:function(s,i){var u=this.findEntry(s,i);return u&&u[0]},findLast:function(s,i,u){return this.toKeyedSeq().reverse().find(s,i,u)},findLastEntry:function(s,i,u){return this.toKeyedSeq().reverse().findEntry(s,i,u)},findLastKey:function(s,i){return this.toKeyedSeq().reverse().findKey(s,i)},first:function(){return this.find(returnTrue)},flatMap:function(s,i){return reify(this,flatMapFactory(this,s,i))},flatten:function(s){return reify(this,flattenFactory(this,s,!0))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(s,i){return this.find((function(i,u){return is(u,s)}),void 0,i)},getIn:function(s,i){for(var u,_=this,w=forceIterator(s);!(u=w.next()).done;){var x=u.value;if((_=_&&_.get?_.get(x,$):$)===$)return i}return _},groupBy:function(s,i){return groupByFactory(this,s,i)},has:function(s){return this.get(s,$)!==$},hasIn:function(s){return this.getIn(s,$)!==$},isSubset:function(s){return s="function"==typeof s.includes?s:Iterable(s),this.every((function(i){return s.includes(i)}))},isSuperset:function(s){return(s="function"==typeof s.isSubset?s:Iterable(s)).isSubset(this)},keyOf:function(s){return this.findKey((function(i){return is(i,s)}))},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(s){return this.toKeyedSeq().reverse().keyOf(s)},max:function(s){return maxFactory(this,s)},maxBy:function(s,i){return maxFactory(this,i,s)},min:function(s){return maxFactory(this,s?neg(s):defaultNegComparator)},minBy:function(s,i){return maxFactory(this,i?neg(i):defaultNegComparator,s)},rest:function(){return this.slice(1)},skip:function(s){return this.slice(Math.max(0,s))},skipLast:function(s){return reify(this,this.toSeq().reverse().skip(s).reverse())},skipWhile:function(s,i){return reify(this,skipWhileFactory(this,s,i,!0))},skipUntil:function(s,i){return this.skipWhile(not(s),i)},sortBy:function(s,i){return reify(this,sortFactory(this,i,s))},take:function(s){return this.slice(0,Math.max(0,s))},takeLast:function(s){return reify(this,this.toSeq().reverse().take(s).reverse())},takeWhile:function(s,i){return reify(this,takeWhileFactory(this,s,i))},takeUntil:function(s,i){return this.takeWhile(not(s),i)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var mt=Iterable.prototype;mt[i]=!0,mt[le]=mt.values,mt.__toJS=mt.toArray,mt.__toStringMapper=quoteString,mt.inspect=mt.toSource=function(){return this.toString()},mt.chain=mt.flatMap,mt.contains=mt.includes,mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(s,i){var u=this,_=0;return reify(this,this.toSeq().map((function(w,x){return s.call(i,[x,w],_++,u)})).fromEntrySeq())},mapKeys:function(s,i){var u=this;return reify(this,this.toSeq().flip().map((function(_,w){return s.call(i,_,w,u)})).flip())}});var gt=KeyedIterable.prototype;function keyMapper(s,i){return i}function entryMapper(s,i){return[i,s]}function not(s){return function(){return!s.apply(this,arguments)}}function neg(s){return function(){return-s.apply(this,arguments)}}function quoteString(s){return"string"==typeof s?JSON.stringify(s):String(s)}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(s,i){return si?-1:0}function hashIterable(s){if(s.size===1/0)return 0;var i=isOrdered(s),u=isKeyed(s),_=i?1:0;return murmurHashOfSize(s.__iterate(u?i?function(s,i){_=31*_+hashMerge(hash(s),hash(i))|0}:function(s,i){_=_+hashMerge(hash(s),hash(i))|0}:i?function(s){_=31*_+hash(s)|0}:function(s){_=_+hash(s)|0}),_)}function murmurHashOfSize(s,i){return i=ye(i,3432918353),i=ye(i<<15|i>>>-15,461845907),i=ye(i<<13|i>>>-13,5),i=ye((i=(i+3864292196|0)^s)^i>>>16,2246822507),i=smi((i=ye(i^i>>>13,3266489909))^i>>>16)}function hashMerge(s,i){return s^i+2654435769+(s<<6)+(s>>2)|0}return gt[u]=!0,gt[le]=mt.entries,gt.__toJS=mt.toObject,gt.__toStringMapper=function(s,i){return JSON.stringify(i)+": "+quoteString(s)},mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,!1)},filter:function(s,i){return reify(this,filterFactory(this,s,i,!1))},findIndex:function(s,i){var u=this.findEntry(s,i);return u?u[0]:-1},indexOf:function(s){var i=this.keyOf(s);return void 0===i?-1:i},lastIndexOf:function(s){var i=this.lastKeyOf(s);return void 0===i?-1:i},reverse:function(){return reify(this,reverseFactory(this,!1))},slice:function(s,i){return reify(this,sliceFactory(this,s,i,!1))},splice:function(s,i){var u=arguments.length;if(i=Math.max(0|i,0),0===u||2===u&&!i)return this;s=resolveBegin(s,s<0?this.count():this.size);var _=this.slice(0,s);return reify(this,1===u?_:_.concat(arrCopy(arguments,2),this.slice(s+i)))},findLastIndex:function(s,i){var u=this.findLastEntry(s,i);return u?u[0]:-1},first:function(){return this.get(0)},flatten:function(s){return reify(this,flattenFactory(this,s,!1))},get:function(s,i){return(s=wrapIndex(this,s))<0||this.size===1/0||void 0!==this.size&&s>this.size?i:this.find((function(i,u){return u===s}),void 0,i)},has:function(s){return(s=wrapIndex(this,s))>=0&&(void 0!==this.size?this.size===1/0||s{"function"==typeof Object.create?s.exports=function inherits(s,i){i&&(s.super_=i,s.prototype=Object.create(i.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}))}:s.exports=function inherits(s,i){if(i){s.super_=i;var TempCtor=function(){};TempCtor.prototype=i.prototype,s.prototype=new TempCtor,s.prototype.constructor=s}}},5419:s=>{s.exports=function(s,i,u,_){var w=new Blob(void 0!==_?[_,s]:[s],{type:u||"application/octet-stream"});if(void 0!==window.navigator.msSaveBlob)window.navigator.msSaveBlob(w,i);else{var x=window.URL&&window.URL.createObjectURL?window.URL.createObjectURL(w):window.webkitURL.createObjectURL(w),j=document.createElement("a");j.style.display="none",j.href=x,j.setAttribute("download",i),void 0===j.download&&j.setAttribute("target","_blank"),document.body.appendChild(j),j.click(),setTimeout((function(){document.body.removeChild(j),window.URL.revokeObjectURL(x)}),200)}}},20181:(s,i,u)=>{var _=NaN,w="[object Symbol]",x=/^\s+|\s+$/g,j=/^[-+]0x[0-9a-f]+$/i,P=/^0b[01]+$/i,B=/^0o[0-7]+$/i,$=parseInt,U="object"==typeof u.g&&u.g&&u.g.Object===Object&&u.g,Y="object"==typeof self&&self&&self.Object===Object&&self,X=U||Y||Function("return this")(),Z=Object.prototype.toString,ee=Math.max,ie=Math.min,now=function(){return X.Date.now()};function isObject(s){var i=typeof s;return!!s&&("object"==i||"function"==i)}function toNumber(s){if("number"==typeof s)return s;if(function isSymbol(s){return"symbol"==typeof s||function isObjectLike(s){return!!s&&"object"==typeof s}(s)&&Z.call(s)==w}(s))return _;if(isObject(s)){var i="function"==typeof s.valueOf?s.valueOf():s;s=isObject(i)?i+"":i}if("string"!=typeof s)return 0===s?s:+s;s=s.replace(x,"");var u=P.test(s);return u||B.test(s)?$(s.slice(2),u?2:8):j.test(s)?_:+s}s.exports=function debounce(s,i,u){var _,w,x,j,P,B,$=0,U=!1,Y=!1,X=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function invokeFunc(i){var u=_,x=w;return _=w=void 0,$=i,j=s.apply(x,u)}function shouldInvoke(s){var u=s-B;return void 0===B||u>=i||u<0||Y&&s-$>=x}function timerExpired(){var s=now();if(shouldInvoke(s))return trailingEdge(s);P=setTimeout(timerExpired,function remainingWait(s){var u=i-(s-B);return Y?ie(u,x-(s-$)):u}(s))}function trailingEdge(s){return P=void 0,X&&_?invokeFunc(s):(_=w=void 0,j)}function debounced(){var s=now(),u=shouldInvoke(s);if(_=arguments,w=this,B=s,u){if(void 0===P)return function leadingEdge(s){return $=s,P=setTimeout(timerExpired,i),U?invokeFunc(s):j}(B);if(Y)return P=setTimeout(timerExpired,i),invokeFunc(B)}return void 0===P&&(P=setTimeout(timerExpired,i)),j}return i=toNumber(i)||0,isObject(u)&&(U=!!u.leading,x=(Y="maxWait"in u)?ee(toNumber(u.maxWait)||0,i):x,X="trailing"in u?!!u.trailing:X),debounced.cancel=function cancel(){void 0!==P&&clearTimeout(P),$=0,_=B=w=P=void 0},debounced.flush=function flush(){return void 0===P?j:trailingEdge(now())},debounced}},55580:(s,i,u)=>{var _=u(56110)(u(9325),"DataView");s.exports=_},21549:(s,i,u)=>{var _=u(22032),w=u(63862),x=u(66721),j=u(12749),P=u(35749);function Hash(s){var i=-1,u=null==s?0:s.length;for(this.clear();++i{var _=u(39344),w=u(94033);function LazyWrapper(s){this.__wrapped__=s,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}LazyWrapper.prototype=_(w.prototype),LazyWrapper.prototype.constructor=LazyWrapper,s.exports=LazyWrapper},80079:(s,i,u)=>{var _=u(63702),w=u(70080),x=u(24739),j=u(48655),P=u(31175);function ListCache(s){var i=-1,u=null==s?0:s.length;for(this.clear();++i{var _=u(39344),w=u(94033);function LodashWrapper(s,i){this.__wrapped__=s,this.__actions__=[],this.__chain__=!!i,this.__index__=0,this.__values__=void 0}LodashWrapper.prototype=_(w.prototype),LodashWrapper.prototype.constructor=LodashWrapper,s.exports=LodashWrapper},68223:(s,i,u)=>{var _=u(56110)(u(9325),"Map");s.exports=_},53661:(s,i,u)=>{var _=u(63040),w=u(17670),x=u(90289),j=u(4509),P=u(72949);function MapCache(s){var i=-1,u=null==s?0:s.length;for(this.clear();++i{var _=u(56110)(u(9325),"Promise");s.exports=_},76545:(s,i,u)=>{var _=u(56110)(u(9325),"Set");s.exports=_},38859:(s,i,u)=>{var _=u(53661),w=u(31380),x=u(51459);function SetCache(s){var i=-1,u=null==s?0:s.length;for(this.__data__=new _;++i{var _=u(80079),w=u(51420),x=u(90938),j=u(63605),P=u(29817),B=u(80945);function Stack(s){var i=this.__data__=new _(s);this.size=i.size}Stack.prototype.clear=w,Stack.prototype.delete=x,Stack.prototype.get=j,Stack.prototype.has=P,Stack.prototype.set=B,s.exports=Stack},51873:(s,i,u)=>{var _=u(9325).Symbol;s.exports=_},37828:(s,i,u)=>{var _=u(9325).Uint8Array;s.exports=_},28303:(s,i,u)=>{var _=u(56110)(u(9325),"WeakMap");s.exports=_},91033:s=>{s.exports=function apply(s,i,u){switch(u.length){case 0:return s.call(i);case 1:return s.call(i,u[0]);case 2:return s.call(i,u[0],u[1]);case 3:return s.call(i,u[0],u[1],u[2])}return s.apply(i,u)}},83729:s=>{s.exports=function arrayEach(s,i){for(var u=-1,_=null==s?0:s.length;++u<_&&!1!==i(s[u],u,s););return s}},79770:s=>{s.exports=function arrayFilter(s,i){for(var u=-1,_=null==s?0:s.length,w=0,x=[];++u<_;){var j=s[u];i(j,u,s)&&(x[w++]=j)}return x}},15325:(s,i,u)=>{var _=u(96131);s.exports=function arrayIncludes(s,i){return!!(null==s?0:s.length)&&_(s,i,0)>-1}},70695:(s,i,u)=>{var _=u(78096),w=u(72428),x=u(56449),j=u(3656),P=u(30361),B=u(37167),$=Object.prototype.hasOwnProperty;s.exports=function arrayLikeKeys(s,i){var u=x(s),U=!u&&w(s),Y=!u&&!U&&j(s),X=!u&&!U&&!Y&&B(s),Z=u||U||Y||X,ee=Z?_(s.length,String):[],ie=ee.length;for(var ae in s)!i&&!$.call(s,ae)||Z&&("length"==ae||Y&&("offset"==ae||"parent"==ae)||X&&("buffer"==ae||"byteLength"==ae||"byteOffset"==ae)||P(ae,ie))||ee.push(ae);return ee}},34932:s=>{s.exports=function arrayMap(s,i){for(var u=-1,_=null==s?0:s.length,w=Array(_);++u<_;)w[u]=i(s[u],u,s);return w}},14528:s=>{s.exports=function arrayPush(s,i){for(var u=-1,_=i.length,w=s.length;++u<_;)s[w+u]=i[u];return s}},40882:s=>{s.exports=function arrayReduce(s,i,u,_){var w=-1,x=null==s?0:s.length;for(_&&x&&(u=s[++w]);++w{s.exports=function arraySome(s,i){for(var u=-1,_=null==s?0:s.length;++u<_;)if(i(s[u],u,s))return!0;return!1}},61074:s=>{s.exports=function asciiToArray(s){return s.split("")}},1733:s=>{var i=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;s.exports=function asciiWords(s){return s.match(i)||[]}},87805:(s,i,u)=>{var _=u(43360),w=u(75288);s.exports=function assignMergeValue(s,i,u){(void 0!==u&&!w(s[i],u)||void 0===u&&!(i in s))&&_(s,i,u)}},16547:(s,i,u)=>{var _=u(43360),w=u(75288),x=Object.prototype.hasOwnProperty;s.exports=function assignValue(s,i,u){var j=s[i];x.call(s,i)&&w(j,u)&&(void 0!==u||i in s)||_(s,i,u)}},26025:(s,i,u)=>{var _=u(75288);s.exports=function assocIndexOf(s,i){for(var u=s.length;u--;)if(_(s[u][0],i))return u;return-1}},74733:(s,i,u)=>{var _=u(21791),w=u(95950);s.exports=function baseAssign(s,i){return s&&_(i,w(i),s)}},43838:(s,i,u)=>{var _=u(21791),w=u(37241);s.exports=function baseAssignIn(s,i){return s&&_(i,w(i),s)}},43360:(s,i,u)=>{var _=u(93243);s.exports=function baseAssignValue(s,i,u){"__proto__"==i&&_?_(s,i,{configurable:!0,enumerable:!0,value:u,writable:!0}):s[i]=u}},9999:(s,i,u)=>{var _=u(37217),w=u(83729),x=u(16547),j=u(74733),P=u(43838),B=u(93290),$=u(23007),U=u(92271),Y=u(48948),X=u(50002),Z=u(83349),ee=u(5861),ie=u(76189),ae=u(77199),le=u(35529),ce=u(56449),pe=u(3656),de=u(87730),fe=u(23805),ye=u(38440),be=u(95950),_e=u(37241),we="[object Arguments]",Se="[object Function]",xe="[object Object]",Pe={};Pe[we]=Pe["[object Array]"]=Pe["[object ArrayBuffer]"]=Pe["[object DataView]"]=Pe["[object Boolean]"]=Pe["[object Date]"]=Pe["[object Float32Array]"]=Pe["[object Float64Array]"]=Pe["[object Int8Array]"]=Pe["[object Int16Array]"]=Pe["[object Int32Array]"]=Pe["[object Map]"]=Pe["[object Number]"]=Pe[xe]=Pe["[object RegExp]"]=Pe["[object Set]"]=Pe["[object String]"]=Pe["[object Symbol]"]=Pe["[object Uint8Array]"]=Pe["[object Uint8ClampedArray]"]=Pe["[object Uint16Array]"]=Pe["[object Uint32Array]"]=!0,Pe["[object Error]"]=Pe[Se]=Pe["[object WeakMap]"]=!1,s.exports=function baseClone(s,i,u,Te,Re,qe){var $e,ze=1&i,We=2&i,He=4&i;if(u&&($e=Re?u(s,Te,Re,qe):u(s)),void 0!==$e)return $e;if(!fe(s))return s;var Ye=ce(s);if(Ye){if($e=ie(s),!ze)return $(s,$e)}else{var Xe=ee(s),Qe=Xe==Se||"[object GeneratorFunction]"==Xe;if(pe(s))return B(s,ze);if(Xe==xe||Xe==we||Qe&&!Re){if($e=We||Qe?{}:le(s),!ze)return We?Y(s,P($e,s)):U(s,j($e,s))}else{if(!Pe[Xe])return Re?s:{};$e=ae(s,Xe,ze)}}qe||(qe=new _);var et=qe.get(s);if(et)return et;qe.set(s,$e),ye(s)?s.forEach((function(_){$e.add(baseClone(_,i,u,_,s,qe))})):de(s)&&s.forEach((function(_,w){$e.set(w,baseClone(_,i,u,w,s,qe))}));var tt=Ye?void 0:(He?We?Z:X:We?_e:be)(s);return w(tt||s,(function(_,w){tt&&(_=s[w=_]),x($e,w,baseClone(_,i,u,w,s,qe))})),$e}},39344:(s,i,u)=>{var _=u(23805),w=Object.create,x=function(){function object(){}return function(s){if(!_(s))return{};if(w)return w(s);object.prototype=s;var i=new object;return object.prototype=void 0,i}}();s.exports=x},80909:(s,i,u)=>{var _=u(30641),w=u(38329)(_);s.exports=w},2523:s=>{s.exports=function baseFindIndex(s,i,u,_){for(var w=s.length,x=u+(_?1:-1);_?x--:++x{var _=u(14528),w=u(45891);s.exports=function baseFlatten(s,i,u,x,j){var P=-1,B=s.length;for(u||(u=w),j||(j=[]);++P0&&u($)?i>1?baseFlatten($,i-1,u,x,j):_(j,$):x||(j[j.length]=$)}return j}},86649:(s,i,u)=>{var _=u(83221)();s.exports=_},30641:(s,i,u)=>{var _=u(86649),w=u(95950);s.exports=function baseForOwn(s,i){return s&&_(s,i,w)}},47422:(s,i,u)=>{var _=u(31769),w=u(77797);s.exports=function baseGet(s,i){for(var u=0,x=(i=_(i,s)).length;null!=s&&u{var _=u(14528),w=u(56449);s.exports=function baseGetAllKeys(s,i,u){var x=i(s);return w(s)?x:_(x,u(s))}},72552:(s,i,u)=>{var _=u(51873),w=u(659),x=u(59350),j=_?_.toStringTag:void 0;s.exports=function baseGetTag(s){return null==s?void 0===s?"[object Undefined]":"[object Null]":j&&j in Object(s)?w(s):x(s)}},28077:s=>{s.exports=function baseHasIn(s,i){return null!=s&&i in Object(s)}},96131:(s,i,u)=>{var _=u(2523),w=u(85463),x=u(76959);s.exports=function baseIndexOf(s,i,u){return i==i?x(s,i,u):_(s,w,u)}},27534:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function baseIsArguments(s){return w(s)&&"[object Arguments]"==_(s)}},60270:(s,i,u)=>{var _=u(87068),w=u(40346);s.exports=function baseIsEqual(s,i,u,x,j){return s===i||(null==s||null==i||!w(s)&&!w(i)?s!=s&&i!=i:_(s,i,u,x,baseIsEqual,j))}},87068:(s,i,u)=>{var _=u(37217),w=u(25911),x=u(21986),j=u(50689),P=u(5861),B=u(56449),$=u(3656),U=u(37167),Y="[object Arguments]",X="[object Array]",Z="[object Object]",ee=Object.prototype.hasOwnProperty;s.exports=function baseIsEqualDeep(s,i,u,ie,ae,le){var ce=B(s),pe=B(i),de=ce?X:P(s),fe=pe?X:P(i),ye=(de=de==Y?Z:de)==Z,be=(fe=fe==Y?Z:fe)==Z,_e=de==fe;if(_e&&$(s)){if(!$(i))return!1;ce=!0,ye=!1}if(_e&&!ye)return le||(le=new _),ce||U(s)?w(s,i,u,ie,ae,le):x(s,i,de,u,ie,ae,le);if(!(1&u)){var we=ye&&ee.call(s,"__wrapped__"),Se=be&&ee.call(i,"__wrapped__");if(we||Se){var xe=we?s.value():s,Pe=Se?i.value():i;return le||(le=new _),ae(xe,Pe,u,ie,le)}}return!!_e&&(le||(le=new _),j(s,i,u,ie,ae,le))}},29172:(s,i,u)=>{var _=u(5861),w=u(40346);s.exports=function baseIsMap(s){return w(s)&&"[object Map]"==_(s)}},41799:(s,i,u)=>{var _=u(37217),w=u(60270);s.exports=function baseIsMatch(s,i,u,x){var j=u.length,P=j,B=!x;if(null==s)return!P;for(s=Object(s);j--;){var $=u[j];if(B&&$[2]?$[1]!==s[$[0]]:!($[0]in s))return!1}for(;++j{s.exports=function baseIsNaN(s){return s!=s}},45083:(s,i,u)=>{var _=u(1882),w=u(87296),x=u(23805),j=u(47473),P=/^\[object .+?Constructor\]$/,B=Function.prototype,$=Object.prototype,U=B.toString,Y=$.hasOwnProperty,X=RegExp("^"+U.call(Y).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");s.exports=function baseIsNative(s){return!(!x(s)||w(s))&&(_(s)?X:P).test(j(s))}},16038:(s,i,u)=>{var _=u(5861),w=u(40346);s.exports=function baseIsSet(s){return w(s)&&"[object Set]"==_(s)}},4901:(s,i,u)=>{var _=u(72552),w=u(30294),x=u(40346),j={};j["[object Float32Array]"]=j["[object Float64Array]"]=j["[object Int8Array]"]=j["[object Int16Array]"]=j["[object Int32Array]"]=j["[object Uint8Array]"]=j["[object Uint8ClampedArray]"]=j["[object Uint16Array]"]=j["[object Uint32Array]"]=!0,j["[object Arguments]"]=j["[object Array]"]=j["[object ArrayBuffer]"]=j["[object Boolean]"]=j["[object DataView]"]=j["[object Date]"]=j["[object Error]"]=j["[object Function]"]=j["[object Map]"]=j["[object Number]"]=j["[object Object]"]=j["[object RegExp]"]=j["[object Set]"]=j["[object String]"]=j["[object WeakMap]"]=!1,s.exports=function baseIsTypedArray(s){return x(s)&&w(s.length)&&!!j[_(s)]}},15389:(s,i,u)=>{var _=u(93663),w=u(87978),x=u(83488),j=u(56449),P=u(50583);s.exports=function baseIteratee(s){return"function"==typeof s?s:null==s?x:"object"==typeof s?j(s)?w(s[0],s[1]):_(s):P(s)}},88984:(s,i,u)=>{var _=u(55527),w=u(3650),x=Object.prototype.hasOwnProperty;s.exports=function baseKeys(s){if(!_(s))return w(s);var i=[];for(var u in Object(s))x.call(s,u)&&"constructor"!=u&&i.push(u);return i}},72903:(s,i,u)=>{var _=u(23805),w=u(55527),x=u(90181),j=Object.prototype.hasOwnProperty;s.exports=function baseKeysIn(s){if(!_(s))return x(s);var i=w(s),u=[];for(var P in s)("constructor"!=P||!i&&j.call(s,P))&&u.push(P);return u}},94033:s=>{s.exports=function baseLodash(){}},93663:(s,i,u)=>{var _=u(41799),w=u(10776),x=u(67197);s.exports=function baseMatches(s){var i=w(s);return 1==i.length&&i[0][2]?x(i[0][0],i[0][1]):function(u){return u===s||_(u,s,i)}}},87978:(s,i,u)=>{var _=u(60270),w=u(58156),x=u(80631),j=u(28586),P=u(30756),B=u(67197),$=u(77797);s.exports=function baseMatchesProperty(s,i){return j(s)&&P(i)?B($(s),i):function(u){var j=w(u,s);return void 0===j&&j===i?x(u,s):_(i,j,3)}}},85250:(s,i,u)=>{var _=u(37217),w=u(87805),x=u(86649),j=u(42824),P=u(23805),B=u(37241),$=u(14974);s.exports=function baseMerge(s,i,u,U,Y){s!==i&&x(i,(function(x,B){if(Y||(Y=new _),P(x))j(s,i,B,u,baseMerge,U,Y);else{var X=U?U($(s,B),x,B+"",s,i,Y):void 0;void 0===X&&(X=x),w(s,B,X)}}),B)}},42824:(s,i,u)=>{var _=u(87805),w=u(93290),x=u(71961),j=u(23007),P=u(35529),B=u(72428),$=u(56449),U=u(83693),Y=u(3656),X=u(1882),Z=u(23805),ee=u(11331),ie=u(37167),ae=u(14974),le=u(69884);s.exports=function baseMergeDeep(s,i,u,ce,pe,de,fe){var ye=ae(s,u),be=ae(i,u),_e=fe.get(be);if(_e)_(s,u,_e);else{var we=de?de(ye,be,u+"",s,i,fe):void 0,Se=void 0===we;if(Se){var xe=$(be),Pe=!xe&&Y(be),Te=!xe&&!Pe&&ie(be);we=be,xe||Pe||Te?$(ye)?we=ye:U(ye)?we=j(ye):Pe?(Se=!1,we=w(be,!0)):Te?(Se=!1,we=x(be,!0)):we=[]:ee(be)||B(be)?(we=ye,B(ye)?we=le(ye):Z(ye)&&!X(ye)||(we=P(be))):Se=!1}Se&&(fe.set(be,we),pe(we,be,ce,de,fe),fe.delete(be)),_(s,u,we)}}},47237:s=>{s.exports=function baseProperty(s){return function(i){return null==i?void 0:i[s]}}},17255:(s,i,u)=>{var _=u(47422);s.exports=function basePropertyDeep(s){return function(i){return _(i,s)}}},54552:s=>{s.exports=function basePropertyOf(s){return function(i){return null==s?void 0:s[i]}}},85558:s=>{s.exports=function baseReduce(s,i,u,_,w){return w(s,(function(s,w,x){u=_?(_=!1,s):i(u,s,w,x)})),u}},69302:(s,i,u)=>{var _=u(83488),w=u(56757),x=u(32865);s.exports=function baseRest(s,i){return x(w(s,i,_),s+"")}},73170:(s,i,u)=>{var _=u(16547),w=u(31769),x=u(30361),j=u(23805),P=u(77797);s.exports=function baseSet(s,i,u,B){if(!j(s))return s;for(var $=-1,U=(i=w(i,s)).length,Y=U-1,X=s;null!=X&&++${var _=u(83488),w=u(48152),x=w?function(s,i){return w.set(s,i),s}:_;s.exports=x},19570:(s,i,u)=>{var _=u(37334),w=u(93243),x=u(83488),j=w?function(s,i){return w(s,"toString",{configurable:!0,enumerable:!1,value:_(i),writable:!0})}:x;s.exports=j},25160:s=>{s.exports=function baseSlice(s,i,u){var _=-1,w=s.length;i<0&&(i=-i>w?0:w+i),(u=u>w?w:u)<0&&(u+=w),w=i>u?0:u-i>>>0,i>>>=0;for(var x=Array(w);++_{var _=u(80909);s.exports=function baseSome(s,i){var u;return _(s,(function(s,_,w){return!(u=i(s,_,w))})),!!u}},78096:s=>{s.exports=function baseTimes(s,i){for(var u=-1,_=Array(s);++u{var _=u(51873),w=u(34932),x=u(56449),j=u(44394),P=_?_.prototype:void 0,B=P?P.toString:void 0;s.exports=function baseToString(s){if("string"==typeof s)return s;if(x(s))return w(s,baseToString)+"";if(j(s))return B?B.call(s):"";var i=s+"";return"0"==i&&1/s==-Infinity?"-0":i}},54128:(s,i,u)=>{var _=u(31800),w=/^\s+/;s.exports=function baseTrim(s){return s?s.slice(0,_(s)+1).replace(w,""):s}},27301:s=>{s.exports=function baseUnary(s){return function(i){return s(i)}}},19931:(s,i,u)=>{var _=u(31769),w=u(68090),x=u(68969),j=u(77797);s.exports=function baseUnset(s,i){return i=_(i,s),null==(s=x(s,i))||delete s[j(w(i))]}},51234:s=>{s.exports=function baseZipObject(s,i,u){for(var _=-1,w=s.length,x=i.length,j={};++_{s.exports=function cacheHas(s,i){return s.has(i)}},31769:(s,i,u)=>{var _=u(56449),w=u(28586),x=u(61802),j=u(13222);s.exports=function castPath(s,i){return _(s)?s:w(s,i)?[s]:x(j(s))}},28754:(s,i,u)=>{var _=u(25160);s.exports=function castSlice(s,i,u){var w=s.length;return u=void 0===u?w:u,!i&&u>=w?s:_(s,i,u)}},49653:(s,i,u)=>{var _=u(37828);s.exports=function cloneArrayBuffer(s){var i=new s.constructor(s.byteLength);return new _(i).set(new _(s)),i}},93290:(s,i,u)=>{s=u.nmd(s);var _=u(9325),w=i&&!i.nodeType&&i,x=w&&s&&!s.nodeType&&s,j=x&&x.exports===w?_.Buffer:void 0,P=j?j.allocUnsafe:void 0;s.exports=function cloneBuffer(s,i){if(i)return s.slice();var u=s.length,_=P?P(u):new s.constructor(u);return s.copy(_),_}},76169:(s,i,u)=>{var _=u(49653);s.exports=function cloneDataView(s,i){var u=i?_(s.buffer):s.buffer;return new s.constructor(u,s.byteOffset,s.byteLength)}},73201:s=>{var i=/\w*$/;s.exports=function cloneRegExp(s){var u=new s.constructor(s.source,i.exec(s));return u.lastIndex=s.lastIndex,u}},93736:(s,i,u)=>{var _=u(51873),w=_?_.prototype:void 0,x=w?w.valueOf:void 0;s.exports=function cloneSymbol(s){return x?Object(x.call(s)):{}}},71961:(s,i,u)=>{var _=u(49653);s.exports=function cloneTypedArray(s,i){var u=i?_(s.buffer):s.buffer;return new s.constructor(u,s.byteOffset,s.length)}},91596:s=>{var i=Math.max;s.exports=function composeArgs(s,u,_,w){for(var x=-1,j=s.length,P=_.length,B=-1,$=u.length,U=i(j-P,0),Y=Array($+U),X=!w;++B<$;)Y[B]=u[B];for(;++x{var i=Math.max;s.exports=function composeArgsRight(s,u,_,w){for(var x=-1,j=s.length,P=-1,B=_.length,$=-1,U=u.length,Y=i(j-B,0),X=Array(Y+U),Z=!w;++x{s.exports=function copyArray(s,i){var u=-1,_=s.length;for(i||(i=Array(_));++u<_;)i[u]=s[u];return i}},21791:(s,i,u)=>{var _=u(16547),w=u(43360);s.exports=function copyObject(s,i,u,x){var j=!u;u||(u={});for(var P=-1,B=i.length;++P{var _=u(21791),w=u(4664);s.exports=function copySymbols(s,i){return _(s,w(s),i)}},48948:(s,i,u)=>{var _=u(21791),w=u(86375);s.exports=function copySymbolsIn(s,i){return _(s,w(s),i)}},55481:(s,i,u)=>{var _=u(9325)["__core-js_shared__"];s.exports=_},58523:s=>{s.exports=function countHolders(s,i){for(var u=s.length,_=0;u--;)s[u]===i&&++_;return _}},20999:(s,i,u)=>{var _=u(69302),w=u(36800);s.exports=function createAssigner(s){return _((function(i,u){var _=-1,x=u.length,j=x>1?u[x-1]:void 0,P=x>2?u[2]:void 0;for(j=s.length>3&&"function"==typeof j?(x--,j):void 0,P&&w(u[0],u[1],P)&&(j=x<3?void 0:j,x=1),i=Object(i);++_{var _=u(64894);s.exports=function createBaseEach(s,i){return function(u,w){if(null==u)return u;if(!_(u))return s(u,w);for(var x=u.length,j=i?x:-1,P=Object(u);(i?j--:++j{s.exports=function createBaseFor(s){return function(i,u,_){for(var w=-1,x=Object(i),j=_(i),P=j.length;P--;){var B=j[s?P:++w];if(!1===u(x[B],B,x))break}return i}}},11842:(s,i,u)=>{var _=u(82819),w=u(9325);s.exports=function createBind(s,i,u){var x=1&i,j=_(s);return function wrapper(){return(this&&this!==w&&this instanceof wrapper?j:s).apply(x?u:this,arguments)}}},12507:(s,i,u)=>{var _=u(28754),w=u(49698),x=u(63912),j=u(13222);s.exports=function createCaseFirst(s){return function(i){i=j(i);var u=w(i)?x(i):void 0,P=u?u[0]:i.charAt(0),B=u?_(u,1).join(""):i.slice(1);return P[s]()+B}}},45539:(s,i,u)=>{var _=u(40882),w=u(50828),x=u(66645),j=RegExp("['’]","g");s.exports=function createCompounder(s){return function(i){return _(x(w(i).replace(j,"")),s,"")}}},82819:(s,i,u)=>{var _=u(39344),w=u(23805);s.exports=function createCtor(s){return function(){var i=arguments;switch(i.length){case 0:return new s;case 1:return new s(i[0]);case 2:return new s(i[0],i[1]);case 3:return new s(i[0],i[1],i[2]);case 4:return new s(i[0],i[1],i[2],i[3]);case 5:return new s(i[0],i[1],i[2],i[3],i[4]);case 6:return new s(i[0],i[1],i[2],i[3],i[4],i[5]);case 7:return new s(i[0],i[1],i[2],i[3],i[4],i[5],i[6])}var u=_(s.prototype),x=s.apply(u,i);return w(x)?x:u}}},77078:(s,i,u)=>{var _=u(91033),w=u(82819),x=u(37471),j=u(18073),P=u(11287),B=u(36306),$=u(9325);s.exports=function createCurry(s,i,u){var U=w(s);return function wrapper(){for(var w=arguments.length,Y=Array(w),X=w,Z=P(wrapper);X--;)Y[X]=arguments[X];var ee=w<3&&Y[0]!==Z&&Y[w-1]!==Z?[]:B(Y,Z);return(w-=ee.length){var _=u(15389),w=u(64894),x=u(95950);s.exports=function createFind(s){return function(i,u,j){var P=Object(i);if(!w(i)){var B=_(u,3);i=x(i),u=function(s){return B(P[s],s,P)}}var $=s(i,u,j);return $>-1?P[B?i[$]:$]:void 0}}},37471:(s,i,u)=>{var _=u(91596),w=u(53320),x=u(58523),j=u(82819),P=u(18073),B=u(11287),$=u(68294),U=u(36306),Y=u(9325);s.exports=function createHybrid(s,i,u,X,Z,ee,ie,ae,le,ce){var pe=128&i,de=1&i,fe=2&i,ye=24&i,be=512&i,_e=fe?void 0:j(s);return function wrapper(){for(var we=arguments.length,Se=Array(we),xe=we;xe--;)Se[xe]=arguments[xe];if(ye)var Pe=B(wrapper),Te=x(Se,Pe);if(X&&(Se=_(Se,X,Z,ye)),ee&&(Se=w(Se,ee,ie,ye)),we-=Te,ye&&we1&&Se.reverse(),pe&&le{var _=u(91033),w=u(82819),x=u(9325);s.exports=function createPartial(s,i,u,j){var P=1&i,B=w(s);return function wrapper(){for(var i=-1,w=arguments.length,$=-1,U=j.length,Y=Array(U+w),X=this&&this!==x&&this instanceof wrapper?B:s;++${var _=u(85087),w=u(54641),x=u(70981);s.exports=function createRecurry(s,i,u,j,P,B,$,U,Y,X){var Z=8&i;i|=Z?32:64,4&(i&=~(Z?64:32))||(i&=-4);var ee=[s,i,P,Z?B:void 0,Z?$:void 0,Z?void 0:B,Z?void 0:$,U,Y,X],ie=u.apply(void 0,ee);return _(s)&&w(ie,ee),ie.placeholder=j,x(ie,s,i)}},66977:(s,i,u)=>{var _=u(68882),w=u(11842),x=u(77078),j=u(37471),P=u(24168),B=u(37381),$=u(3209),U=u(54641),Y=u(70981),X=u(61489),Z=Math.max;s.exports=function createWrap(s,i,u,ee,ie,ae,le,ce){var pe=2&i;if(!pe&&"function"!=typeof s)throw new TypeError("Expected a function");var de=ee?ee.length:0;if(de||(i&=-97,ee=ie=void 0),le=void 0===le?le:Z(X(le),0),ce=void 0===ce?ce:X(ce),de-=ie?ie.length:0,64&i){var fe=ee,ye=ie;ee=ie=void 0}var be=pe?void 0:B(s),_e=[s,i,u,ee,ie,fe,ye,ae,le,ce];if(be&&$(_e,be),s=_e[0],i=_e[1],u=_e[2],ee=_e[3],ie=_e[4],!(ce=_e[9]=void 0===_e[9]?pe?0:s.length:Z(_e[9]-de,0))&&24&i&&(i&=-25),i&&1!=i)we=8==i||16==i?x(s,i,ce):32!=i&&33!=i||ie.length?j.apply(void 0,_e):P(s,i,u,ee);else var we=w(s,i,u);return Y((be?_:U)(we,_e),s,i)}},53138:(s,i,u)=>{var _=u(11331);s.exports=function customOmitClone(s){return _(s)?void 0:s}},24647:(s,i,u)=>{var _=u(54552)({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"});s.exports=_},93243:(s,i,u)=>{var _=u(56110),w=function(){try{var s=_(Object,"defineProperty");return s({},"",{}),s}catch(s){}}();s.exports=w},25911:(s,i,u)=>{var _=u(38859),w=u(14248),x=u(19219);s.exports=function equalArrays(s,i,u,j,P,B){var $=1&u,U=s.length,Y=i.length;if(U!=Y&&!($&&Y>U))return!1;var X=B.get(s),Z=B.get(i);if(X&&Z)return X==i&&Z==s;var ee=-1,ie=!0,ae=2&u?new _:void 0;for(B.set(s,i),B.set(i,s);++ee{var _=u(51873),w=u(37828),x=u(75288),j=u(25911),P=u(20317),B=u(84247),$=_?_.prototype:void 0,U=$?$.valueOf:void 0;s.exports=function equalByTag(s,i,u,_,$,Y,X){switch(u){case"[object DataView]":if(s.byteLength!=i.byteLength||s.byteOffset!=i.byteOffset)return!1;s=s.buffer,i=i.buffer;case"[object ArrayBuffer]":return!(s.byteLength!=i.byteLength||!Y(new w(s),new w(i)));case"[object Boolean]":case"[object Date]":case"[object Number]":return x(+s,+i);case"[object Error]":return s.name==i.name&&s.message==i.message;case"[object RegExp]":case"[object String]":return s==i+"";case"[object Map]":var Z=P;case"[object Set]":var ee=1&_;if(Z||(Z=B),s.size!=i.size&&!ee)return!1;var ie=X.get(s);if(ie)return ie==i;_|=2,X.set(s,i);var ae=j(Z(s),Z(i),_,$,Y,X);return X.delete(s),ae;case"[object Symbol]":if(U)return U.call(s)==U.call(i)}return!1}},50689:(s,i,u)=>{var _=u(50002),w=Object.prototype.hasOwnProperty;s.exports=function equalObjects(s,i,u,x,j,P){var B=1&u,$=_(s),U=$.length;if(U!=_(i).length&&!B)return!1;for(var Y=U;Y--;){var X=$[Y];if(!(B?X in i:w.call(i,X)))return!1}var Z=P.get(s),ee=P.get(i);if(Z&&ee)return Z==i&&ee==s;var ie=!0;P.set(s,i),P.set(i,s);for(var ae=B;++Y{var _=u(35970),w=u(56757),x=u(32865);s.exports=function flatRest(s){return x(w(s,void 0,_),s+"")}},34840:(s,i,u)=>{var _="object"==typeof u.g&&u.g&&u.g.Object===Object&&u.g;s.exports=_},50002:(s,i,u)=>{var _=u(82199),w=u(4664),x=u(95950);s.exports=function getAllKeys(s){return _(s,x,w)}},83349:(s,i,u)=>{var _=u(82199),w=u(86375),x=u(37241);s.exports=function getAllKeysIn(s){return _(s,x,w)}},37381:(s,i,u)=>{var _=u(48152),w=u(63950),x=_?function(s){return _.get(s)}:w;s.exports=x},62284:(s,i,u)=>{var _=u(84629),w=Object.prototype.hasOwnProperty;s.exports=function getFuncName(s){for(var i=s.name+"",u=_[i],x=w.call(_,i)?u.length:0;x--;){var j=u[x],P=j.func;if(null==P||P==s)return j.name}return i}},11287:s=>{s.exports=function getHolder(s){return s.placeholder}},12651:(s,i,u)=>{var _=u(74218);s.exports=function getMapData(s,i){var u=s.__data__;return _(i)?u["string"==typeof i?"string":"hash"]:u.map}},10776:(s,i,u)=>{var _=u(30756),w=u(95950);s.exports=function getMatchData(s){for(var i=w(s),u=i.length;u--;){var x=i[u],j=s[x];i[u]=[x,j,_(j)]}return i}},56110:(s,i,u)=>{var _=u(45083),w=u(10392);s.exports=function getNative(s,i){var u=w(s,i);return _(u)?u:void 0}},28879:(s,i,u)=>{var _=u(74335)(Object.getPrototypeOf,Object);s.exports=_},659:(s,i,u)=>{var _=u(51873),w=Object.prototype,x=w.hasOwnProperty,j=w.toString,P=_?_.toStringTag:void 0;s.exports=function getRawTag(s){var i=x.call(s,P),u=s[P];try{s[P]=void 0;var _=!0}catch(s){}var w=j.call(s);return _&&(i?s[P]=u:delete s[P]),w}},4664:(s,i,u)=>{var _=u(79770),w=u(63345),x=Object.prototype.propertyIsEnumerable,j=Object.getOwnPropertySymbols,P=j?function(s){return null==s?[]:(s=Object(s),_(j(s),(function(i){return x.call(s,i)})))}:w;s.exports=P},86375:(s,i,u)=>{var _=u(14528),w=u(28879),x=u(4664),j=u(63345),P=Object.getOwnPropertySymbols?function(s){for(var i=[];s;)_(i,x(s)),s=w(s);return i}:j;s.exports=P},5861:(s,i,u)=>{var _=u(55580),w=u(68223),x=u(32804),j=u(76545),P=u(28303),B=u(72552),$=u(47473),U="[object Map]",Y="[object Promise]",X="[object Set]",Z="[object WeakMap]",ee="[object DataView]",ie=$(_),ae=$(w),le=$(x),ce=$(j),pe=$(P),de=B;(_&&de(new _(new ArrayBuffer(1)))!=ee||w&&de(new w)!=U||x&&de(x.resolve())!=Y||j&&de(new j)!=X||P&&de(new P)!=Z)&&(de=function(s){var i=B(s),u="[object Object]"==i?s.constructor:void 0,_=u?$(u):"";if(_)switch(_){case ie:return ee;case ae:return U;case le:return Y;case ce:return X;case pe:return Z}return i}),s.exports=de},10392:s=>{s.exports=function getValue(s,i){return null==s?void 0:s[i]}},75251:s=>{var i=/\{\n\/\* \[wrapped with (.+)\] \*/,u=/,? & /;s.exports=function getWrapDetails(s){var _=s.match(i);return _?_[1].split(u):[]}},49326:(s,i,u)=>{var _=u(31769),w=u(72428),x=u(56449),j=u(30361),P=u(30294),B=u(77797);s.exports=function hasPath(s,i,u){for(var $=-1,U=(i=_(i,s)).length,Y=!1;++${var i=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");s.exports=function hasUnicode(s){return i.test(s)}},45434:s=>{var i=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;s.exports=function hasUnicodeWord(s){return i.test(s)}},22032:(s,i,u)=>{var _=u(81042);s.exports=function hashClear(){this.__data__=_?_(null):{},this.size=0}},63862:s=>{s.exports=function hashDelete(s){var i=this.has(s)&&delete this.__data__[s];return this.size-=i?1:0,i}},66721:(s,i,u)=>{var _=u(81042),w=Object.prototype.hasOwnProperty;s.exports=function hashGet(s){var i=this.__data__;if(_){var u=i[s];return"__lodash_hash_undefined__"===u?void 0:u}return w.call(i,s)?i[s]:void 0}},12749:(s,i,u)=>{var _=u(81042),w=Object.prototype.hasOwnProperty;s.exports=function hashHas(s){var i=this.__data__;return _?void 0!==i[s]:w.call(i,s)}},35749:(s,i,u)=>{var _=u(81042);s.exports=function hashSet(s,i){var u=this.__data__;return this.size+=this.has(s)?0:1,u[s]=_&&void 0===i?"__lodash_hash_undefined__":i,this}},76189:s=>{var i=Object.prototype.hasOwnProperty;s.exports=function initCloneArray(s){var u=s.length,_=new s.constructor(u);return u&&"string"==typeof s[0]&&i.call(s,"index")&&(_.index=s.index,_.input=s.input),_}},77199:(s,i,u)=>{var _=u(49653),w=u(76169),x=u(73201),j=u(93736),P=u(71961);s.exports=function initCloneByTag(s,i,u){var B=s.constructor;switch(i){case"[object ArrayBuffer]":return _(s);case"[object Boolean]":case"[object Date]":return new B(+s);case"[object DataView]":return w(s,u);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return P(s,u);case"[object Map]":case"[object Set]":return new B;case"[object Number]":case"[object String]":return new B(s);case"[object RegExp]":return x(s);case"[object Symbol]":return j(s)}}},35529:(s,i,u)=>{var _=u(39344),w=u(28879),x=u(55527);s.exports=function initCloneObject(s){return"function"!=typeof s.constructor||x(s)?{}:_(w(s))}},62060:s=>{var i=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;s.exports=function insertWrapDetails(s,u){var _=u.length;if(!_)return s;var w=_-1;return u[w]=(_>1?"& ":"")+u[w],u=u.join(_>2?", ":" "),s.replace(i,"{\n/* [wrapped with "+u+"] */\n")}},45891:(s,i,u)=>{var _=u(51873),w=u(72428),x=u(56449),j=_?_.isConcatSpreadable:void 0;s.exports=function isFlattenable(s){return x(s)||w(s)||!!(j&&s&&s[j])}},30361:s=>{var i=/^(?:0|[1-9]\d*)$/;s.exports=function isIndex(s,u){var _=typeof s;return!!(u=null==u?9007199254740991:u)&&("number"==_||"symbol"!=_&&i.test(s))&&s>-1&&s%1==0&&s{var _=u(75288),w=u(64894),x=u(30361),j=u(23805);s.exports=function isIterateeCall(s,i,u){if(!j(u))return!1;var P=typeof i;return!!("number"==P?w(u)&&x(i,u.length):"string"==P&&i in u)&&_(u[i],s)}},28586:(s,i,u)=>{var _=u(56449),w=u(44394),x=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,j=/^\w*$/;s.exports=function isKey(s,i){if(_(s))return!1;var u=typeof s;return!("number"!=u&&"symbol"!=u&&"boolean"!=u&&null!=s&&!w(s))||(j.test(s)||!x.test(s)||null!=i&&s in Object(i))}},74218:s=>{s.exports=function isKeyable(s){var i=typeof s;return"string"==i||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==s:null===s}},85087:(s,i,u)=>{var _=u(30980),w=u(37381),x=u(62284),j=u(53758);s.exports=function isLaziable(s){var i=x(s),u=j[i];if("function"!=typeof u||!(i in _.prototype))return!1;if(s===u)return!0;var P=w(u);return!!P&&s===P[0]}},87296:(s,i,u)=>{var _,w=u(55481),x=(_=/[^.]+$/.exec(w&&w.keys&&w.keys.IE_PROTO||""))?"Symbol(src)_1."+_:"";s.exports=function isMasked(s){return!!x&&x in s}},55527:s=>{var i=Object.prototype;s.exports=function isPrototype(s){var u=s&&s.constructor;return s===("function"==typeof u&&u.prototype||i)}},30756:(s,i,u)=>{var _=u(23805);s.exports=function isStrictComparable(s){return s==s&&!_(s)}},63702:s=>{s.exports=function listCacheClear(){this.__data__=[],this.size=0}},70080:(s,i,u)=>{var _=u(26025),w=Array.prototype.splice;s.exports=function listCacheDelete(s){var i=this.__data__,u=_(i,s);return!(u<0)&&(u==i.length-1?i.pop():w.call(i,u,1),--this.size,!0)}},24739:(s,i,u)=>{var _=u(26025);s.exports=function listCacheGet(s){var i=this.__data__,u=_(i,s);return u<0?void 0:i[u][1]}},48655:(s,i,u)=>{var _=u(26025);s.exports=function listCacheHas(s){return _(this.__data__,s)>-1}},31175:(s,i,u)=>{var _=u(26025);s.exports=function listCacheSet(s,i){var u=this.__data__,w=_(u,s);return w<0?(++this.size,u.push([s,i])):u[w][1]=i,this}},63040:(s,i,u)=>{var _=u(21549),w=u(80079),x=u(68223);s.exports=function mapCacheClear(){this.size=0,this.__data__={hash:new _,map:new(x||w),string:new _}}},17670:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheDelete(s){var i=_(this,s).delete(s);return this.size-=i?1:0,i}},90289:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheGet(s){return _(this,s).get(s)}},4509:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheHas(s){return _(this,s).has(s)}},72949:(s,i,u)=>{var _=u(12651);s.exports=function mapCacheSet(s,i){var u=_(this,s),w=u.size;return u.set(s,i),this.size+=u.size==w?0:1,this}},20317:s=>{s.exports=function mapToArray(s){var i=-1,u=Array(s.size);return s.forEach((function(s,_){u[++i]=[_,s]})),u}},67197:s=>{s.exports=function matchesStrictComparable(s,i){return function(u){return null!=u&&(u[s]===i&&(void 0!==i||s in Object(u)))}}},62224:(s,i,u)=>{var _=u(50104);s.exports=function memoizeCapped(s){var i=_(s,(function(s){return 500===u.size&&u.clear(),s})),u=i.cache;return i}},3209:(s,i,u)=>{var _=u(91596),w=u(53320),x=u(36306),j="__lodash_placeholder__",P=128,B=Math.min;s.exports=function mergeData(s,i){var u=s[1],$=i[1],U=u|$,Y=U<131,X=$==P&&8==u||$==P&&256==u&&s[7].length<=i[8]||384==$&&i[7].length<=i[8]&&8==u;if(!Y&&!X)return s;1&$&&(s[2]=i[2],U|=1&u?0:4);var Z=i[3];if(Z){var ee=s[3];s[3]=ee?_(ee,Z,i[4]):Z,s[4]=ee?x(s[3],j):i[4]}return(Z=i[5])&&(ee=s[5],s[5]=ee?w(ee,Z,i[6]):Z,s[6]=ee?x(s[5],j):i[6]),(Z=i[7])&&(s[7]=Z),$&P&&(s[8]=null==s[8]?i[8]:B(s[8],i[8])),null==s[9]&&(s[9]=i[9]),s[0]=i[0],s[1]=U,s}},48152:(s,i,u)=>{var _=u(28303),w=_&&new _;s.exports=w},81042:(s,i,u)=>{var _=u(56110)(Object,"create");s.exports=_},3650:(s,i,u)=>{var _=u(74335)(Object.keys,Object);s.exports=_},90181:s=>{s.exports=function nativeKeysIn(s){var i=[];if(null!=s)for(var u in Object(s))i.push(u);return i}},86009:(s,i,u)=>{s=u.nmd(s);var _=u(34840),w=i&&!i.nodeType&&i,x=w&&s&&!s.nodeType&&s,j=x&&x.exports===w&&_.process,P=function(){try{var s=x&&x.require&&x.require("util").types;return s||j&&j.binding&&j.binding("util")}catch(s){}}();s.exports=P},59350:s=>{var i=Object.prototype.toString;s.exports=function objectToString(s){return i.call(s)}},74335:s=>{s.exports=function overArg(s,i){return function(u){return s(i(u))}}},56757:(s,i,u)=>{var _=u(91033),w=Math.max;s.exports=function overRest(s,i,u){return i=w(void 0===i?s.length-1:i,0),function(){for(var x=arguments,j=-1,P=w(x.length-i,0),B=Array(P);++j{var _=u(47422),w=u(25160);s.exports=function parent(s,i){return i.length<2?s:_(s,w(i,0,-1))}},84629:s=>{s.exports={}},68294:(s,i,u)=>{var _=u(23007),w=u(30361),x=Math.min;s.exports=function reorder(s,i){for(var u=s.length,j=x(i.length,u),P=_(s);j--;){var B=i[j];s[j]=w(B,u)?P[B]:void 0}return s}},36306:s=>{var i="__lodash_placeholder__";s.exports=function replaceHolders(s,u){for(var _=-1,w=s.length,x=0,j=[];++_{var _=u(34840),w="object"==typeof self&&self&&self.Object===Object&&self,x=_||w||Function("return this")();s.exports=x},14974:s=>{s.exports=function safeGet(s,i){if(("constructor"!==i||"function"!=typeof s[i])&&"__proto__"!=i)return s[i]}},31380:s=>{s.exports=function setCacheAdd(s){return this.__data__.set(s,"__lodash_hash_undefined__"),this}},51459:s=>{s.exports=function setCacheHas(s){return this.__data__.has(s)}},54641:(s,i,u)=>{var _=u(68882),w=u(51811)(_);s.exports=w},84247:s=>{s.exports=function setToArray(s){var i=-1,u=Array(s.size);return s.forEach((function(s){u[++i]=s})),u}},32865:(s,i,u)=>{var _=u(19570),w=u(51811)(_);s.exports=w},70981:(s,i,u)=>{var _=u(75251),w=u(62060),x=u(32865),j=u(75948);s.exports=function setWrapToString(s,i,u){var P=i+"";return x(s,w(P,j(_(P),u)))}},51811:s=>{var i=Date.now;s.exports=function shortOut(s){var u=0,_=0;return function(){var w=i(),x=16-(w-_);if(_=w,x>0){if(++u>=800)return arguments[0]}else u=0;return s.apply(void 0,arguments)}}},51420:(s,i,u)=>{var _=u(80079);s.exports=function stackClear(){this.__data__=new _,this.size=0}},90938:s=>{s.exports=function stackDelete(s){var i=this.__data__,u=i.delete(s);return this.size=i.size,u}},63605:s=>{s.exports=function stackGet(s){return this.__data__.get(s)}},29817:s=>{s.exports=function stackHas(s){return this.__data__.has(s)}},80945:(s,i,u)=>{var _=u(80079),w=u(68223),x=u(53661);s.exports=function stackSet(s,i){var u=this.__data__;if(u instanceof _){var j=u.__data__;if(!w||j.length<199)return j.push([s,i]),this.size=++u.size,this;u=this.__data__=new x(j)}return u.set(s,i),this.size=u.size,this}},76959:s=>{s.exports=function strictIndexOf(s,i,u){for(var _=u-1,w=s.length;++_{var _=u(61074),w=u(49698),x=u(42054);s.exports=function stringToArray(s){return w(s)?x(s):_(s)}},61802:(s,i,u)=>{var _=u(62224),w=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,x=/\\(\\)?/g,j=_((function(s){var i=[];return 46===s.charCodeAt(0)&&i.push(""),s.replace(w,(function(s,u,_,w){i.push(_?w.replace(x,"$1"):u||s)})),i}));s.exports=j},77797:(s,i,u)=>{var _=u(44394);s.exports=function toKey(s){if("string"==typeof s||_(s))return s;var i=s+"";return"0"==i&&1/s==-Infinity?"-0":i}},47473:s=>{var i=Function.prototype.toString;s.exports=function toSource(s){if(null!=s){try{return i.call(s)}catch(s){}try{return s+""}catch(s){}}return""}},31800:s=>{var i=/\s/;s.exports=function trimmedEndIndex(s){for(var u=s.length;u--&&i.test(s.charAt(u)););return u}},42054:s=>{var i="\\ud800-\\udfff",u="["+i+"]",_="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",w="\\ud83c[\\udffb-\\udfff]",x="[^"+i+"]",j="(?:\\ud83c[\\udde6-\\uddff]){2}",P="[\\ud800-\\udbff][\\udc00-\\udfff]",B="(?:"+_+"|"+w+")"+"?",$="[\\ufe0e\\ufe0f]?",U=$+B+("(?:\\u200d(?:"+[x,j,P].join("|")+")"+$+B+")*"),Y="(?:"+[x+_+"?",_,j,P,u].join("|")+")",X=RegExp(w+"(?="+w+")|"+Y+U,"g");s.exports=function unicodeToArray(s){return s.match(X)||[]}},22225:s=>{var i="\\ud800-\\udfff",u="\\u2700-\\u27bf",_="a-z\\xdf-\\xf6\\xf8-\\xff",w="A-Z\\xc0-\\xd6\\xd8-\\xde",x="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",j="["+x+"]",P="\\d+",B="["+u+"]",$="["+_+"]",U="[^"+i+x+P+u+_+w+"]",Y="(?:\\ud83c[\\udde6-\\uddff]){2}",X="[\\ud800-\\udbff][\\udc00-\\udfff]",Z="["+w+"]",ee="(?:"+$+"|"+U+")",ie="(?:"+Z+"|"+U+")",ae="(?:['’](?:d|ll|m|re|s|t|ve))?",le="(?:['’](?:D|LL|M|RE|S|T|VE))?",ce="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",pe="[\\ufe0e\\ufe0f]?",de=pe+ce+("(?:\\u200d(?:"+["[^"+i+"]",Y,X].join("|")+")"+pe+ce+")*"),fe="(?:"+[B,Y,X].join("|")+")"+de,ye=RegExp([Z+"?"+$+"+"+ae+"(?="+[j,Z,"$"].join("|")+")",ie+"+"+le+"(?="+[j,Z+ee,"$"].join("|")+")",Z+"?"+ee+"+"+ae,Z+"+"+le,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",P,fe].join("|"),"g");s.exports=function unicodeWords(s){return s.match(ye)||[]}},75948:(s,i,u)=>{var _=u(83729),w=u(15325),x=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]];s.exports=function updateWrapDetails(s,i){return _(x,(function(u){var _="_."+u[0];i&u[1]&&!w(s,_)&&s.push(_)})),s.sort()}},80257:(s,i,u)=>{var _=u(30980),w=u(56017),x=u(23007);s.exports=function wrapperClone(s){if(s instanceof _)return s.clone();var i=new w(s.__wrapped__,s.__chain__);return i.__actions__=x(s.__actions__),i.__index__=s.__index__,i.__values__=s.__values__,i}},64626:(s,i,u)=>{var _=u(66977);s.exports=function ary(s,i,u){return i=u?void 0:i,i=s&&null==i?s.length:i,_(s,128,void 0,void 0,void 0,void 0,i)}},84058:(s,i,u)=>{var _=u(14792),w=u(45539)((function(s,i,u){return i=i.toLowerCase(),s+(u?_(i):i)}));s.exports=w},14792:(s,i,u)=>{var _=u(13222),w=u(55808);s.exports=function capitalize(s){return w(_(s).toLowerCase())}},32629:(s,i,u)=>{var _=u(9999);s.exports=function clone(s){return _(s,4)}},37334:s=>{s.exports=function constant(s){return function(){return s}}},49747:(s,i,u)=>{var _=u(66977);function curry(s,i,u){var w=_(s,8,void 0,void 0,void 0,void 0,void 0,i=u?void 0:i);return w.placeholder=curry.placeholder,w}curry.placeholder={},s.exports=curry},38221:(s,i,u)=>{var _=u(23805),w=u(10124),x=u(99374),j=Math.max,P=Math.min;s.exports=function debounce(s,i,u){var B,$,U,Y,X,Z,ee=0,ie=!1,ae=!1,le=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function invokeFunc(i){var u=B,_=$;return B=$=void 0,ee=i,Y=s.apply(_,u)}function shouldInvoke(s){var u=s-Z;return void 0===Z||u>=i||u<0||ae&&s-ee>=U}function timerExpired(){var s=w();if(shouldInvoke(s))return trailingEdge(s);X=setTimeout(timerExpired,function remainingWait(s){var u=i-(s-Z);return ae?P(u,U-(s-ee)):u}(s))}function trailingEdge(s){return X=void 0,le&&B?invokeFunc(s):(B=$=void 0,Y)}function debounced(){var s=w(),u=shouldInvoke(s);if(B=arguments,$=this,Z=s,u){if(void 0===X)return function leadingEdge(s){return ee=s,X=setTimeout(timerExpired,i),ie?invokeFunc(s):Y}(Z);if(ae)return clearTimeout(X),X=setTimeout(timerExpired,i),invokeFunc(Z)}return void 0===X&&(X=setTimeout(timerExpired,i)),Y}return i=x(i)||0,_(u)&&(ie=!!u.leading,U=(ae="maxWait"in u)?j(x(u.maxWait)||0,i):U,le="trailing"in u?!!u.trailing:le),debounced.cancel=function cancel(){void 0!==X&&clearTimeout(X),ee=0,B=Z=$=X=void 0},debounced.flush=function flush(){return void 0===X?Y:trailingEdge(w())},debounced}},50828:(s,i,u)=>{var _=u(24647),w=u(13222),x=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,j=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");s.exports=function deburr(s){return(s=w(s))&&s.replace(x,_).replace(j,"")}},75288:s=>{s.exports=function eq(s,i){return s===i||s!=s&&i!=i}},60680:(s,i,u)=>{var _=u(13222),w=/[\\^$.*+?()[\]{}|]/g,x=RegExp(w.source);s.exports=function escapeRegExp(s){return(s=_(s))&&x.test(s)?s.replace(w,"\\$&"):s}},7309:(s,i,u)=>{var _=u(62006)(u(24713));s.exports=_},24713:(s,i,u)=>{var _=u(2523),w=u(15389),x=u(61489),j=Math.max;s.exports=function findIndex(s,i,u){var P=null==s?0:s.length;if(!P)return-1;var B=null==u?0:x(u);return B<0&&(B=j(P+B,0)),_(s,w(i,3),B)}},35970:(s,i,u)=>{var _=u(83120);s.exports=function flatten(s){return(null==s?0:s.length)?_(s,1):[]}},73424:(s,i,u)=>{var _=u(16962),w=u(2874),x=Array.prototype.push;function baseAry(s,i){return 2==i?function(i,u){return s(i,u)}:function(i){return s(i)}}function cloneArray(s){for(var i=s?s.length:0,u=Array(i);i--;)u[i]=s[i];return u}function wrapImmutable(s,i){return function(){var u=arguments.length;if(u){for(var _=Array(u);u--;)_[u]=arguments[u];var w=_[0]=i.apply(void 0,_);return s.apply(void 0,_),w}}}s.exports=function baseConvert(s,i,u,j){var P="function"==typeof i,B=i===Object(i);if(B&&(j=u,u=i,i=void 0),null==u)throw new TypeError;j||(j={});var $={cap:!("cap"in j)||j.cap,curry:!("curry"in j)||j.curry,fixed:!("fixed"in j)||j.fixed,immutable:!("immutable"in j)||j.immutable,rearg:!("rearg"in j)||j.rearg},U=P?u:w,Y="curry"in j&&j.curry,X="fixed"in j&&j.fixed,Z="rearg"in j&&j.rearg,ee=P?u.runInContext():void 0,ie=P?u:{ary:s.ary,assign:s.assign,clone:s.clone,curry:s.curry,forEach:s.forEach,isArray:s.isArray,isError:s.isError,isFunction:s.isFunction,isWeakMap:s.isWeakMap,iteratee:s.iteratee,keys:s.keys,rearg:s.rearg,toInteger:s.toInteger,toPath:s.toPath},ae=ie.ary,le=ie.assign,ce=ie.clone,pe=ie.curry,de=ie.forEach,fe=ie.isArray,ye=ie.isError,be=ie.isFunction,_e=ie.isWeakMap,we=ie.keys,Se=ie.rearg,xe=ie.toInteger,Pe=ie.toPath,Te=we(_.aryMethod),Re={castArray:function(s){return function(){var i=arguments[0];return fe(i)?s(cloneArray(i)):s.apply(void 0,arguments)}},iteratee:function(s){return function(){var i=arguments[1],u=s(arguments[0],i),_=u.length;return $.cap&&"number"==typeof i?(i=i>2?i-2:1,_&&_<=i?u:baseAry(u,i)):u}},mixin:function(s){return function(i){var u=this;if(!be(u))return s(u,Object(i));var _=[];return de(we(i),(function(s){be(i[s])&&_.push([s,u.prototype[s]])})),s(u,Object(i)),de(_,(function(s){var i=s[1];be(i)?u.prototype[s[0]]=i:delete u.prototype[s[0]]})),u}},nthArg:function(s){return function(i){var u=i<0?1:xe(i)+1;return pe(s(i),u)}},rearg:function(s){return function(i,u){var _=u?u.length:0;return pe(s(i,u),_)}},runInContext:function(i){return function(u){return baseConvert(s,i(u),j)}}};function castCap(s,i){if($.cap){var u=_.iterateeRearg[s];if(u)return function iterateeRearg(s,i){return overArg(s,(function(s){var u=i.length;return function baseArity(s,i){return 2==i?function(i,u){return s.apply(void 0,arguments)}:function(i){return s.apply(void 0,arguments)}}(Se(baseAry(s,u),i),u)}))}(i,u);var w=!P&&_.iterateeAry[s];if(w)return function iterateeAry(s,i){return overArg(s,(function(s){return"function"==typeof s?baseAry(s,i):s}))}(i,w)}return i}function castFixed(s,i,u){if($.fixed&&(X||!_.skipFixed[s])){var w=_.methodSpread[s],j=w&&w.start;return void 0===j?ae(i,u):function flatSpread(s,i){return function(){for(var u=arguments.length,_=u-1,w=Array(u);u--;)w[u]=arguments[u];var j=w[i],P=w.slice(0,i);return j&&x.apply(P,j),i!=_&&x.apply(P,w.slice(i+1)),s.apply(this,P)}}(i,j)}return i}function castRearg(s,i,u){return $.rearg&&u>1&&(Z||!_.skipRearg[s])?Se(i,_.methodRearg[s]||_.aryRearg[u]):i}function cloneByPath(s,i){for(var u=-1,_=(i=Pe(i)).length,w=_-1,x=ce(Object(s)),j=x;null!=j&&++u<_;){var P=i[u],B=j[P];null==B||be(B)||ye(B)||_e(B)||(j[P]=ce(u==w?B:Object(B))),j=j[P]}return x}function createConverter(s,i){var u=_.aliasToReal[s]||s,w=_.remap[u]||u,x=j;return function(s){var _=P?ee:ie,j=P?ee[w]:i,B=le(le({},x),s);return baseConvert(_,u,j,B)}}function overArg(s,i){return function(){var u=arguments.length;if(!u)return s();for(var _=Array(u);u--;)_[u]=arguments[u];var w=$.rearg?0:u-1;return _[w]=i(_[w]),s.apply(void 0,_)}}function wrap(s,i,u){var w,x=_.aliasToReal[s]||s,j=i,P=Re[x];return P?j=P(i):$.immutable&&(_.mutate.array[x]?j=wrapImmutable(i,cloneArray):_.mutate.object[x]?j=wrapImmutable(i,function createCloner(s){return function(i){return s({},i)}}(i)):_.mutate.set[x]&&(j=wrapImmutable(i,cloneByPath))),de(Te,(function(s){return de(_.aryMethod[s],(function(i){if(x==i){var u=_.methodSpread[x],P=u&&u.afterRearg;return w=P?castFixed(x,castRearg(x,j,s),s):castRearg(x,castFixed(x,j,s),s),w=function castCurry(s,i,u){return Y||$.curry&&u>1?pe(i,u):i}(0,w=castCap(x,w),s),!1}})),!w})),w||(w=j),w==i&&(w=Y?pe(w,1):function(){return i.apply(this,arguments)}),w.convert=createConverter(x,i),w.placeholder=i.placeholder=u,w}if(!B)return wrap(i,u,U);var qe=u,$e=[];return de(Te,(function(s){de(_.aryMethod[s],(function(s){var i=qe[_.remap[s]||s];i&&$e.push([s,wrap(s,i,qe)])}))})),de(we(qe),(function(s){var i=qe[s];if("function"==typeof i){for(var u=$e.length;u--;)if($e[u][0]==s)return;i.convert=createConverter(s,i),$e.push([s,i])}})),de($e,(function(s){qe[s[0]]=s[1]})),qe.convert=function convertLib(s){return qe.runInContext.convert(s)(void 0)},qe.placeholder=qe,de(we(qe),(function(s){de(_.realToAlias[s]||[],(function(i){qe[i]=qe[s]}))})),qe}},16962:(s,i)=>{i.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},i.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},i.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},i.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},i.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},i.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},i.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},i.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},i.realToAlias=function(){var s=Object.prototype.hasOwnProperty,u=i.aliasToReal,_={};for(var w in u){var x=u[w];s.call(_,x)?_[x].push(w):_[x]=[w]}return _}(),i.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},i.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},i.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},47934:(s,i,u)=>{s.exports={ary:u(64626),assign:u(74733),clone:u(32629),curry:u(49747),forEach:u(83729),isArray:u(56449),isError:u(23546),isFunction:u(1882),isWeakMap:u(47886),iteratee:u(33855),keys:u(88984),rearg:u(84195),toInteger:u(61489),toPath:u(42072)}},56367:(s,i,u)=>{s.exports=u(77731)},79920:(s,i,u)=>{var _=u(73424),w=u(47934);s.exports=function convert(s,i,u){return _(w,s,i,u)}},2874:s=>{s.exports={}},77731:(s,i,u)=>{var _=u(79920)("set",u(63560));_.placeholder=u(2874),s.exports=_},58156:(s,i,u)=>{var _=u(47422);s.exports=function get(s,i,u){var w=null==s?void 0:_(s,i);return void 0===w?u:w}},80631:(s,i,u)=>{var _=u(28077),w=u(49326);s.exports=function hasIn(s,i){return null!=s&&w(s,i,_)}},83488:s=>{s.exports=function identity(s){return s}},72428:(s,i,u)=>{var _=u(27534),w=u(40346),x=Object.prototype,j=x.hasOwnProperty,P=x.propertyIsEnumerable,B=_(function(){return arguments}())?_:function(s){return w(s)&&j.call(s,"callee")&&!P.call(s,"callee")};s.exports=B},56449:s=>{var i=Array.isArray;s.exports=i},64894:(s,i,u)=>{var _=u(1882),w=u(30294);s.exports=function isArrayLike(s){return null!=s&&w(s.length)&&!_(s)}},83693:(s,i,u)=>{var _=u(64894),w=u(40346);s.exports=function isArrayLikeObject(s){return w(s)&&_(s)}},53812:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function isBoolean(s){return!0===s||!1===s||w(s)&&"[object Boolean]"==_(s)}},3656:(s,i,u)=>{s=u.nmd(s);var _=u(9325),w=u(89935),x=i&&!i.nodeType&&i,j=x&&s&&!s.nodeType&&s,P=j&&j.exports===x?_.Buffer:void 0,B=(P?P.isBuffer:void 0)||w;s.exports=B},62193:(s,i,u)=>{var _=u(88984),w=u(5861),x=u(72428),j=u(56449),P=u(64894),B=u(3656),$=u(55527),U=u(37167),Y=Object.prototype.hasOwnProperty;s.exports=function isEmpty(s){if(null==s)return!0;if(P(s)&&(j(s)||"string"==typeof s||"function"==typeof s.splice||B(s)||U(s)||x(s)))return!s.length;var i=w(s);if("[object Map]"==i||"[object Set]"==i)return!s.size;if($(s))return!_(s).length;for(var u in s)if(Y.call(s,u))return!1;return!0}},2404:(s,i,u)=>{var _=u(60270);s.exports=function isEqual(s,i){return _(s,i)}},23546:(s,i,u)=>{var _=u(72552),w=u(40346),x=u(11331);s.exports=function isError(s){if(!w(s))return!1;var i=_(s);return"[object Error]"==i||"[object DOMException]"==i||"string"==typeof s.message&&"string"==typeof s.name&&!x(s)}},1882:(s,i,u)=>{var _=u(72552),w=u(23805);s.exports=function isFunction(s){if(!w(s))return!1;var i=_(s);return"[object Function]"==i||"[object GeneratorFunction]"==i||"[object AsyncFunction]"==i||"[object Proxy]"==i}},30294:s=>{s.exports=function isLength(s){return"number"==typeof s&&s>-1&&s%1==0&&s<=9007199254740991}},87730:(s,i,u)=>{var _=u(29172),w=u(27301),x=u(86009),j=x&&x.isMap,P=j?w(j):_;s.exports=P},5187:s=>{s.exports=function isNull(s){return null===s}},98023:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function isNumber(s){return"number"==typeof s||w(s)&&"[object Number]"==_(s)}},23805:s=>{s.exports=function isObject(s){var i=typeof s;return null!=s&&("object"==i||"function"==i)}},40346:s=>{s.exports=function isObjectLike(s){return null!=s&&"object"==typeof s}},11331:(s,i,u)=>{var _=u(72552),w=u(28879),x=u(40346),j=Function.prototype,P=Object.prototype,B=j.toString,$=P.hasOwnProperty,U=B.call(Object);s.exports=function isPlainObject(s){if(!x(s)||"[object Object]"!=_(s))return!1;var i=w(s);if(null===i)return!0;var u=$.call(i,"constructor")&&i.constructor;return"function"==typeof u&&u instanceof u&&B.call(u)==U}},38440:(s,i,u)=>{var _=u(16038),w=u(27301),x=u(86009),j=x&&x.isSet,P=j?w(j):_;s.exports=P},85015:(s,i,u)=>{var _=u(72552),w=u(56449),x=u(40346);s.exports=function isString(s){return"string"==typeof s||!w(s)&&x(s)&&"[object String]"==_(s)}},44394:(s,i,u)=>{var _=u(72552),w=u(40346);s.exports=function isSymbol(s){return"symbol"==typeof s||w(s)&&"[object Symbol]"==_(s)}},37167:(s,i,u)=>{var _=u(4901),w=u(27301),x=u(86009),j=x&&x.isTypedArray,P=j?w(j):_;s.exports=P},47886:(s,i,u)=>{var _=u(5861),w=u(40346);s.exports=function isWeakMap(s){return w(s)&&"[object WeakMap]"==_(s)}},33855:(s,i,u)=>{var _=u(9999),w=u(15389);s.exports=function iteratee(s){return w("function"==typeof s?s:_(s,1))}},95950:(s,i,u)=>{var _=u(70695),w=u(88984),x=u(64894);s.exports=function keys(s){return x(s)?_(s):w(s)}},37241:(s,i,u)=>{var _=u(70695),w=u(72903),x=u(64894);s.exports=function keysIn(s){return x(s)?_(s,!0):w(s)}},68090:s=>{s.exports=function last(s){var i=null==s?0:s.length;return i?s[i-1]:void 0}},50104:(s,i,u)=>{var _=u(53661);function memoize(s,i){if("function"!=typeof s||null!=i&&"function"!=typeof i)throw new TypeError("Expected a function");var memoized=function(){var u=arguments,_=i?i.apply(this,u):u[0],w=memoized.cache;if(w.has(_))return w.get(_);var x=s.apply(this,u);return memoized.cache=w.set(_,x)||w,x};return memoized.cache=new(memoize.Cache||_),memoized}memoize.Cache=_,s.exports=memoize},55364:(s,i,u)=>{var _=u(85250),w=u(20999)((function(s,i,u){_(s,i,u)}));s.exports=w},6048:s=>{s.exports=function negate(s){if("function"!=typeof s)throw new TypeError("Expected a function");return function(){var i=arguments;switch(i.length){case 0:return!s.call(this);case 1:return!s.call(this,i[0]);case 2:return!s.call(this,i[0],i[1]);case 3:return!s.call(this,i[0],i[1],i[2])}return!s.apply(this,i)}}},63950:s=>{s.exports=function noop(){}},10124:(s,i,u)=>{var _=u(9325);s.exports=function(){return _.Date.now()}},90179:(s,i,u)=>{var _=u(34932),w=u(9999),x=u(19931),j=u(31769),P=u(21791),B=u(53138),$=u(38816),U=u(83349),Y=$((function(s,i){var u={};if(null==s)return u;var $=!1;i=_(i,(function(i){return i=j(i,s),$||($=i.length>1),i})),P(s,U(s),u),$&&(u=w(u,7,B));for(var Y=i.length;Y--;)x(u,i[Y]);return u}));s.exports=Y},50583:(s,i,u)=>{var _=u(47237),w=u(17255),x=u(28586),j=u(77797);s.exports=function property(s){return x(s)?_(j(s)):w(s)}},84195:(s,i,u)=>{var _=u(66977),w=u(38816),x=w((function(s,i){return _(s,256,void 0,void 0,void 0,i)}));s.exports=x},40860:(s,i,u)=>{var _=u(40882),w=u(80909),x=u(15389),j=u(85558),P=u(56449);s.exports=function reduce(s,i,u){var B=P(s)?_:j,$=arguments.length<3;return B(s,x(i,4),u,$,w)}},63560:(s,i,u)=>{var _=u(73170);s.exports=function set(s,i,u){return null==s?s:_(s,i,u)}},42426:(s,i,u)=>{var _=u(14248),w=u(15389),x=u(90916),j=u(56449),P=u(36800);s.exports=function some(s,i,u){var B=j(s)?_:x;return u&&P(s,i,u)&&(i=void 0),B(s,w(i,3))}},63345:s=>{s.exports=function stubArray(){return[]}},89935:s=>{s.exports=function stubFalse(){return!1}},17400:(s,i,u)=>{var _=u(99374),w=1/0;s.exports=function toFinite(s){return s?(s=_(s))===w||s===-1/0?17976931348623157e292*(s<0?-1:1):s==s?s:0:0===s?s:0}},61489:(s,i,u)=>{var _=u(17400);s.exports=function toInteger(s){var i=_(s),u=i%1;return i==i?u?i-u:i:0}},80218:(s,i,u)=>{var _=u(13222);s.exports=function toLower(s){return _(s).toLowerCase()}},99374:(s,i,u)=>{var _=u(54128),w=u(23805),x=u(44394),j=/^[-+]0x[0-9a-f]+$/i,P=/^0b[01]+$/i,B=/^0o[0-7]+$/i,$=parseInt;s.exports=function toNumber(s){if("number"==typeof s)return s;if(x(s))return NaN;if(w(s)){var i="function"==typeof s.valueOf?s.valueOf():s;s=w(i)?i+"":i}if("string"!=typeof s)return 0===s?s:+s;s=_(s);var u=P.test(s);return u||B.test(s)?$(s.slice(2),u?2:8):j.test(s)?NaN:+s}},42072:(s,i,u)=>{var _=u(34932),w=u(23007),x=u(56449),j=u(44394),P=u(61802),B=u(77797),$=u(13222);s.exports=function toPath(s){return x(s)?_(s,B):j(s)?[s]:w(P($(s)))}},69884:(s,i,u)=>{var _=u(21791),w=u(37241);s.exports=function toPlainObject(s){return _(s,w(s))}},13222:(s,i,u)=>{var _=u(77556);s.exports=function toString(s){return null==s?"":_(s)}},55808:(s,i,u)=>{var _=u(12507)("toUpperCase");s.exports=_},66645:(s,i,u)=>{var _=u(1733),w=u(45434),x=u(13222),j=u(22225);s.exports=function words(s,i,u){return s=x(s),void 0===(i=u?void 0:i)?w(s)?j(s):_(s):s.match(i)||[]}},53758:(s,i,u)=>{var _=u(30980),w=u(56017),x=u(94033),j=u(56449),P=u(40346),B=u(80257),$=Object.prototype.hasOwnProperty;function lodash(s){if(P(s)&&!j(s)&&!(s instanceof _)){if(s instanceof w)return s;if($.call(s,"__wrapped__"))return B(s)}return new w(s)}lodash.prototype=x.prototype,lodash.prototype.constructor=lodash,s.exports=lodash},47248:(s,i,u)=>{var _=u(16547),w=u(51234);s.exports=function zipObject(s,i){return w(s||[],i||[],_)}},43768:(s,i,u)=>{"use strict";var _=u(45981),w=u(85587);i.highlight=highlight,i.highlightAuto=function highlightAuto(s,i){var u,j,P,B,$=i||{},U=$.subset||_.listLanguages(),Y=$.prefix,X=U.length,Z=-1;null==Y&&(Y=x);if("string"!=typeof s)throw w("Expected `string` for value, got `%s`",s);j={relevance:0,language:null,value:[]},u={relevance:0,language:null,value:[]};for(;++Zj.relevance&&(j=P),P.relevance>u.relevance&&(j=u,u=P));j.language&&(u.secondBest=j);return u},i.registerLanguage=function registerLanguage(s,i){_.registerLanguage(s,i)},i.listLanguages=function listLanguages(){return _.listLanguages()},i.registerAlias=function registerAlias(s,i){var u,w=s;i&&((w={})[s]=i);for(u in w)_.registerAliases(w[u],{languageName:u})},Emitter.prototype.addText=function text(s){var i,u,_=this.stack;if(""===s)return;i=_[_.length-1],(u=i.children[i.children.length-1])&&"text"===u.type?u.value+=s:i.children.push({type:"text",value:s})},Emitter.prototype.addKeyword=function addKeyword(s,i){this.openNode(i),this.addText(s),this.closeNode()},Emitter.prototype.addSublanguage=function addSublanguage(s,i){var u=this.stack,_=u[u.length-1],w=s.rootNode.children,x=i?{type:"element",tagName:"span",properties:{className:[i]},children:w}:w;_.children=_.children.concat(x)},Emitter.prototype.openNode=function open(s){var i=this.stack,u=this.options.classPrefix+s,_=i[i.length-1],w={type:"element",tagName:"span",properties:{className:[u]},children:[]};_.children.push(w),i.push(w)},Emitter.prototype.closeNode=function close(){this.stack.pop()},Emitter.prototype.closeAllNodes=noop,Emitter.prototype.finalize=noop,Emitter.prototype.toHTML=function toHtmlNoop(){return""};var x="hljs-";function highlight(s,i,u){var j,P=_.configure({}),B=(u||{}).prefix;if("string"!=typeof s)throw w("Expected `string` for name, got `%s`",s);if(!_.getLanguage(s))throw w("Unknown language: `%s` is not registered",s);if("string"!=typeof i)throw w("Expected `string` for value, got `%s`",i);if(null==B&&(B=x),_.configure({__emitter:Emitter,classPrefix:B}),j=_.highlight(i,{language:s,ignoreIllegals:!0}),_.configure(P||{}),j.errorRaised)throw j.errorRaised;return{relevance:j.relevance,language:j.language,value:j.emitter.rootNode.children}}function Emitter(s){this.options=s,this.rootNode={children:[]},this.stack=[this.rootNode]}function noop(){}},92340:(s,i,u)=>{const _=u(6048);function coerceElementMatchingCallback(s){return"string"==typeof s?i=>i.element===s:s.constructor&&s.extend?i=>i instanceof s:s}class ArraySlice{constructor(s){this.elements=s||[]}toValue(){return this.elements.map((s=>s.toValue()))}map(s,i){return this.elements.map(s,i)}flatMap(s,i){return this.map(s,i).reduce(((s,i)=>s.concat(i)),[])}compactMap(s,i){const u=[];return this.forEach((_=>{const w=s.bind(i)(_);w&&u.push(w)})),u}filter(s,i){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(s,i))}reject(s,i){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(_(s),i))}find(s,i){return s=coerceElementMatchingCallback(s),this.elements.find(s,i)}forEach(s,i){this.elements.forEach(s,i)}reduce(s,i){return this.elements.reduce(s,i)}includes(s){return this.elements.some((i=>i.equals(s)))}shift(){return this.elements.shift()}unshift(s){this.elements.unshift(this.refract(s))}push(s){return this.elements.push(this.refract(s)),this}add(s){this.push(s)}get(s){return this.elements[s]}getValue(s){const i=this.elements[s];if(i)return i.toValue()}get length(){return this.elements.length}get isEmpty(){return 0===this.elements.length}get first(){return this.elements[0]}}"undefined"!=typeof Symbol&&(ArraySlice.prototype[Symbol.iterator]=function symbol(){return this.elements[Symbol.iterator]()}),s.exports=ArraySlice},55973:s=>{class KeyValuePair{constructor(s,i){this.key=s,this.value=i}clone(){const s=new KeyValuePair;return this.key&&(s.key=this.key.clone()),this.value&&(s.value=this.value.clone()),s}}s.exports=KeyValuePair},3110:(s,i,u)=>{const _=u(5187),w=u(85015),x=u(98023),j=u(53812),P=u(23805),B=u(85105),$=u(86804);class Namespace{constructor(s){this.elementMap={},this.elementDetection=[],this.Element=$.Element,this.KeyValuePair=$.KeyValuePair,s&&s.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(s){return s.namespace&&s.namespace({base:this}),s.load&&s.load({base:this}),this}useDefault(){return this.register("null",$.NullElement).register("string",$.StringElement).register("number",$.NumberElement).register("boolean",$.BooleanElement).register("array",$.ArrayElement).register("object",$.ObjectElement).register("member",$.MemberElement).register("ref",$.RefElement).register("link",$.LinkElement),this.detect(_,$.NullElement,!1).detect(w,$.StringElement,!1).detect(x,$.NumberElement,!1).detect(j,$.BooleanElement,!1).detect(Array.isArray,$.ArrayElement,!1).detect(P,$.ObjectElement,!1),this}register(s,i){return this._elements=void 0,this.elementMap[s]=i,this}unregister(s){return this._elements=void 0,delete this.elementMap[s],this}detect(s,i,u){return void 0===u||u?this.elementDetection.unshift([s,i]):this.elementDetection.push([s,i]),this}toElement(s){if(s instanceof this.Element)return s;let i;for(let u=0;u{const i=s[0].toUpperCase()+s.substr(1);this._elements[i]=this.elementMap[s]}))),this._elements}get serialiser(){return new B(this)}}B.prototype.Namespace=Namespace,s.exports=Namespace},10866:(s,i,u)=>{const _=u(6048),w=u(92340);class ObjectSlice extends w{map(s,i){return this.elements.map((u=>s.bind(i)(u.value,u.key,u)))}filter(s,i){return new ObjectSlice(this.elements.filter((u=>s.bind(i)(u.value,u.key,u))))}reject(s,i){return this.filter(_(s.bind(i)))}forEach(s,i){return this.elements.forEach(((u,_)=>{s.bind(i)(u.value,u.key,u,_)}))}keys(){return this.map(((s,i)=>i.toValue()))}values(){return this.map((s=>s.toValue()))}}s.exports=ObjectSlice},86804:(s,i,u)=>{const _=u(10316),w=u(41067),x=u(71167),j=u(40239),P=u(12242),B=u(6233),$=u(87726),U=u(61045),Y=u(86303),X=u(14540),Z=u(92340),ee=u(10866),ie=u(55973);function refract(s){if(s instanceof _)return s;if("string"==typeof s)return new x(s);if("number"==typeof s)return new j(s);if("boolean"==typeof s)return new P(s);if(null===s)return new w;if(Array.isArray(s))return new B(s.map(refract));if("object"==typeof s){return new U(s)}return s}_.prototype.ObjectElement=U,_.prototype.RefElement=X,_.prototype.MemberElement=$,_.prototype.refract=refract,Z.prototype.refract=refract,s.exports={Element:_,NullElement:w,StringElement:x,NumberElement:j,BooleanElement:P,ArrayElement:B,MemberElement:$,ObjectElement:U,LinkElement:Y,RefElement:X,refract,ArraySlice:Z,ObjectSlice:ee,KeyValuePair:ie}},86303:(s,i,u)=>{const _=u(10316);s.exports=class LinkElement extends _{constructor(s,i,u){super(s||[],i,u),this.element="link"}get relation(){return this.attributes.get("relation")}set relation(s){this.attributes.set("relation",s)}get href(){return this.attributes.get("href")}set href(s){this.attributes.set("href",s)}}},14540:(s,i,u)=>{const _=u(10316);s.exports=class RefElement extends _{constructor(s,i,u){super(s||[],i,u),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(s){this.attributes.set("path",s)}}},34035:(s,i,u)=>{const _=u(3110),w=u(86804);i.g$=_,i.KeyValuePair=u(55973),i.G6=w.ArraySlice,i.ot=w.ObjectSlice,i.Hg=w.Element,i.Om=w.StringElement,i.kT=w.NumberElement,i.bd=w.BooleanElement,i.Os=w.NullElement,i.wE=w.ArrayElement,i.Sh=w.ObjectElement,i.Pr=w.MemberElement,i.sI=w.RefElement,i.Ft=w.LinkElement,i.e=w.refract,u(85105),u(75147)},6233:(s,i,u)=>{const _=u(6048),w=u(10316),x=u(92340);class ArrayElement extends w{constructor(s,i,u){super(s||[],i,u),this.element="array"}primitive(){return"array"}get(s){return this.content[s]}getValue(s){const i=this.get(s);if(i)return i.toValue()}getIndex(s){return this.content[s]}set(s,i){return this.content[s]=this.refract(i),this}remove(s){const i=this.content.splice(s,1);return i.length?i[0]:null}map(s,i){return this.content.map(s,i)}flatMap(s,i){return this.map(s,i).reduce(((s,i)=>s.concat(i)),[])}compactMap(s,i){const u=[];return this.forEach((_=>{const w=s.bind(i)(_);w&&u.push(w)})),u}filter(s,i){return new x(this.content.filter(s,i))}reject(s,i){return this.filter(_(s),i)}reduce(s,i){let u,_;void 0!==i?(u=0,_=this.refract(i)):(u=1,_="object"===this.primitive()?this.first.value:this.first);for(let i=u;i{s.bind(i)(u,this.refract(_))}))}shift(){return this.content.shift()}unshift(s){this.content.unshift(this.refract(s))}push(s){return this.content.push(this.refract(s)),this}add(s){this.push(s)}findElements(s,i){const u=i||{},_=!!u.recursive,w=void 0===u.results?[]:u.results;return this.forEach(((i,u,x)=>{_&&void 0!==i.findElements&&i.findElements(s,{results:w,recursive:_}),s(i,u,x)&&w.push(i)})),w}find(s){return new x(this.findElements(s,{recursive:!0}))}findByElement(s){return this.find((i=>i.element===s))}findByClass(s){return this.find((i=>i.classes.includes(s)))}getById(s){return this.find((i=>i.id.toValue()===s)).first}includes(s){return this.content.some((i=>i.equals(s)))}contains(s){return this.includes(s)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(s){return new this.constructor(this.content.concat(s.content))}"fantasy-land/concat"(s){return this.concat(s)}"fantasy-land/map"(s){return new this.constructor(this.map(s))}"fantasy-land/chain"(s){return this.map((i=>s(i)),this).reduce(((s,i)=>s.concat(i)),this.empty())}"fantasy-land/filter"(s){return new this.constructor(this.content.filter(s))}"fantasy-land/reduce"(s,i){return this.content.reduce(s,i)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}ArrayElement.empty=function empty(){return new this},ArrayElement["fantasy-land/empty"]=ArrayElement.empty,"undefined"!=typeof Symbol&&(ArrayElement.prototype[Symbol.iterator]=function symbol(){return this.content[Symbol.iterator]()}),s.exports=ArrayElement},12242:(s,i,u)=>{const _=u(10316);s.exports=class BooleanElement extends _{constructor(s,i,u){super(s,i,u),this.element="boolean"}primitive(){return"boolean"}}},10316:(s,i,u)=>{const _=u(2404),w=u(55973),x=u(92340);class Element{constructor(s,i,u){i&&(this.meta=i),u&&(this.attributes=u),this.content=s}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this,this.meta.freeze()),this._attributes&&(this.attributes.parent=this,this.attributes.freeze()),this.children.forEach((s=>{s.parent=this,s.freeze()}),this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const s=new this.constructor;return s.element=this.element,this.meta.length&&(s._meta=this.meta.clone()),this.attributes.length&&(s._attributes=this.attributes.clone()),this.content?this.content.clone?s.content=this.content.clone():Array.isArray(this.content)?s.content=this.content.map((s=>s.clone())):s.content=this.content:s.content=this.content,s}toValue(){return this.content instanceof Element?this.content.toValue():this.content instanceof w?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map((s=>s.toValue()),this):this.content}toRef(s){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const i=new this.RefElement(this.id.toValue());return s&&(i.path=s),i}findRecursive(...s){if(arguments.length>1&&!this.isFrozen)throw new Error("Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`");const i=s.pop();let u=new x;const append=(s,i)=>(s.push(i),s),checkElement=(s,u)=>{u.element===i&&s.push(u);const _=u.findRecursive(i);return _&&_.reduce(append,s),u.content instanceof w&&(u.content.key&&checkElement(s,u.content.key),u.content.value&&checkElement(s,u.content.value)),s};return this.content&&(this.content.element&&checkElement(u,this.content),Array.isArray(this.content)&&this.content.reduce(checkElement,u)),s.isEmpty||(u=u.filter((i=>{let u=i.parents.map((s=>s.element));for(const i in s){const _=s[i],w=u.indexOf(_);if(-1===w)return!1;u=u.splice(0,w)}return!0}))),u}set(s){return this.content=s,this}equals(s){return _(this.toValue(),s)}getMetaProperty(s,i){if(!this.meta.hasKey(s)){if(this.isFrozen){const s=this.refract(i);return s.freeze(),s}this.meta.set(s,i)}return this.meta.get(s)}setMetaProperty(s,i){this.meta.set(s,i)}get element(){return this._storedElement||"element"}set element(s){this._storedElement=s}get content(){return this._content}set content(s){if(s instanceof Element)this._content=s;else if(s instanceof x)this.content=s.elements;else if("string"==typeof s||"number"==typeof s||"boolean"==typeof s||"null"===s||null==s)this._content=s;else if(s instanceof w)this._content=s;else if(Array.isArray(s))this._content=s.map(this.refract);else{if("object"!=typeof s)throw new Error("Cannot set content to given value");this._content=Object.keys(s).map((i=>new this.MemberElement(i,s[i])))}}get meta(){if(!this._meta){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._meta=new this.ObjectElement}return this._meta}set meta(s){s instanceof this.ObjectElement?this._meta=s:this.meta.set(s||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._attributes=new this.ObjectElement}return this._attributes}set attributes(s){s instanceof this.ObjectElement?this._attributes=s:this.attributes.set(s||{})}get id(){return this.getMetaProperty("id","")}set id(s){this.setMetaProperty("id",s)}get classes(){return this.getMetaProperty("classes",[])}set classes(s){this.setMetaProperty("classes",s)}get title(){return this.getMetaProperty("title","")}set title(s){this.setMetaProperty("title",s)}get description(){return this.getMetaProperty("description","")}set description(s){this.setMetaProperty("description",s)}get links(){return this.getMetaProperty("links",[])}set links(s){this.setMetaProperty("links",s)}get isFrozen(){return Object.isFrozen(this)}get parents(){let{parent:s}=this;const i=new x;for(;s;)i.push(s),s=s.parent;return i}get children(){if(Array.isArray(this.content))return new x(this.content);if(this.content instanceof w){const s=new x([this.content.key]);return this.content.value&&s.push(this.content.value),s}return this.content instanceof Element?new x([this.content]):new x}get recursiveChildren(){const s=new x;return this.children.forEach((i=>{s.push(i),i.recursiveChildren.forEach((i=>{s.push(i)}))})),s}}s.exports=Element},87726:(s,i,u)=>{const _=u(55973),w=u(10316);s.exports=class MemberElement extends w{constructor(s,i,u,w){super(new _,u,w),this.element="member",this.key=s,this.value=i}get key(){return this.content.key}set key(s){this.content.key=this.refract(s)}get value(){return this.content.value}set value(s){this.content.value=this.refract(s)}}},41067:(s,i,u)=>{const _=u(10316);s.exports=class NullElement extends _{constructor(s,i,u){super(s||null,i,u),this.element="null"}primitive(){return"null"}set(){return new Error("Cannot set the value of null")}}},40239:(s,i,u)=>{const _=u(10316);s.exports=class NumberElement extends _{constructor(s,i,u){super(s,i,u),this.element="number"}primitive(){return"number"}}},61045:(s,i,u)=>{const _=u(6048),w=u(23805),x=u(6233),j=u(87726),P=u(10866);s.exports=class ObjectElement extends x{constructor(s,i,u){super(s||[],i,u),this.element="object"}primitive(){return"object"}toValue(){return this.content.reduce(((s,i)=>(s[i.key.toValue()]=i.value?i.value.toValue():void 0,s)),{})}get(s){const i=this.getMember(s);if(i)return i.value}getMember(s){if(void 0!==s)return this.content.find((i=>i.key.toValue()===s))}remove(s){let i=null;return this.content=this.content.filter((u=>u.key.toValue()!==s||(i=u,!1))),i}getKey(s){const i=this.getMember(s);if(i)return i.key}set(s,i){if(w(s))return Object.keys(s).forEach((i=>{this.set(i,s[i])})),this;const u=s,_=this.getMember(u);return _?_.value=i:this.content.push(new j(u,i)),this}keys(){return this.content.map((s=>s.key.toValue()))}values(){return this.content.map((s=>s.value.toValue()))}hasKey(s){return this.content.some((i=>i.key.equals(s)))}items(){return this.content.map((s=>[s.key.toValue(),s.value.toValue()]))}map(s,i){return this.content.map((u=>s.bind(i)(u.value,u.key,u)))}compactMap(s,i){const u=[];return this.forEach(((_,w,x)=>{const j=s.bind(i)(_,w,x);j&&u.push(j)})),u}filter(s,i){return new P(this.content).filter(s,i)}reject(s,i){return this.filter(_(s),i)}forEach(s,i){return this.content.forEach((u=>s.bind(i)(u.value,u.key,u)))}}},71167:(s,i,u)=>{const _=u(10316);s.exports=class StringElement extends _{constructor(s,i,u){super(s,i,u),this.element="string"}primitive(){return"string"}get length(){return this.content.length}}},75147:(s,i,u)=>{const _=u(85105);s.exports=class JSON06Serialiser extends _{serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);let i;s._attributes&&s.attributes.get("variable")&&(i=s.attributes.get("variable"));const u={element:s.element};s._meta&&s._meta.length>0&&(u.meta=this.serialiseObject(s.meta));const _="enum"===s.element||-1!==s.attributes.keys().indexOf("enumerations");if(_){const i=this.enumSerialiseAttributes(s);i&&(u.attributes=i)}else if(s._attributes&&s._attributes.length>0){let{attributes:_}=s;_.get("metadata")&&(_=_.clone(),_.set("meta",_.get("metadata")),_.remove("metadata")),"member"===s.element&&i&&(_=_.clone(),_.remove("variable")),_.length>0&&(u.attributes=this.serialiseObject(_))}if(_)u.content=this.enumSerialiseContent(s,u);else if(this[`${s.element}SerialiseContent`])u.content=this[`${s.element}SerialiseContent`](s,u);else if(void 0!==s.content){let _;i&&s.content.key?(_=s.content.clone(),_.key.attributes.set("variable",i),_=this.serialiseContent(_)):_=this.serialiseContent(s.content),this.shouldSerialiseContent(s,_)&&(u.content=_)}else this.shouldSerialiseContent(s,s.content)&&s instanceof this.namespace.elements.Array&&(u.content=[]);return u}shouldSerialiseContent(s,i){return"parseResult"===s.element||"httpRequest"===s.element||"httpResponse"===s.element||"category"===s.element||"link"===s.element||void 0!==i&&(!Array.isArray(i)||0!==i.length)}refSerialiseContent(s,i){return delete i.attributes,{href:s.toValue(),path:s.path.toValue()}}sourceMapSerialiseContent(s){return s.toValue()}dataStructureSerialiseContent(s){return[this.serialiseContent(s.content)]}enumSerialiseAttributes(s){const i=s.attributes.clone(),u=i.remove("enumerations")||new this.namespace.elements.Array([]),_=i.get("default");let w=i.get("samples")||new this.namespace.elements.Array([]);if(_&&_.content&&(_.content.attributes&&_.content.attributes.remove("typeAttributes"),i.set("default",new this.namespace.elements.Array([_.content]))),w.forEach((s=>{s.content&&s.content.element&&s.content.attributes.remove("typeAttributes")})),s.content&&0!==u.length&&w.unshift(s.content),w=w.map((s=>s instanceof this.namespace.elements.Array?[s]:new this.namespace.elements.Array([s.content]))),w.length&&i.set("samples",w),i.length>0)return this.serialiseObject(i)}enumSerialiseContent(s){if(s._attributes){const i=s.attributes.get("enumerations");if(i&&i.length>0)return i.content.map((s=>{const i=s.clone();return i.attributes.remove("typeAttributes"),this.serialise(i)}))}if(s.content){const i=s.content.clone();return i.attributes.remove("typeAttributes"),[this.serialise(i)]}return[]}deserialise(s){if("string"==typeof s)return new this.namespace.elements.String(s);if("number"==typeof s)return new this.namespace.elements.Number(s);if("boolean"==typeof s)return new this.namespace.elements.Boolean(s);if(null===s)return new this.namespace.elements.Null;if(Array.isArray(s))return new this.namespace.elements.Array(s.map(this.deserialise,this));const i=this.namespace.getElementClass(s.element),u=new i;u.element!==s.element&&(u.element=s.element),s.meta&&this.deserialiseObject(s.meta,u.meta),s.attributes&&this.deserialiseObject(s.attributes,u.attributes);const _=this.deserialiseContent(s.content);if(void 0===_&&null!==u.content||(u.content=_),"enum"===u.element){u.content&&u.attributes.set("enumerations",u.content);let s=u.attributes.get("samples");if(u.attributes.remove("samples"),s){const _=s;s=new this.namespace.elements.Array,_.forEach((_=>{_.forEach((_=>{const w=new i(_);w.element=u.element,s.push(w)}))}));const w=s.shift();u.content=w?w.content:void 0,u.attributes.set("samples",s)}else u.content=void 0;let _=u.attributes.get("default");if(_&&_.length>0){_=_.get(0);const s=new i(_);s.element=u.element,u.attributes.set("default",s)}}else if("dataStructure"===u.element&&Array.isArray(u.content))[u.content]=u.content;else if("category"===u.element){const s=u.attributes.get("meta");s&&(u.attributes.set("metadata",s),u.attributes.remove("meta"))}else"member"===u.element&&u.key&&u.key._attributes&&u.key._attributes.getValue("variable")&&(u.attributes.set("variable",u.key.attributes.get("variable")),u.key.attributes.remove("variable"));return u}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const i={key:this.serialise(s.key)};return s.value&&(i.value=this.serialise(s.value)),i}return s&&s.map?s.map(this.serialise,this):s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const i=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(i.value=this.deserialise(s.value)),i}if(s.map)return s.map(this.deserialise,this)}return s}shouldRefract(s){return!!(s._attributes&&s.attributes.keys().length||s._meta&&s.meta.keys().length)||"enum"!==s.element&&(s.element!==s.primitive()||"member"===s.element)}convertKeyToRefract(s,i){return this.shouldRefract(i)?this.serialise(i):"enum"===i.element?this.serialiseEnum(i):"array"===i.element?i.map((i=>this.shouldRefract(i)||"default"===s?this.serialise(i):"array"===i.element||"object"===i.element||"enum"===i.element?i.children.map((s=>this.serialise(s))):i.toValue())):"object"===i.element?(i.content||[]).map(this.serialise,this):i.toValue()}serialiseEnum(s){return s.children.map((s=>this.serialise(s)))}serialiseObject(s){const i={};return s.forEach(((s,u)=>{if(s){const _=u.toValue();i[_]=this.convertKeyToRefract(_,s)}})),i}deserialiseObject(s,i){Object.keys(s).forEach((u=>{i.set(u,this.deserialise(s[u]))}))}}},85105:s=>{s.exports=class JSONSerialiser{constructor(s){this.namespace=s||new this.Namespace}serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);const i={element:s.element};s._meta&&s._meta.length>0&&(i.meta=this.serialiseObject(s.meta)),s._attributes&&s._attributes.length>0&&(i.attributes=this.serialiseObject(s.attributes));const u=this.serialiseContent(s.content);return void 0!==u&&(i.content=u),i}deserialise(s){if(!s.element)throw new Error("Given value is not an object containing an element name");const i=new(this.namespace.getElementClass(s.element));i.element!==s.element&&(i.element=s.element),s.meta&&this.deserialiseObject(s.meta,i.meta),s.attributes&&this.deserialiseObject(s.attributes,i.attributes);const u=this.deserialiseContent(s.content);return void 0===u&&null!==i.content||(i.content=u),i}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const i={key:this.serialise(s.key)};return s.value&&(i.value=this.serialise(s.value)),i}if(s&&s.map){if(0===s.length)return;return s.map(this.serialise,this)}return s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const i=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(i.value=this.deserialise(s.value)),i}if(s.map)return s.map(this.deserialise,this)}return s}serialiseObject(s){const i={};if(s.forEach(((s,u)=>{s&&(i[u.toValue()]=this.serialise(s))})),0!==Object.keys(i).length)return i}deserialiseObject(s,i){Object.keys(s).forEach((u=>{i.set(u,this.deserialise(s[u]))}))}}},58859:(s,i,u)=>{var _="function"==typeof Map&&Map.prototype,w=Object.getOwnPropertyDescriptor&&_?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,x=_&&w&&"function"==typeof w.get?w.get:null,j=_&&Map.prototype.forEach,P="function"==typeof Set&&Set.prototype,B=Object.getOwnPropertyDescriptor&&P?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,$=P&&B&&"function"==typeof B.get?B.get:null,U=P&&Set.prototype.forEach,Y="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,X="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Z="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ee=Boolean.prototype.valueOf,ie=Object.prototype.toString,ae=Function.prototype.toString,le=String.prototype.match,ce=String.prototype.slice,pe=String.prototype.replace,de=String.prototype.toUpperCase,fe=String.prototype.toLowerCase,ye=RegExp.prototype.test,be=Array.prototype.concat,_e=Array.prototype.join,we=Array.prototype.slice,Se=Math.floor,xe="function"==typeof BigInt?BigInt.prototype.valueOf:null,Pe=Object.getOwnPropertySymbols,Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Re="function"==typeof Symbol&&"object"==typeof Symbol.iterator,qe="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Re||"symbol")?Symbol.toStringTag:null,$e=Object.prototype.propertyIsEnumerable,ze=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(s){return s.__proto__}:null);function addNumericSeparator(s,i){if(s===1/0||s===-1/0||s!=s||s&&s>-1e3&&s<1e3||ye.call(/e/,i))return i;var u=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof s){var _=s<0?-Se(-s):Se(s);if(_!==s){var w=String(_),x=ce.call(i,w.length+1);return pe.call(w,u,"$&_")+"."+pe.call(pe.call(x,/([0-9]{3})/g,"$&_"),/_$/,"")}}return pe.call(i,u,"$&_")}var We=u(42634),He=We.custom,Ye=isSymbol(He)?He:null;function wrapQuotes(s,i,u){var _="double"===(u.quoteStyle||i)?'"':"'";return _+s+_}function quote(s){return pe.call(String(s),/"/g,""")}function isArray(s){return!("[object Array]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}function isRegExp(s){return!("[object RegExp]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}function isSymbol(s){if(Re)return s&&"object"==typeof s&&s instanceof Symbol;if("symbol"==typeof s)return!0;if(!s||"object"!=typeof s||!Te)return!1;try{return Te.call(s),!0}catch(s){}return!1}s.exports=function inspect_(s,i,_,w){var P=i||{};if(has(P,"quoteStyle")&&"single"!==P.quoteStyle&&"double"!==P.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(P,"maxStringLength")&&("number"==typeof P.maxStringLength?P.maxStringLength<0&&P.maxStringLength!==1/0:null!==P.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var B=!has(P,"customInspect")||P.customInspect;if("boolean"!=typeof B&&"symbol"!==B)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(P,"indent")&&null!==P.indent&&"\t"!==P.indent&&!(parseInt(P.indent,10)===P.indent&&P.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(P,"numericSeparator")&&"boolean"!=typeof P.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ie=P.numericSeparator;if(void 0===s)return"undefined";if(null===s)return"null";if("boolean"==typeof s)return s?"true":"false";if("string"==typeof s)return inspectString(s,P);if("number"==typeof s){if(0===s)return 1/0/s>0?"0":"-0";var de=String(s);return ie?addNumericSeparator(s,de):de}if("bigint"==typeof s){var ye=String(s)+"n";return ie?addNumericSeparator(s,ye):ye}var Se=void 0===P.depth?5:P.depth;if(void 0===_&&(_=0),_>=Se&&Se>0&&"object"==typeof s)return isArray(s)?"[Array]":"[Object]";var Pe=function getIndent(s,i){var u;if("\t"===s.indent)u="\t";else{if(!("number"==typeof s.indent&&s.indent>0))return null;u=_e.call(Array(s.indent+1)," ")}return{base:u,prev:_e.call(Array(i+1),u)}}(P,_);if(void 0===w)w=[];else if(indexOf(w,s)>=0)return"[Circular]";function inspect(s,i,u){if(i&&(w=we.call(w)).push(i),u){var x={depth:P.depth};return has(P,"quoteStyle")&&(x.quoteStyle=P.quoteStyle),inspect_(s,x,_+1,w)}return inspect_(s,P,_+1,w)}if("function"==typeof s&&!isRegExp(s)){var He=function nameOf(s){if(s.name)return s.name;var i=le.call(ae.call(s),/^function\s*([\w$]+)/);if(i)return i[1];return null}(s),Xe=arrObjKeys(s,inspect);return"[Function"+(He?": "+He:" (anonymous)")+"]"+(Xe.length>0?" { "+_e.call(Xe,", ")+" }":"")}if(isSymbol(s)){var Qe=Re?pe.call(String(s),/^(Symbol\(.*\))_[^)]*$/,"$1"):Te.call(s);return"object"!=typeof s||Re?Qe:markBoxed(Qe)}if(function isElement(s){if(!s||"object"!=typeof s)return!1;if("undefined"!=typeof HTMLElement&&s instanceof HTMLElement)return!0;return"string"==typeof s.nodeName&&"function"==typeof s.getAttribute}(s)){for(var et="<"+fe.call(String(s.nodeName)),tt=s.attributes||[],rt=0;rt"}if(isArray(s)){if(0===s.length)return"[]";var nt=arrObjKeys(s,inspect);return Pe&&!function singleLineValues(s){for(var i=0;i=0)return!1;return!0}(nt)?"["+indentedJoin(nt,Pe)+"]":"[ "+_e.call(nt,", ")+" ]"}if(function isError(s){return!("[object Error]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s)){var ot=arrObjKeys(s,inspect);return"cause"in Error.prototype||!("cause"in s)||$e.call(s,"cause")?0===ot.length?"["+String(s)+"]":"{ ["+String(s)+"] "+_e.call(ot,", ")+" }":"{ ["+String(s)+"] "+_e.call(be.call("[cause]: "+inspect(s.cause),ot),", ")+" }"}if("object"==typeof s&&B){if(Ye&&"function"==typeof s[Ye]&&We)return We(s,{depth:Se-_});if("symbol"!==B&&"function"==typeof s.inspect)return s.inspect()}if(function isMap(s){if(!x||!s||"object"!=typeof s)return!1;try{x.call(s);try{$.call(s)}catch(s){return!0}return s instanceof Map}catch(s){}return!1}(s)){var st=[];return j&&j.call(s,(function(i,u){st.push(inspect(u,s,!0)+" => "+inspect(i,s))})),collectionOf("Map",x.call(s),st,Pe)}if(function isSet(s){if(!$||!s||"object"!=typeof s)return!1;try{$.call(s);try{x.call(s)}catch(s){return!0}return s instanceof Set}catch(s){}return!1}(s)){var it=[];return U&&U.call(s,(function(i){it.push(inspect(i,s))})),collectionOf("Set",$.call(s),it,Pe)}if(function isWeakMap(s){if(!Y||!s||"object"!=typeof s)return!1;try{Y.call(s,Y);try{X.call(s,X)}catch(s){return!0}return s instanceof WeakMap}catch(s){}return!1}(s))return weakCollectionOf("WeakMap");if(function isWeakSet(s){if(!X||!s||"object"!=typeof s)return!1;try{X.call(s,X);try{Y.call(s,Y)}catch(s){return!0}return s instanceof WeakSet}catch(s){}return!1}(s))return weakCollectionOf("WeakSet");if(function isWeakRef(s){if(!Z||!s||"object"!=typeof s)return!1;try{return Z.call(s),!0}catch(s){}return!1}(s))return weakCollectionOf("WeakRef");if(function isNumber(s){return!("[object Number]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s))return markBoxed(inspect(Number(s)));if(function isBigInt(s){if(!s||"object"!=typeof s||!xe)return!1;try{return xe.call(s),!0}catch(s){}return!1}(s))return markBoxed(inspect(xe.call(s)));if(function isBoolean(s){return!("[object Boolean]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s))return markBoxed(ee.call(s));if(function isString(s){return!("[object String]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s))return markBoxed(inspect(String(s)));if("undefined"!=typeof window&&s===window)return"{ [object Window] }";if(s===u.g)return"{ [object globalThis] }";if(!function isDate(s){return!("[object Date]"!==toStr(s)||qe&&"object"==typeof s&&qe in s)}(s)&&!isRegExp(s)){var at=arrObjKeys(s,inspect),lt=ze?ze(s)===Object.prototype:s instanceof Object||s.constructor===Object,ct=s instanceof Object?"":"null prototype",ut=!lt&&qe&&Object(s)===s&&qe in s?ce.call(toStr(s),8,-1):ct?"Object":"",pt=(lt||"function"!=typeof s.constructor?"":s.constructor.name?s.constructor.name+" ":"")+(ut||ct?"["+_e.call(be.call([],ut||[],ct||[]),": ")+"] ":"");return 0===at.length?pt+"{}":Pe?pt+"{"+indentedJoin(at,Pe)+"}":pt+"{ "+_e.call(at,", ")+" }"}return String(s)};var Xe=Object.prototype.hasOwnProperty||function(s){return s in this};function has(s,i){return Xe.call(s,i)}function toStr(s){return ie.call(s)}function indexOf(s,i){if(s.indexOf)return s.indexOf(i);for(var u=0,_=s.length;u<_;u++)if(s[u]===i)return u;return-1}function inspectString(s,i){if(s.length>i.maxStringLength){var u=s.length-i.maxStringLength,_="... "+u+" more character"+(u>1?"s":"");return inspectString(ce.call(s,0,i.maxStringLength),i)+_}return wrapQuotes(pe.call(pe.call(s,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",i)}function lowbyte(s){var i=s.charCodeAt(0),u={8:"b",9:"t",10:"n",12:"f",13:"r"}[i];return u?"\\"+u:"\\x"+(i<16?"0":"")+de.call(i.toString(16))}function markBoxed(s){return"Object("+s+")"}function weakCollectionOf(s){return s+" { ? }"}function collectionOf(s,i,u,_){return s+" ("+i+") {"+(_?indentedJoin(u,_):_e.call(u,", "))+"}"}function indentedJoin(s,i){if(0===s.length)return"";var u="\n"+i.prev+i.base;return u+_e.call(s,","+u)+"\n"+i.prev}function arrObjKeys(s,i){var u=isArray(s),_=[];if(u){_.length=s.length;for(var w=0;w{var i,u,_=s.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(s){if(i===setTimeout)return setTimeout(s,0);if((i===defaultSetTimout||!i)&&setTimeout)return i=setTimeout,setTimeout(s,0);try{return i(s,0)}catch(u){try{return i.call(null,s,0)}catch(u){return i.call(this,s,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(s){i=defaultSetTimout}try{u="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(s){u=defaultClearTimeout}}();var w,x=[],j=!1,P=-1;function cleanUpNextTick(){j&&w&&(j=!1,w.length?x=w.concat(x):P=-1,x.length&&drainQueue())}function drainQueue(){if(!j){var s=runTimeout(cleanUpNextTick);j=!0;for(var i=x.length;i;){for(w=x,x=[];++P1)for(var u=1;u{"use strict";var _=u(6925);function emptyFunction(){}function emptyFunctionWithReset(){}emptyFunctionWithReset.resetWarningCache=emptyFunction,s.exports=function(){function shim(s,i,u,w,x,j){if(j!==_){var P=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw P.name="Invariant Violation",P}}function getShim(){return shim}shim.isRequired=shim;var s={array:shim,bigint:shim,bool:shim,func:shim,number:shim,object:shim,string:shim,symbol:shim,any:shim,arrayOf:getShim,element:shim,elementType:shim,instanceOf:getShim,node:shim,objectOf:getShim,oneOf:getShim,oneOfType:getShim,shape:getShim,exact:getShim,checkPropTypes:emptyFunctionWithReset,resetWarningCache:emptyFunction};return s.PropTypes=s,s}},5556:(s,i,u)=>{s.exports=u(2694)()},6925:s=>{"use strict";s.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},74765:s=>{"use strict";var i=String.prototype.replace,u=/%20/g,_="RFC1738",w="RFC3986";s.exports={default:w,formatters:{RFC1738:function(s){return i.call(s,u,"+")},RFC3986:function(s){return String(s)}},RFC1738:_,RFC3986:w}},55373:(s,i,u)=>{"use strict";var _=u(98636),w=u(62642),x=u(74765);s.exports={formats:x,parse:w,stringify:_}},62642:(s,i,u)=>{"use strict";var _=u(37720),w=Object.prototype.hasOwnProperty,x=Array.isArray,j={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},interpretNumericEntities=function(s){return s.replace(/&#(\d+);/g,(function(s,i){return String.fromCharCode(parseInt(i,10))}))},parseArrayValue=function(s,i){return s&&"string"==typeof s&&i.comma&&s.indexOf(",")>-1?s.split(","):s},P=function parseQueryStringKeys(s,i,u,_){if(s){var x=u.allowDots?s.replace(/\.([^.[]+)/g,"[$1]"):s,j=/(\[[^[\]]*])/g,P=u.depth>0&&/(\[[^[\]]*])/.exec(x),B=P?x.slice(0,P.index):x,$=[];if(B){if(!u.plainObjects&&w.call(Object.prototype,B)&&!u.allowPrototypes)return;$.push(B)}for(var U=0;u.depth>0&&null!==(P=j.exec(x))&&U=0;--x){var j,P=s[x];if("[]"===P&&u.parseArrays)j=[].concat(w);else{j=u.plainObjects?Object.create(null):{};var B="["===P.charAt(0)&&"]"===P.charAt(P.length-1)?P.slice(1,-1):P,$=parseInt(B,10);u.parseArrays||""!==B?!isNaN($)&&P!==B&&String($)===B&&$>=0&&u.parseArrays&&$<=u.arrayLimit?(j=[])[$]=w:"__proto__"!==B&&(j[B]=w):j={0:w}}w=j}return w}($,i,u,_)}};s.exports=function(s,i){var u=function normalizeParseOptions(s){if(!s)return j;if(null!==s.decoder&&void 0!==s.decoder&&"function"!=typeof s.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==s.charset&&"utf-8"!==s.charset&&"iso-8859-1"!==s.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var i=void 0===s.charset?j.charset:s.charset;return{allowDots:void 0===s.allowDots?j.allowDots:!!s.allowDots,allowPrototypes:"boolean"==typeof s.allowPrototypes?s.allowPrototypes:j.allowPrototypes,allowSparse:"boolean"==typeof s.allowSparse?s.allowSparse:j.allowSparse,arrayLimit:"number"==typeof s.arrayLimit?s.arrayLimit:j.arrayLimit,charset:i,charsetSentinel:"boolean"==typeof s.charsetSentinel?s.charsetSentinel:j.charsetSentinel,comma:"boolean"==typeof s.comma?s.comma:j.comma,decoder:"function"==typeof s.decoder?s.decoder:j.decoder,delimiter:"string"==typeof s.delimiter||_.isRegExp(s.delimiter)?s.delimiter:j.delimiter,depth:"number"==typeof s.depth||!1===s.depth?+s.depth:j.depth,ignoreQueryPrefix:!0===s.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof s.interpretNumericEntities?s.interpretNumericEntities:j.interpretNumericEntities,parameterLimit:"number"==typeof s.parameterLimit?s.parameterLimit:j.parameterLimit,parseArrays:!1!==s.parseArrays,plainObjects:"boolean"==typeof s.plainObjects?s.plainObjects:j.plainObjects,strictNullHandling:"boolean"==typeof s.strictNullHandling?s.strictNullHandling:j.strictNullHandling}}(i);if(""===s||null==s)return u.plainObjects?Object.create(null):{};for(var B="string"==typeof s?function parseQueryStringValues(s,i){var u,P={},B=i.ignoreQueryPrefix?s.replace(/^\?/,""):s,$=i.parameterLimit===1/0?void 0:i.parameterLimit,U=B.split(i.delimiter,$),Y=-1,X=i.charset;if(i.charsetSentinel)for(u=0;u-1&&(ee=x(ee)?[ee]:ee),w.call(P,Z)?P[Z]=_.combine(P[Z],ee):P[Z]=ee}return P}(s,u):s,$=u.plainObjects?Object.create(null):{},U=Object.keys(B),Y=0;Y{"use strict";var _=u(920),w=u(37720),x=u(74765),j=Object.prototype.hasOwnProperty,P={brackets:function brackets(s){return s+"[]"},comma:"comma",indices:function indices(s,i){return s+"["+i+"]"},repeat:function repeat(s){return s}},B=Array.isArray,$=String.prototype.split,U=Array.prototype.push,pushToArray=function(s,i){U.apply(s,B(i)?i:[i])},Y=Date.prototype.toISOString,X=x.default,Z={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:w.encode,encodeValuesOnly:!1,format:X,formatter:x.formatters[X],indices:!1,serializeDate:function serializeDate(s){return Y.call(s)},skipNulls:!1,strictNullHandling:!1},ee={},ie=function stringify(s,i,u,x,j,P,U,Y,X,ie,ae,le,ce,pe,de,fe){for(var ye=s,be=fe,_e=0,we=!1;void 0!==(be=be.get(ee))&&!we;){var Se=be.get(s);if(_e+=1,void 0!==Se){if(Se===_e)throw new RangeError("Cyclic object value");we=!0}void 0===be.get(ee)&&(_e=0)}if("function"==typeof Y?ye=Y(i,ye):ye instanceof Date?ye=ae(ye):"comma"===u&&B(ye)&&(ye=w.maybeMap(ye,(function(s){return s instanceof Date?ae(s):s}))),null===ye){if(j)return U&&!pe?U(i,Z.encoder,de,"key",le):i;ye=""}if(function isNonNullishPrimitive(s){return"string"==typeof s||"number"==typeof s||"boolean"==typeof s||"symbol"==typeof s||"bigint"==typeof s}(ye)||w.isBuffer(ye)){if(U){var xe=pe?i:U(i,Z.encoder,de,"key",le);if("comma"===u&&pe){for(var Pe=$.call(String(ye),","),Te="",Re=0;Re0?ye.join(",")||null:void 0}];else if(B(Y))qe=Y;else{var ze=Object.keys(ye);qe=X?ze.sort(X):ze}for(var We=x&&B(ye)&&1===ye.length?i+"[]":i,He=0;He0?de+pe:""}},37720:(s,i,u)=>{"use strict";var _=u(74765),w=Object.prototype.hasOwnProperty,x=Array.isArray,j=function(){for(var s=[],i=0;i<256;++i)s.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase());return s}(),P=function arrayToObject(s,i){for(var u=i&&i.plainObjects?Object.create(null):{},_=0;_1;){var i=s.pop(),u=i.obj[i.prop];if(x(u)){for(var _=[],w=0;w=48&&U<=57||U>=65&&U<=90||U>=97&&U<=122||x===_.RFC1738&&(40===U||41===U)?B+=P.charAt($):U<128?B+=j[U]:U<2048?B+=j[192|U>>6]+j[128|63&U]:U<55296||U>=57344?B+=j[224|U>>12]+j[128|U>>6&63]+j[128|63&U]:($+=1,U=65536+((1023&U)<<10|1023&P.charCodeAt($)),B+=j[240|U>>18]+j[128|U>>12&63]+j[128|U>>6&63]+j[128|63&U])}return B},isBuffer:function isBuffer(s){return!(!s||"object"!=typeof s)&&!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))},isRegExp:function isRegExp(s){return"[object RegExp]"===Object.prototype.toString.call(s)},maybeMap:function maybeMap(s,i){if(x(s)){for(var u=[],_=0;_{"use strict";var u=Object.prototype.hasOwnProperty;function decode(s){try{return decodeURIComponent(s.replace(/\+/g," "))}catch(s){return null}}function encode(s){try{return encodeURIComponent(s)}catch(s){return null}}i.stringify=function querystringify(s,i){i=i||"";var _,w,x=[];for(w in"string"!=typeof i&&(i="?"),s)if(u.call(s,w)){if((_=s[w])||null!=_&&!isNaN(_)||(_=""),w=encode(w),_=encode(_),null===w||null===_)continue;x.push(w+"="+_)}return x.length?i+x.join("&"):""},i.parse=function querystring(s){for(var i,u=/([^=?#&]+)=?([^&]*)/g,_={};i=u.exec(s);){var w=decode(i[1]),x=decode(i[2]);null===w||null===x||w in _||(_[w]=x)}return _}},41859:(s,i,u)=>{const _=u(27096),w=u(78004),x=_.types;s.exports=class RandExp{constructor(s,i){if(this._setDefaults(s),s instanceof RegExp)this.ignoreCase=s.ignoreCase,this.multiline=s.multiline,s=s.source;else{if("string"!=typeof s)throw new Error("Expected a regexp or string");this.ignoreCase=i&&-1!==i.indexOf("i"),this.multiline=i&&-1!==i.indexOf("m")}this.tokens=_(s)}_setDefaults(s){this.max=null!=s.max?s.max:null!=RandExp.prototype.max?RandExp.prototype.max:100,this.defaultRange=s.defaultRange?s.defaultRange:this.defaultRange.clone(),s.randInt&&(this.randInt=s.randInt)}gen(){return this._gen(this.tokens,[])}_gen(s,i){var u,_,w,j,P;switch(s.type){case x.ROOT:case x.GROUP:if(s.followedBy||s.notFollowedBy)return"";for(s.remember&&void 0===s.groupNumber&&(s.groupNumber=i.push(null)-1),_="",j=0,P=(u=s.options?this._randSelect(s.options):s.stack).length;j{"use strict";var _=u(65606),w=65536,x=4294967295;var j=u(92861).Buffer,P=u.g.crypto||u.g.msCrypto;P&&P.getRandomValues?s.exports=function randomBytes(s,i){if(s>x)throw new RangeError("requested too many random bytes");var u=j.allocUnsafe(s);if(s>0)if(s>w)for(var B=0;B{"use strict";function _typeof(s){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(s){return typeof s}:function(s){return s&&"function"==typeof Symbol&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},_typeof(s)}Object.defineProperty(i,"__esModule",{value:!0}),i.CopyToClipboard=void 0;var _=_interopRequireDefault(u(96540)),w=_interopRequireDefault(u(17965)),x=["text","onCopy","options","children"];function _interopRequireDefault(s){return s&&s.__esModule?s:{default:s}}function ownKeys(s,i){var u=Object.keys(s);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);i&&(_=_.filter((function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable}))),u.push.apply(u,_)}return u}function _objectSpread(s){for(var i=1;i=0||(w[u]=s[u]);return w}(s,i);if(Object.getOwnPropertySymbols){var x=Object.getOwnPropertySymbols(s);for(_=0;_=0||Object.prototype.propertyIsEnumerable.call(s,u)&&(w[u]=s[u])}return w}function _defineProperties(s,i){for(var u=0;u{"use strict";var _=u(25264).CopyToClipboard;_.CopyToClipboard=_,s.exports=_},81214:(s,i,u)=>{"use strict";function _typeof(s){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(s){return typeof s}:function(s){return s&&"function"==typeof Symbol&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},_typeof(s)}Object.defineProperty(i,"__esModule",{value:!0}),i.DebounceInput=void 0;var _=_interopRequireDefault(u(96540)),w=_interopRequireDefault(u(20181)),x=["element","onChange","value","minLength","debounceTimeout","forceNotifyByEnter","forceNotifyOnBlur","onKeyDown","onBlur","inputRef"];function _interopRequireDefault(s){return s&&s.__esModule?s:{default:s}}function _objectWithoutProperties(s,i){if(null==s)return{};var u,_,w=function _objectWithoutPropertiesLoose(s,i){if(null==s)return{};var u,_,w={},x=Object.keys(s);for(_=0;_=0||(w[u]=s[u]);return w}(s,i);if(Object.getOwnPropertySymbols){var x=Object.getOwnPropertySymbols(s);for(_=0;_=0||Object.prototype.propertyIsEnumerable.call(s,u)&&(w[u]=s[u])}return w}function ownKeys(s,i){var u=Object.keys(s);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);i&&(_=_.filter((function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable}))),u.push.apply(u,_)}return u}function _objectSpread(s){for(var i=1;i=_?u.notify(s):i.length>w.length&&u.notify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:""})}))}))})),_defineProperty(_assertThisInitialized(u),"onKeyDown",(function(s){"Enter"===s.key&&u.forceNotify(s);var i=u.props.onKeyDown;i&&(s.persist(),i(s))})),_defineProperty(_assertThisInitialized(u),"onBlur",(function(s){u.forceNotify(s);var i=u.props.onBlur;i&&(s.persist(),i(s))})),_defineProperty(_assertThisInitialized(u),"createNotifier",(function(s){if(s<0)u.notify=function(){return null};else if(0===s)u.notify=u.doNotify;else{var i=(0,w.default)((function(s){u.isDebouncing=!1,u.doNotify(s)}),s);u.notify=function(s){u.isDebouncing=!0,i(s)},u.flush=function(){return i.flush()},u.cancel=function(){u.isDebouncing=!1,i.cancel()}}})),_defineProperty(_assertThisInitialized(u),"doNotify",(function(){u.props.onChange.apply(void 0,arguments)})),_defineProperty(_assertThisInitialized(u),"forceNotify",(function(s){var i=u.props.debounceTimeout;if(u.isDebouncing||!(i>0)){u.cancel&&u.cancel();var _=u.state.value,w=u.props.minLength;_.length>=w?u.doNotify(s):u.doNotify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:_})}))}})),u.isDebouncing=!1,u.state={value:void 0===s.value||null===s.value?"":s.value};var _=u.props.debounceTimeout;return u.createNotifier(_),u}return function _createClass(s,i,u){return i&&_defineProperties(s.prototype,i),u&&_defineProperties(s,u),Object.defineProperty(s,"prototype",{writable:!1}),s}(DebounceInput,[{key:"componentDidUpdate",value:function componentDidUpdate(s){if(!this.isDebouncing){var i=this.props,u=i.value,_=i.debounceTimeout,w=s.debounceTimeout,x=s.value,j=this.state.value;void 0!==u&&x!==u&&j!==u&&this.setState({value:u}),_!==w&&this.createNotifier(_)}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.flush&&this.flush()}},{key:"render",value:function render(){var s,i,u=this.props,w=u.element,j=(u.onChange,u.value,u.minLength,u.debounceTimeout,u.forceNotifyByEnter),P=u.forceNotifyOnBlur,B=u.onKeyDown,$=u.onBlur,U=u.inputRef,Y=_objectWithoutProperties(u,x),X=this.state.value;s=j?{onKeyDown:this.onKeyDown}:B?{onKeyDown:B}:{},i=P?{onBlur:this.onBlur}:$?{onBlur:$}:{};var Z=U?{ref:U}:{};return _.default.createElement(w,_objectSpread(_objectSpread(_objectSpread(_objectSpread({},Y),{},{onChange:this.onChange,value:X},s),i),Z))}}]),DebounceInput}(_.default.PureComponent);i.DebounceInput=j,_defineProperty(j,"defaultProps",{element:"input",type:"text",onKeyDown:void 0,onBlur:void 0,value:void 0,minLength:0,debounceTimeout:100,forceNotifyByEnter:!0,forceNotifyOnBlur:!0,inputRef:void 0})},24677:(s,i,u)=>{"use strict";var _=u(81214).DebounceInput;_.DebounceInput=_,s.exports=_},22551:(s,i,u)=>{"use strict";var _=u(96540),w=u(69982);function p(s){for(var i="https://reactjs.org/docs/error-decoder.html?invariant="+s,u=1;u